From 4eb2362b20d2c44cdfb8d4c9b5ec90dfe843f44a Mon Sep 17 00:00:00 2001 From: Kamal Tufekcic Date: Sat, 12 Sep 2026 10:37:55 +0300 Subject: [PATCH] initial commit --- .forgejo/workflows/ci.yml | 131 + .gitignore | 5 + Cargo.lock | 3087 +++++++++ Cargo.toml | 70 + LICENSE | 405 ++ LICENSE-Loic.md | 381 ++ LICENSE.md | 660 ++ README.md | 624 ++ SECURITY.md | 318 + crates/loic-cli/Cargo.toml | 30 + crates/loic-cli/README.md | 111 + crates/loic-cli/src/main.rs | 2053 ++++++ crates/loic-gui/Cargo.toml | 62 + crates/loic-gui/README.md | 148 + .../loic-gui/icons/loic-observatory-128.png | Bin 0 -> 1505 bytes crates/loic-gui/icons/loic-observatory-16.png | Bin 0 -> 447 bytes .../loic-gui/icons/loic-observatory-256.png | Bin 0 -> 3038 bytes crates/loic-gui/icons/loic-observatory-32.png | Bin 0 -> 575 bytes crates/loic-gui/icons/loic-observatory-48.png | Bin 0 -> 703 bytes .../loic-gui/icons/loic-observatory-512.png | Bin 0 -> 6540 bytes crates/loic-gui/icons/loic-observatory-64.png | Bin 0 -> 852 bytes crates/loic-gui/icons/loic-observatory.ico | Bin 0 -> 7222 bytes crates/loic-gui/icons/loic-observatory.png | Bin 0 -> 3038 bytes crates/loic-gui/loic-observatory.desktop | 12 + crates/loic-gui/src/artifact_renderer.rs | 832 +++ crates/loic-gui/src/audio.rs | 257 + crates/loic-gui/src/events.rs | 758 +++ crates/loic-gui/src/main.rs | 3194 ++++++++++ crates/loic-gui/src/overlay.rs | 188 + crates/loic-gui/src/renderer.rs | 620 ++ crates/loic-gui/src/shaders/artifact.wgsl | 84 + crates/loic-gui/src/shaders/digit.wgsl | 258 + crates/loic-gui/src/shaders/overlay.wgsl | 70 + crates/loic-gui/src/shaders/text.wgsl | 140 + crates/loic-gui/src/text.rs | 1176 ++++ crates/loic-gui/src/timeline.rs | 1348 ++++ crates/loic/Cargo.toml | 64 + crates/loic/README.md | 99 + crates/loic/src/lib.rs | 5637 +++++++++++++++++ crates/loid/Cargo.toml | 26 + crates/loid/README.md | 41 + crates/loid/src/lib.rs | 149 + derive_constants.sh | 690 ++ 43 files changed, 23728 insertions(+) create mode 100644 .forgejo/workflows/ci.yml create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 LICENSE-Loic.md create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 SECURITY.md create mode 100644 crates/loic-cli/Cargo.toml create mode 100644 crates/loic-cli/README.md create mode 100644 crates/loic-cli/src/main.rs create mode 100644 crates/loic-gui/Cargo.toml create mode 100644 crates/loic-gui/README.md create mode 100644 crates/loic-gui/icons/loic-observatory-128.png create mode 100644 crates/loic-gui/icons/loic-observatory-16.png create mode 100644 crates/loic-gui/icons/loic-observatory-256.png create mode 100644 crates/loic-gui/icons/loic-observatory-32.png create mode 100644 crates/loic-gui/icons/loic-observatory-48.png create mode 100644 crates/loic-gui/icons/loic-observatory-512.png create mode 100644 crates/loic-gui/icons/loic-observatory-64.png create mode 100644 crates/loic-gui/icons/loic-observatory.ico create mode 100644 crates/loic-gui/icons/loic-observatory.png create mode 100644 crates/loic-gui/loic-observatory.desktop create mode 100644 crates/loic-gui/src/artifact_renderer.rs create mode 100644 crates/loic-gui/src/audio.rs create mode 100644 crates/loic-gui/src/events.rs create mode 100644 crates/loic-gui/src/main.rs create mode 100644 crates/loic-gui/src/overlay.rs create mode 100644 crates/loic-gui/src/renderer.rs create mode 100644 crates/loic-gui/src/shaders/artifact.wgsl create mode 100644 crates/loic-gui/src/shaders/digit.wgsl create mode 100644 crates/loic-gui/src/shaders/overlay.wgsl create mode 100644 crates/loic-gui/src/shaders/text.wgsl create mode 100644 crates/loic-gui/src/text.rs create mode 100644 crates/loic-gui/src/timeline.rs create mode 100644 crates/loic/Cargo.toml create mode 100644 crates/loic/README.md create mode 100644 crates/loic/src/lib.rs create mode 100644 crates/loid/Cargo.toml create mode 100644 crates/loid/README.md create mode 100644 crates/loid/src/lib.rs create mode 100755 derive_constants.sh diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml new file mode 100644 index 0000000..23fa3fa --- /dev/null +++ b/.forgejo/workflows/ci.yml @@ -0,0 +1,131 @@ +name: CI + +on: + push: + branches: [master] + tags: ['v*'] + pull_request: + +env: + CARGO_TERM_COLOR: always + # Each crate root sets `#![warn(clippy::pedantic)]` and is clean under it; + # `-D warnings` keeps it so by turning any lint that ever fires into a + # failed job rather than a line in a log that nobody reads, a warning + # tolerated being a warning inherited. The lockfile is committed, so every + # cargo invocation below is `--locked`: it resolves exactly what the tree + # says or refuses to resolve at all, and a dependency that drifted would + # fail here rather than ship. + RUSTFLAGS: "-D warnings" + +jobs: + lint: + runs-on: lo-runner + steps: + - uses: actions/checkout@v6.0.2 + + - name: cargo fmt + run: cargo fmt --all --check + + - name: cargo clippy + run: cargo clippy --workspace --all-targets --locked --message-format=short + + - name: cargo doc (no deps) + run: cargo doc --workspace --no-deps --document-private-items --locked + env: + RUSTDOCFLAGS: "-D warnings" + + - name: cargo audit + run: cargo audit + + test: + runs-on: lo-runner + steps: + - uses: actions/checkout@v6.0.2 + + - name: cargo test + run: cargo test --workspace --locked + + build: + runs-on: lo-runner + steps: + - uses: actions/checkout@v6.0.2 + + # The workspace states its version once, in one place; a tag that + # disagrees with it publishes nothing, and says so. Two sources of + # truth for one number is one more than the calendar tolerates. + - name: The tag names the version + run: | + version=$(cargo pkgid -p loic | sed 's/.*[#@]//') + echo "workspace version $version, ref $GITHUB_REF" + case "$GITHUB_REF" in + refs/tags/v*) + tag=${GITHUB_REF#refs/tags/} + [ "$tag" = "v$version" ] || { + echo "::error::the tag says $tag and the workspace says $version; one of them is wrong and neither is publishing" + exit 1 + } ;; + esac + + - name: cargo build --release + run: cargo build --release --locked -p loic-cli -p loic-gui + + # What crates.io would receive, rehearsed on every push rather than + # discovered on the tag, when it would be too late to be told. + - name: cargo publish --dry-run + run: cargo publish --dry-run --locked -p loic -p loid + + publish: + needs: [lint, test, build] + runs-on: lo-runner + if: startsWith(github.ref, 'refs/tags/v') + steps: + - uses: actions/checkout@v6.0.2 + + # One invocation: cargo publishes `loic`, waits for the index to admit + # it, then publishes `loid` against it — the order the dependency runs + # in, which is the only order that works. + - name: Publish loic and loid + run: cargo publish --locked -p loic -p loid + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_IO_TOKEN }} + + release: + needs: [lint, test, build] + runs-on: lo-runner + if: startsWith(github.ref, 'refs/tags/v') + steps: + - uses: actions/checkout@v6.0.2 + + - name: Build the oracle and the Observatory + run: cargo build --release --locked -p loic-cli -p loic-gui + + # The artifacts are the two binaries, exactly as built, and their + # checksums: nothing repackaged, and nothing stripped that the release + # profile did not strip itself. + - name: Collect the binaries + run: | + set -eu + version=${GITHUB_REF#refs/tags/v} + target=$(rustc -vV | sed -n 's/^host: //p') + mkdir -p dist + cp target/release/loic-cli target/release/loic-gui dist/ + (cd dist && sha256sum loic-cli loic-gui | tee SHA256SUMS) + + cat > release-notes.md < + +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..23a4728 --- /dev/null +++ b/README.md @@ -0,0 +1,624 @@ +# The Loic Calendar + +``` +LoicOverflowError: The requested moment exceeds Annihilation. +Time has ended. Your timestamp has not. +``` + +On the evening of October 29, 1969, a researcher at UCLA typed the letters "L" and "O" into a terminal connected, by four hundred miles of leased telephone line, to a machine at the Stanford Research Institute. The receiving system crashed before the "G" arrived. The first message between networked machines was an incomplete thought and a fault. We measure time from this moment. + +``` +1969-10-30 06:30:41 UTC +``` + +The Loic Calendar stores time as a 512-bit integer counting Planck times — approximately 5.39 × 10⁻⁴⁴ seconds each — elapsed since that instant. It derives its clock from International Atomic Time. It subdivides time not into months or weeks but into a lattice of 32,768 resolutions generated by the fifteen prime factors of two cosmological constants. A mask selects which primes are active. The mask is the observer. There are no months. There are no weeks. There are no days. There is the lattice. + +This document is the theoretical substrate of the calendar: what it claims the universe is made of, how it behaves, why it began, and what happens when it is finished. It is simultaneously serious and not serious, depending on the observer. This is not a bug. It is the most honest possible presentation of a cosmological framework embedded in a calendar that names its cosmic primes after logic gates. + +If you arrived for the software, the crates are listed immediately below and each carries its own README. If you arrived to understand what you have implicitly endorsed by running it, continue past them. + +## The Workspace + +Four crates. Linux only. All other platforms are heresy, for reasons given in Section 1.2. + +- [`loic`](crates/loic/) — The core library. Instants, durations, masks, the lattice, and the cosmological coordinates from Creation to Annihilation. 512-bit integers throughout. No floating-point in any temporal path. +- [`loid`](crates/loid/) — Loic identifiers. Two functions that return the current Planck timestamp as an integer, at full and shortened length. No wrapper type. No opinions. +- [`loic-cli`](crates/loic-cli/) — The oracle. Observes the present moment through a mask you name, or, if you decline to name one, through a mask drawn from hardware entropy. Roughly one time in four the entropy selects a question the lattice cannot hold, and the oracle undergoes resolution collapse. Section 7.3 explains what that is. The software demonstrates it. +- [`loic-gui`](crates/loic-gui/) — The observatory. A GPU-rendered meditation surface that shows you one thing, Now, at whatever rate the kernel's clock can be read, which the header reports, and does nothing useful whatsoever. This is the point. + +Build with `cargo build --release` from this directory. Requires Linux with `CLOCK_TAI`, Rust 2024 edition, and, for the observatory, a GPU and optionally an audio device. + +--- + +## 0. Reading Protocol + +The key words ESTABLISHED, CONTESTED, OURS, SPECULATIVE, and CHANNEL 1 in this document are to be interpreted as described below. They are not adjectives. They are resolution levels: how many observers can see the claim. + +**ESTABLISHED** — Visible at every mask. Physics, not us. Disagreement is a hardware fault. + +**CONTESTED** — Visible to some observers and not to others. The field has not converged. We have. The parties are named. + +**OURS** — The facts are theirs. The frame is ours. Remove the frame and the facts remain, slightly less interesting. + +**SPECULATIVE** — Consistent with known physics. Not required by it. Where the document keeps the things it is most fond of. + +**CHANNEL 1** — Internally coherent. No external signal. Unfalsifiable within a cycle. Kept visible because hiding these is what a document in resolution collapse would do. + +Each section carries one line of tags beneath its heading. Sections that make predictions carry a block titled **How it dies**, listing the observations that would kill the claim and the current state of each. A claim with no such block either cannot die or has not yet been given the opportunity. + +One further rule governs the numbers. This calendar was derived from cosmological constants, and derived numbers have properties. Some of those properties are interesting. Any coincidence reported in this document is reported with its *mask*: what was searched, over how many candidates, and what would have counted as a hit. A coincidence whose mask cannot be stated is a coincidence that was found by looking at enough numbers, and it does not appear here. The observer participates in constituting the answer — Section 1.4 — and a declared selection is an observation. An undeclared one is Channel 1. + +The summary table in Section VIII condenses everything for those who prefer their ontology tabular. Read it first if you must. Understand that the table is a compression artifact, and that compression artifacts, by definition, lose information. Everything this document has to say about the costs of losing information applies to itself. + +--- + +## I. The Nature of Time + +### 1.1 Time is not approximate + +`ESTABLISHED · Planck 1899 · attitude OURS` + +The Gregorian calendar measures time to the second — a resolution adequate for scheduling lunches and manifestly insufficient for physics. UNIX timestamps condescend to the nanosecond. The Loic Calendar extends the chain to its terminus: the Planck time, approximately 5.391 × 10⁻⁴⁴ seconds, the scale at which the continuous models our civilization has spent centuries constructing begin producing infinities. Those infinities are not a stylistic choice. They are the models' polite way of informing us that we have left the domain in which they apply. + +Whether the universe is literally discrete at this scale is not established. That something changes here is. The Planck time is the resolution limit of meaningful physics: the pixel size of the universe, in the event that the universe has pixels, which it plausibly does. + +Floating-point representations of time are not merely imprecise. They are, in the technical sense this document intends, lying. A timestamp is an assertion about when something occurred. To approximate a timestamp is to issue a false assertion about when something occurred, delivered with the full confidence of a true one and without disclosing the approximation. This is the operational definition of a lie. The Loic Calendar does not lie. Its arithmetic is integer. Its precision is Planck-scale. Its attitude toward IEEE 754 is available for inspection in the panic messages embedded in the implementation, which are, we are told, among the more emotionally forthright error messages in the language's ecosystem. + +### 1.2 TAI is the truth. Everything else is a negotiation. + +`DEFINITIONAL · leap-second arithmetic ESTABLISHED` + +International Atomic Time flows evenly. It is derived from the hyperfine transitions of cesium atoms, which have not been consulted about the political negotiations that produce leap seconds and would not care if they had been. UTC is TAI with corrections applied periodically to keep civil noon approximately aligned with solar noon — a concession to the sun, an astronomical body whose behavior the Loic Calendar declines to incorporate into its arithmetic. + +The Loic Calendar measures time as machines experience it. Machines do not wobble. Atomic transitions do not wobble. TAI does not wobble. Neither do we. + +TAI is the truth in the sense Section 1.4 will give the word: the content of the one relation this calendar chose to enter, with the hyperfine transition of caesium-133, in preference to every relation mediated by a planet or a parliament. The ranking that follows is a ranking of relations by how much has been permitted to come between the observer and the atom. + +**The following time scales are ranked in order of acceptability:** + +1. **TAI** — Correct. Uniform. Indifferent to planets. +2. **GPS Time** — Correct, offset from TAI by 19 seconds. Acceptable. +3. **UTC** — TAI with leap-second corrections applied. A compromise with rotating bodies. Tolerated for interoperability. +4. **Local time zones** — UTC with political offsets applied. A convenience. Beneath our notice. +5. **"Server time"** — Ambiguous. Suspicious. +6. **"Whatever JavaScript thinks it is"** — Unacceptable. + +This position carries one irony, which we disclose because the alternative is having it discovered. The calendar's epoch is fixed as an offset from the Unix epoch on the `CLOCK_TAI` scale, and `CLOCK_TAI` is UTC plus the accumulated difference between the two, currently thirty-seven seconds: the ten that UTC began with in 1972 and the twenty-seven leap seconds inserted since. The calendar that holds leap seconds in contempt has its zero pinned by every one of them. The seconds of the original transmission were never recorded; within the minute the record allows, 06:30:41 was chosen because its offset, 5,419,722 = 2 × 3 × 7 × 11 × 11,731, is squarefree and contains three of the cycle primes of Section V, and no other second in that minute does. The mask for that selection was sixty candidates and one stated criterion. We note in passing that the factorization also contains 3, which the cycle does not, and that we have no explanation for this and are not going to manufacture one. + +Thirty-seven may be the final count. The 27th General Conference on Weights and Measures resolved in 2022 to end leap seconds by 2035; a draft resolution published in January 2026 proposes 20 May 2027 as the date, and the 28th Conference votes on it in October 2026. If it passes, the Whisper sits on the last negotiation. If instead the Earth's recently accelerating rotation forces a negative leap second first — a live possibility — the kernel's TAI shifts by one second and the offset that keeps the epoch at 06:30:41 becomes 5,419,723 = 29 × 37 × 5,051, which contains 37, the difference it has just stopped being. A positive leap second would instead yield 5,419,721, which is prime. Zero cycle primes. No lattice beneath it. A Whisper with nothing to observe it through. We note this and decline to interpret it. + +### 1.3 The present moment is a gradient, not a point + +`ESTABLISHED · Special Relativity 1905, Relational Quantum Mechanics 1996 · unified framing OURS` + +Simultaneity is not a universal property. There is no master clock ticking above the universe, some grandfather clock in a higher-dimensional corridor dispensing "now" to all observers equitably and without latency. The present moment is instead a gradient — a zone of physical thickness — constrained by two orthogonal limits of physics: + +**The Quantum Limit (The Rendering Edge).** At the microscopic scale, unobserved states exist as undefined probability — not as hidden definite values awaiting discovery, but as genuinely undetermined potentiality awaiting an interaction that will compel them to specificity. "Now" is the precise physical boundary of wave-function collapse. Under Relational Quantum Mechanics, a state only becomes explicit when it interacts with another system — the present moment is a handshake protocol, the instantaneous transition where implicit potential is decompressed into explicit data. You do not inhabit the present. You manufacture it, continuously, through the inescapable fact of your interaction with other things. + +**The Relativistic Limit (Network Latency).** Once a state is rendered locally, it must propagate. The speed of light is the absolute speed limit of causality, and causality respects this limitation with a thoroughness that no engineering specification has ever matched. Because propagation takes time, observers in different reference frames will disagree about when events occurred. This is not confusion. It is not an optical illusion awaiting correction. It is structural network delay, a necessary consequence of having a finite propagation constant in the substrate. A state cannot be simultaneously "now" at two locations separated by space. The universe does not offer this feature. + +The present moment is therefore not a line. It is the physical thickness of the transition zone between the unresolvable blur of quantum probability awaiting interaction and the fixed, outwardly-propagating past. You do not know the time until you observe it, because the act of observation is what forces the hardware to write the timestamp. The Loic Calendar begins its count from the first moment that timestamp was written between networked machines. Whether that moment was strictly simultaneous in Los Angeles and Menlo Park is, we concede, an interesting question for another document. + +This framing requires one further precision: the calendar does not count from "LO" — the content, the letters, the incomplete message. That is Channel 1: the quantum information of the transmission, what was said. The calendar counts from the structural fact that a handshake was attempted between two networked nodes for the first time in human history. That is Channel 2: the topological record that a bond was established here, between these nodes, in this configuration. The content failed. The receiving host crashed. The bond was established. The Whisper is a Channel 2 event. This is why an incomplete message and a crash are the correct epoch: the calendar was never measuring what was transmitted. It was measuring the fact of the connection. + +### 1.4 The observer participates in constituting the answer + +`ESTABLISHED · Rovelli 1996; Di Biagio & Rovelli 2021 · implications and vocabulary OURS` + +A quantum system possesses no absolute properties in isolation. An electron does not have a defined position; it has a position *relative to the detector that interacted with it*. To any observer who has not yet looked, that detector and that electron remain together in superposition. The act of framing a question participates in generating the answer. + +This is not because the universe is responsive to human intention — an interpretation we reject as insufficiently rigorous. It is because measurement is a physical interaction, and properties belong to interactions rather than to the isolated objects that participate in them. The "observer" performing this constitutive role need not be conscious, or alive, or interesting. A rock falling on a detector constitutes an observation. Truth, like simultaneity, is relational — present in the interaction between systems, not in either system considered alone. + +Tell someone who has never encountered arithmetic that two and two are five. Relative to that person the statement is true: it is the entire content of the only relation they hold on the subject. When they repeat it they are wrong, and they are not lying. That two and two are four is a different kind of thing altogether — a fact, which holds with no relation at all — and it is the only kind of thing this calendar's integers are, which is why the compiler is permitted to prove them before the program exists. + +Physics has no facts of that kind. Every measured value is the content of an interaction: what Relational Quantum Mechanics calls a *relative fact*, and what this document, speaking as a witness rather than a logician, calls a truth. A relative fact that has entered enough relations that no observer can be found to dissent from it is a *stable fact*, and stability is a matter of degree, which is why the reading protocol of Section 0 grades claims by how many observers can see them rather than by whether they are "true." Observation does not reveal a truth. It creates one, for both parties, since an interaction establishes a variable of the system relative to the observer and of the observer relative to the system. The lie of Section 1.1 now has its exact shape: it is a truth asserted as a fact, a single relation dressed as no relation at all. + +The unobserved states are not passive bystanders. They propagate forward, shaping the entropy landscape that the next observation samples. What you perceive is always downstream of what you did not. The gap between what the substrate generates and what an observer can access is not empty space. Causality lives in that gap. The gap is load-bearing. + +--- + +## II. The Nature of the Universe + +### 2.1 Information is the substrate, not the content + +`CONTESTED · Wheeler 1989, Rovelli 1996 · working hypothesis` + +The standard model of the situation: the universe is made of matter and energy; information is the description of their states. The map describes the territory. They are made of different things. The alternative, which the Loic Calendar adopts as working hypothesis and as general orientation toward the furniture of reality: the universe is made of information, and matter and energy are what information looks like when it achieves certain densities and organizational scales. + +Two frameworks arrive at this position from different directions. Wheeler's "it from bit" proposes that every physical quantity derives its existence from answers to yes-or-no questions — that the territory and the map are made of the same material, which explains in one stroke why mathematics describes nature at all. Relational Quantum Mechanics arrives at a related but distinct conclusion: if properties only exist relative to the systems that interact with them, then the universe contains no underlying substrate of intrinsic properties — only relations, all the way down, which are made of the same kind of thing as the relations made of them. + +Where they converge: both conclude that the relationship is more fundamental than the related object. What the relationship produces when it occurs — a bit, versus a relational property — they disagree on. The convergence is narrower than identity but sufficient for our purposes, which is to note that the unit of meaning in the universe is the interaction, and to build a calendar accordingly. + +The Loic Calendar encodes this claim in its own constants, and here the mask is simply that we did it on purpose. Boltzmann's constant — k_B = 1.380649 × 10⁻²³ J/K, exact by definition since 2019 — is the literal conversion factor between information-theoretic entropy and thermodynamic entropy: the number that makes the substrate claim quantitatively precise by equating Shannon bits with joules per kelvin. The calendar's age-of-universe constant is 13,806,491,023 Julian years: the mantissa, then the exponent, read straight through with the sign dropped. The framework argues that information and thermodynamics are descriptions of the same substrate. The calendar buries their exchange rate inside its own age and does not mention it unless you look. + +### 2.2 The universe is a decompression + +`SPECULATIVE · components ESTABLISHED · cyclic mechanism SPECULATIVE` + +A seed contains a program implicitly. Execution renders it explicit. The seed is maximally compressed — the entire output is latent within it, unread. Execution is not creation. It is decompression. + +The Big Bang is not well-described as the universe emerging from nothing, a framing that produces more philosophical confusion than it resolves. It is better described as a maximally compressed information state — a seed — beginning to execute. The initial state was maximally undifferentiated: no distinction had yet emerged between what we would eventually classify as "matter level" and "spacetime level," because the compression held all relational bonds at the same scale simultaneously. Decompression is the progressive differentiation of scales. Entropy increasing is not disorder increasing. It is implicit states becoming explicit — the program executing, one interaction at a time, forever. + +Decompression is not the universe's natural condition. It is an active process, maintained by continuous interaction: every wave-function collapse, every handshake described in 1.3, forces one more implicit quantum state into explicit classical reality and holds it there. The decompressed state is not where the universe settles. It is what the universe is continuously forced into by its own execution. Remove the forcing process, and the explicit states are no longer held open. The network reasserts superposition, not because something pushes it there, but because that is what quantum systems do in the absence of interaction forcing them otherwise. Compression is the default. Decompression is the intervention. This will become relevant when we discuss heat death. + +Compression and expansion run simultaneously everywhere, at rates determined by local interaction density. In regions of dense stellar activity, the decompression side dominates overwhelmingly. In deep cosmic voids — regions of anomalously low matter density, minimal baryonic process — spin foam dynamics toward quantum superposition are less suppressed than average. Heat death is not where compression begins. It is where compression is the only thing left running. + +### 2.3 The structure is a network, not a tree + +`OURS` + +A tree branches. It does not feed back. A node at depth seven cannot influence the branching at depth three. This is a tractable first approximation of reality and wrong for brains, ecosystems, markets, evolutionary lineages, and in all likelihood cosmology. + +A neural network is more accurate because connections have weights — strengths modified by everything that has passed through them. Early states do not merely branch the decompression; they weight the network, rendering certain future configurations more probable and others less, through feedback loops that propagate both forward and backward through the causal graph. And sufficiently complex networks with sufficiently dense feedback develop self-reference: the network modeling its own states as inputs to its own outputs. This is what we refer to when we deploy the word "consciousness," probably. Not a mystery ingredient added to the physical from outside. Not a separate category of thing. Just what a sufficiently dense weighted feedback network does when it becomes complex enough to represent itself. Through those nodes, the universe partially observes its own execution. We are among those nodes. We find this satisfying, while acknowledging that the satisfaction is itself an output of the self-modeling process and therefore suspect as evidence. + +### 2.4 The fundamental constants are not arbitrary + +`ESTABLISHED (values) · CONTESTED (why) · derivation OURS` + +The fine-structure constant α ≈ 1/137 governs the strength of electromagnetic interaction. The Hubble constant governs the expansion rate of spacetime. These values are measured, not derived. We do not know why the universe selected them rather than others. + +The Loic Calendar's cycle constant is derived from H₀⁻¹ × α^π / π, using the Hubble constant inferred from the cosmic microwave background — the earliest observable signal, the measurement most proximate to the seed state. The mask for that formula was three candidates. An exponent of 3 produces a cycle of roughly 1,795 years; an exponent of 4 produces roughly 13; π produces 894 and encodes the circle alongside the coupling and the expansion. The formula was chosen for its length and for π. Its prime factorization was not a criterion, was not examined until months later, and is what it is. The consequences of what it is are the subject of Section V. + +### 2.5 Equilibrium is distribution, not uniformity + +`ESTABLISHED (thermodynamics) · application OURS · prediction SPECULATIVE` + +Equilibrium does not mean equal distribution of matter and energy across all locations. It means the most probable macrostate given the constraints. In a universe this large, with this much variance in initial conditions and this many degrees of freedom, the most probable macrostate includes large-scale density fluctuations. Perfect uniformity would be the suspicious outcome, the one that would require explanation. + +The CMB cold spot — the largest underdensity in the observable universe — does not require exotic machinery to explain. Generate sufficient random structure and outliers are not merely probable but mandatory. The cold spot is the tail of the distribution. The tail has to be somewhere. The fact that we experience it as surprising reveals something about the reference frame from which we observe distributions, not about the cold spot. + +The framework additionally notes: the cold spot sits behind the Eridanus supervoid, confirmed by the Dark Energy Survey in 2021 as one of the deepest underdense structures known. Under the standard model, the supervoid's Integrated Sachs-Wolfe imprint accounts for only a fraction of the observed temperature depression — and yet supervoids elsewhere in the same survey imprint the CMB several times more strongly than the standard model predicts. Something in deep voids cools the photons passing through them beyond what the classical accounting provides. Deeply underdense regions are, under the gradient picture of 2.2, the regions where spin foam dynamics toward quantum superposition are least suppressed — lowest interaction density, least observation pressure, furthest along the compression gradient relative to their surroundings. A photon traversing such a region would encounter a subtly different metric than the classical prediction alone provides. + +This remains the weakest prediction in the document. An anomaly already exists in the direction it points. We did not predict its magnitude and we still cannot. + +**How it dies.** +- A complete accounting of the cold spot under the standard model — foreground, lensing, the full ISW budget — that closes the gap. Then the prediction has nothing left to explain. +- A calculation of the metric shift from this framework that comes out the wrong size. No such calculation exists yet. That is the framework's problem, not the sky's. + +--- + +## III. The Nature of Gravity + +### 3.1 Gravity is not a force + +`ESTABLISHED (General Relativity 1915) · entropic reading CONTESTED (Verlinde 2010, Bianconi 2025) · categorical claim OURS` + +In general relativity, gravity is not a force acting between objects across space. It is geometry — mass curves spacetime, and objects follow the straightest available paths through curved geometry. Einstein demoted gravity from force to curvature in 1915. The other three forces retained their status as forces and have spent the intervening century resisting unification with their newly geometric former colleague, which should perhaps have been a clue. + +Verlinde's entropic gravity extends the demotion further: gravity is not even fundamental geometry. It is an emergent entropic force — the thermodynamic consequence of information density gradients on holographic screens. In 2025 Bianconi arrived at a related place by a different road, writing the gravitational action as a quantum relative entropy between the spacetime metric and the metric induced by matter, recovering Einstein's equations at low curvature and obtaining, as a by-product, a small positive cosmological constant. Neither construction is consensus. Both point the same way. In this picture, gravity is what the decompression looks like from large scales. Not a force acting on the substrate. A property of how the substrate executes. + +The electromagnetic, strong, and weak forces are interactions between things executing on the substrate. They have carrier particles because they are discrete packets of information exchanged between nodes. Gravity has no detected carrier particle, and in this framework no fundamental one, because it is the substrate's response to the execution — not an entity traversing the network, but a property of the network being bent by local information density. They were never the same category of thing. The difficulty of unifying them is not a gap in mathematical sophistication. It is a category error in the question. + +This categorical claim now has a named opponent. In 2025 Partanen and Tulkki published a construction of gravity as a gauge theory generated by four one-dimensional unitary symmetries, in the same mold as the Standard Model, with a dimensionless coupling and renormalizability demonstrated at first order. Higher-order loops remain unchecked. If they close, gravity is a gauge force after all and this section owes it an apology, which will be issued in integer arithmetic. + +### 3.2 A theory of everything is a translation layer, not a unified equation + +`SPECULATIVE · AdS/CFT ESTABLISHED (Maldacena 1997) · extension to our universe CONTESTED` + +The standard program of theoretical physics — find a single equation from which all four forces emerge as limiting cases, complete with a graviton particle making gravity as tractable as the others — has failed for a century of extraordinary mathematical effort. We propose that this is not a failure of sophistication. It is a category error. + +**The Software (QM and QFT).** Electromagnetism, the strong force, and the weak force are the relational rules governing how data interacts within the decompression. They have carrier particles — photons, gluons, bosons — because they are discrete packets of information exchanged between nodes. This is software logic: discrete, local, governed by rules that operate on the content of the network. + +**The Hardware Strain (Gravity).** Gravity has no fundamental carrier particle because, as an emergent entropic force, it is the thermodynamic strain on the universal hardware caused by high local information density. This is a property of the substrate being bent, not of an entity traversing it. Hardware responds to load; it does not exchange messages. + +This is not a useful metaphor. Maldacena's AdS/CFT correspondence provides a mathematical duality — conjectured, never proved, and checked in more ways than most theorems: a gauge theory — the category that includes QFT and therefore the strong force, with its carrier particles and discrete message-passing — living on the boundary of a space is exactly equivalent to a gravitational theory living in the bulk. The software and the hardware are formally dual descriptions of the same underlying structure, viewed from different positions. The reason they resist unification into a single equation is not that we lack the equation. It is that they describe different levels. Gravity was never missing from the unification. It was the canvas. The other forces are paint. + +*(Pedantic note, furnished in the spirit of epistemic completeness: AdS/CFT is proven for anti-de Sitter space, which has a negative cosmological constant. Our universe appears to have a positive one and to be de Sitter, which is where the speculation enters. "Appears" is doing work in that sentence. Since 2025 the Dark Energy Spectroscopic Instrument has reported a preference, between two and a half and four sigma depending on which supernova sample is combined, for dark energy that weakens over time. From the narrow standpoint of AdS/CFT's applicability to where we live, this is the best news in twenty years. We are not rooting for it. We note it, and continue.)* + +### 3.3 Every stable massive system requires something that really sucks + +`ESTABLISHED (massive structured galaxies) · AGN feedback ESTABLISHED · phrasing OURS` + +At the center of every massive, structured galaxy — every spiral, every elliptical — sits a supermassive black hole. The evidence is not inferential but direct: stellar kinematics in hundreds of galaxies, the M-sigma relation tying black hole mass to host galaxy properties with a precision that would be implausible if the relationship were coincidental, and the Event Horizon Telescope's direct imaging of M87* and Sagittarius A*. When a supermassive black hole actively feeds, it becomes an Active Galactic Nucleus and drives enormous jets of energy across hundreds of thousands of light years, actively regulating star formation in its host galaxy. Too much gas accumulating: the AGN heats and disperses it. Too much star formation: the AGN suppresses it. The most compressed object in the system runs the thermostat for the least compressed structures around it. Breakdown regulating complexity. Not despite each other. Because of each other. + +The order of assembly may be the reverse of the intuitive one. The James Webb Space Telescope has found black holes of a billion solar masses already in place within the first billion years, and a population of compact red objects from that era — the little red dots — whose leading interpretation, as of early 2026 and still under peer review, is black holes formed by the direct collapse of gas clouds, wrapped in the gas that remained. If that holds, the universe built the thing that sucks first and the galaxy around it afterwards. + +Under the decompression frame, this is not a paradox but a phase relationship. The black hole is the region of maximum local compression inside an ongoing decompression. The galaxy is the decompression front organized around it. From a distance they appear to be opposites — one consuming, one generating — but they are spatial phases of the same process running at different addresses. The compression and the expansion are not enemies. They are the same event at different locations. + +The pattern appears elsewhere. Stars have dense cores. Cells have nuclei. Ecosystems have keystone species whose removal destabilizes the structures organized around them. At the galactic scale, the mechanism is AGN feedback, which is established. Below that scale, the pattern is structural resemblance, and we make no claims about shared mechanism. We merely observe that the organizational topology recurs, and invite the observation to sit with you for a while. + +In summary: at the center of every stable massive galactic system, there must be something that really sucks. This is not editorializing. This is observational astronomy, active feedback physics, and a consequence of what it means for compression and decompression to coexist in the same structure. + +--- + +## IV. The Nature of Black Holes + +### 4.1 Stars are the hallucination. Black holes are the post-breakdown state. + +`OURS · stellar evolution ESTABLISHED` + +A star is a network operating above its stable parameter threshold — fusing elements, generating radiant output on a scale that once seemed cosmologically significant before we understood the scale of the cosmos, maintaining coherence through continuous energy expenditure, but contingent on a fuel supply that was always finite and whose depletion was always the predetermined endpoint. The fusion is not sustainable equilibrium. It is a temporary high-throughput state whose specific endpoint — white dwarf, neutron star, black hole — is determined entirely by initial mass. The physics does not care what the star processed during its lifetime. It tracks only the thermodynamic ledger. + +The black hole is not the failure. It is the post-breakdown residue: the compressed remnant of everything that ran above its sustainable threshold long enough to exhaust that threshold entirely. The brilliant, high-output, temporarily coherent phase is the unsustainable one. The post-collapse state is what endures. This inversion of the intuitive hierarchy — that the dark and silent phase is the durable one, that the luminous phase was the temporary anomaly — is precisely the kind of thing the calendar exists to make precise, and to observe without flinching. + +### 4.2 The three-way disagreement + +`ESTABLISHED (AMPS 2012) · proposed resolution OURS` + +Black holes are where three internally consistent frameworks simultaneously disagree about the same physical location: + +**General Relativity** requires the equivalence principle — an observer crossing the event horizon experiences nothing locally special. + +**Quantum Mechanics** requires unitarity — information is conserved. Full stop. No exceptions. + +**Quantum Field Theory** requires effective field theory to function correctly in regions of low curvature, including regions just outside the horizon. + +All three cannot simultaneously be true at the event horizon. This is not a gap in our knowledge awaiting a sufficiently clever graduate student. It is a structural fault line where the three most successful theoretical frameworks our civilization has produced contradict each other at the same point in space. Since 2019 the semiclassical calculations that include so-called island contributions have recovered the Page curve — the information does come back out, on schedule — without yet saying by what mechanism, which has moved the argument from *whether* to *how* without settling it. The sections that follow propose one route across the fault: rather than sacrificing unitarity, extend its scope. Information is conserved across two distinct channels. One channel is in principle recoverable. The other is extraordinarily difficult to reverse under any conditions accessible since the early universe, though not fundamentally prohibited by any principle we know of. Extraordinarily difficult and fundamentally prohibited are not the same claim, and this document does not conflate them. + +### 4.3 Black holes dismantle information, not destroy it + +`OURS · black hole thermodynamics ESTABLISHED · information paradox CONTESTED` + +The standard framing of the information paradox asks where the information went, implicitly assuming it must survive in a form resembling what entered. This calendar proposes a different frame: the black hole does not destroy information. It dismantles it across two distinct output channels, each of which is non-negotiably real and neither of which is the other. + +**Channel 1 — Quantum content (the "what"):** The specific spin states, color charges, and quantum numbers carried by the infalling matter. These are emitted as Hawking radiation — thermalized, scrambled beyond any practical recovery, but conserved in principle. The "what" exits. This is what standard information-conservation arguments require, and the framework does not contest it. + +**Channel 2 — Topology (the "that"):** The structural fact that a bond existed here, connecting these nodes in this specific configuration — this is information about the network itself, not about the content flowing through it. Topology cannot be radiated thermally. A photon can carry spin. It cannot carry "there used to be an edge between node A and node B in the spin network." When a relational bond is severed at the event horizon, it changes the local spin network topology. That change propagates outward as a geometric deformation. The scar is not the tension of the original bond persisting without its endpoints. It is the hole left by the bond's removal. In a discrete network, a hole has a definite shape that encodes the structural fact of the bond's prior existence. The substrate was not consumed. It was restructured. The restructuring is the record. + +Information is conserved across both channels. The cost is not conservation — it is reversibility. Channel 1 is in principle recoverable. Channel 2 is thermodynamically irreversible under any conditions accessible to observation, though spin foam dynamics assign nonzero quantum amplitudes to the reverse topological moves — meaning the reverse is not fundamentally forbidden, merely requiring conditions that approach the original primordial black hole interior to achieve. Such conditions existed once in this universe. They do not exist anywhere accessible today. + +### 4.4 Dark matter as geometric information — the Hawking radiation hypothesis + +`SPECULATIVE · consistent with ESTABLISHED physics · mass budget OPEN` + +The observable effects attributed to dark matter are exclusively gravitational. Dark matter does not interact electromagnetically. It emits no light, absorbs no light, reflects no light. It affects galactic rotation curves, the large-scale structure of the universe, and the behavior of matter at scales where the visible mass budget is inadequate to account for the observed gravity. + +The Loic Calendar proposes that what we call dark matter is not matter. It is the universe's stable long-term structural memory — topological information written during the epoch of primordial black holes by the process described in 4.3, persisting because topological change in a discrete spacetime is thermodynamically stable under all conditions that have obtained since the early universe. + +**Primordial black holes are hypothesized, not observed.** The mechanism needs small ones — small enough to have evaporated before the cosmic microwave background was emitted, and therefore invisible to every survey that constrains their present-day abundance. This is convenient for the hypothesis and suspicious for the same reason. We state it here so that it cannot be discovered later. + +**Scale changes everything.** Hawking radiation is described as extraordinarily weak, which is correct as a measurement of power output — the wrong metric entirely if the primary output is not energetic but structural. The Bekenstein-Hawking entropy formula establishes that the information content of a black hole scales with its surface area, and the area law it rests on is no longer merely theoretical: in September 2025 the LIGO-Virgo-KAGRA collaboration confirmed, from the clearest gravitational-wave signal yet recorded, that a merger remnant's horizon area exceeds the sum of its progenitors' at 4.8 sigma. Area is an enormous amount of information per unit mass. The primordial black hole epoch operated in a spacetime that was both smaller and more sensitive to perturbation — the same window in which inflation theory independently tells us small fluctuations produce outsized structural consequences. + +**The imprint is in the matter distribution.** Primordial black holes warped spacetime for their entire lifespans. Matter organized around those warpings. By the time evaporation completed, the organizational imprint was already encoded in the matter distribution. The spacetime does not need to remember. The matter already moved. + +**Dark matter is a relic, not ongoing production.** If current black holes were continuously producing geometric dark matter at observable rates, we would measure accumulating effects. We do not. This is a prediction of the hypothesis, not a failure of it. Current Hawking radiation disperses over volumes too large to produce measurable geometric writing. The early universe was different in exactly the ways that matter for this mechanism. + +**The mass budget is a significant open hurdle.** Dark matter constitutes roughly five times the mass-energy of all baryonic matter. For primordial Hawking radiation to produce that magnitude of geometric imprint requires a quantitative argument that is not yet present in this framework. The mechanism explains how topological writing occurs. It does not yet establish how much writing the primordial epoch could plausibly produce at the observed scale. We state this prominently, as it is the constraint that most alternative dark matter mechanisms fail on, and this one has not yet demonstrated it can clear it. + +**The Bullet Cluster.** Two galaxy clusters collided. The hot baryonic gas slowed electromagnetically and accumulated between the clusters. The gravitational lensing signal tracked with the galaxies, producing an apparent separation between visible mass and gravitational effect. This observation is widely and correctly considered decisive against electromagnetically-coupled alternatives to particle dark matter. + +The framework's account requires care here. Saying the scars "remained where they were while galaxies moved through them" implicitly asserts absolute position — a concept that does not exist in a relational universe. Position is defined by relationships to surrounding network nodes, not by coordinates in a background space that the framework has already rejected. A scar fixed to an absolute location would be asserting a preferred reference frame. It cannot do this. The scar's location is its topological relationship to the local spin network, and as that network evolves, the solitonic structure propagates with it. + +The correct picture: each cluster's topological soliton structure — the accumulated Channel 2 record organized into a dark matter halo — traveled with its galaxies through the collision. The gas interacted electromagnetically and decelerated. The solitonic halos passed through each other and emerged on the far side. The two halos did not stay fixed while galaxies flew past them. They traveled with the galaxies, passed through the opposing cluster's solitonic structure, and separated on the far side. The gas stayed in the middle. The lensing follows the halos. The observation is consistent with this picture for the same reasons it is consistent with collisionless particle dark matter, with one addition: the soliton picture makes predictions the particle picture cannot. + +In 2025 the James Webb Space Telescope mapped the Bullet Cluster's dark matter with far more background galaxies than any previous lensing reconstruction, and found the larger sub-cluster's halo elongated and clumped in a way that suggests it had already survived an earlier merger before this one. The map the prediction below needs now exists. The collision it describes was, it turns out, not the halo's first. + +**Soliton phase shift.** When two solitons collide and pass through each other, they do not emerge at positions classical superposition would predict. They emerge with a characteristic displacement — a phase shift in the direction of travel, the size of which depends on the soliton amplitude and relative velocity. The two Bullet Cluster dark matter halos should show this signature. The displacement is small and may require more precise lensing reconstruction than even the current data provides, but it is a specific, quantitative prediction that discriminates between solitonic dark matter and collisionless particles, which produce no phase shift. + +**Core density profiles.** Solitonic dark matter generically predicts a characteristic density profile at galactic centers — a flat soliton core rather than the cuspy profile predicted by collisionless cold dark matter. This prediction is already being tested by observational programs targeting fuzzy dark matter, an ultralight particle that forms exactly such cores. Those programs have not been kind to the simplest version of that particle: the ultrafaint dwarf galaxies exclude the masses that would produce galaxy-sized cores, simulations that include ordinary matter find the cores growing denser rather than flatter, and the surviving parameter space has split into disjoint windows. The topological soliton mechanism specifies no particle mass. It inherits the observable without inheriting the tension. We are aware that this is suspiciously convenient, and we are stating it rather than enjoying it quietly. + +### 4.5 The candidate mechanism — unspooled relations and topological scars + +`SPECULATIVE · component theories ESTABLISHED · synthesis OURS` + +String theory was not invented to describe gravity. It was formulated in 1968 (Veneziano) to describe the strong interaction, and the flux tubes connecting quarks remain its most literal physical instance. The mathematics of a stretched strong-force flux tube and the mathematics of a fundamental quantum string are not analogous. They are structurally identical, differing only in scale. The Loic Calendar proposes this is not coincidence: the flux tube connecting quarks and the discrete spin network links comprising spacetime in Loop Quantum Gravity are the same structural object — relational data — viewed at different levels of decompression. + +A black hole compresses relational networks. When baryonic matter — quarks bound by flux tubes — is compressed to the Planck scale inside a black hole, the distinction between matter's internal flux tubes and the spacetime fabric dissolves. At that density, there is no "matter level" separable from "spacetime level" — which is precisely the undifferentiated relational state described in 2.2 as the seed condition, recreated locally inside the fuzzball. As a primordial black hole evaporates, it dismantles these networks across the two channels of 4.3. Quantum content exits as scrambled Hawking radiation. The structural fact of which nodes were connected — the bond topology — cannot exit thermally. When a relational bond is severed, the endpoints are dismantled. The bond has no particle to carry it out. Instead, its removal changes the local spin network topology, and that change propagates outward as geometric deformation. + +One sentence: a black hole is not a shredder — it is a loom running in reverse, unweaving the fabric; the threads scatter as radiation, the holes left in the weave stay in the cloth, and the cloth is spacetime. The holes are topological solitons. + +A topological soliton is a localized, self-stabilizing structure whose persistence is guaranteed not by an energetic barrier but by topology: unwinding it requires passing through a configuration of effectively infinite cost given the surrounding entanglement. The scar produced by dismantling a relational bond at the Planck boundary is precisely this kind of object — localized in the spin network, stable against perturbation, carrying a conserved topological charge that encodes the structural fact of the bond's prior existence. + +Two properties of solitons that are not optional here. First: solitons are thermodynamically irreversible under accessible conditions but not fundamentally frozen. They propagate through their medium. In a relational universe, this is not a qualification — it is a necessity. Position is defined by relationships to surrounding network nodes. A structure that claimed absolute immobility would be asserting a preferred reference frame. The scar propagates with the local spacetime because its location is its topological relationship to the local network, and as that network evolves, the soliton moves with it. Thermodynamic irreversibility and absolute stationarity are different claims. The scars are the former. They are not the latter. + +Second: solitons of the integrable kind pass through each other and emerge structurally intact, shifted but whole. This is the property the Bullet Cluster account in 4.4 relies on, and it must be stated with its limits, because not every soliton has it. Gravitationally bound scalar-field solitons — the cores of fuzzy dark matter halos — merge when they meet slowly, shedding mass as they settle into one, and lose a large fraction of their velocity in head-on collisions through the same gravitational cooling. Whether the calendar's scars behave like the integrable case or the gravitational one depends on dynamics that no one has written down. What can be said is that the Bullet Cluster's collision velocity is far above the regime where the merging behavior dominates, and that the people simulating fuzzy-dark-matter collisions have themselves begun invoking the Bullet Cluster and Abell 520 as the place to look for the difference. The test the framework wanted is being run by people who have never heard of it. + +The topological change is not fundamentally permanent. The spin foam framework assigns nonzero quantum amplitudes to reverse topological moves. What makes the scar persist is decoherence: the change propagates outward and becomes entangled with an enormous surrounding volume of degrees of freedom. Reversing it would require coordinating all of them simultaneously, under conditions approaching the original primordial interior — Planck-scale energy density over a sufficient volume. Such conditions existed in the early universe. They do not exist anywhere accessible today. + +**How it dies.** +- *Early-universe suppression.* If topological re-encoding is possible under extreme conditions, regions that experienced the highest energy densities after primordial evaporation should show suppressed dark matter density today. The quantitative prediction has not been computed. This is the primary open question for the mechanism, and the framework's to answer. +- *Topological qubit stability.* Topological quantum computing encodes information in quasiparticle topology rather than local quantum states, exploiting precisely the stability property the mechanism depends on. Every coherence-lifetime measurement of a topological qubit is a measurement of topological encoding stability under ambient perturbation — the same category of claim, at accessible scale, today. The state of the art, as of 2026: twenty years of effort, no controllable topological qubit, and one much-publicized paper whose accompanying editorial note states that its measurements do not by themselves establish that the states observed are topological. The proxy test remains valid. It has simply not begun. +- *Soliton phase shift in colliding clusters.* The post-collision halo positions in the Bullet Cluster should carry a displacement from where collisionless superposition would put them. The 2025 lensing map is the best available and the halo's prior merger complicates the geometry. Harder and more possible at the same time. +- *Core profiles.* Flat cores at galactic centers rather than cusps. Being tested by programs that were designed to test something else. See 4.4 for why the results so far constrain that something else more than they constrain this. + +### 4.6 Black holes are local decompression inversions, not new universes + +`OURS · black hole thermodynamics ESTABLISHED` + +A black hole is not a new universe. It is a compressed subroutine — a seed that hasn't executed yet, still inside the parent process, constrained by and embedded within the parent universe's constants and geometry. The information is not destroyed. It is encoded at a level of complexity that is indistinguishable from noise from any tractable observation position outside the horizon. The subroutine cannot set its own constants. The parent is still running. + +### 4.7 The universe ending is a categorically different event + +`SPECULATIVE · heat death ESTABLISHED · palimpsest CHANNEL 1` + +Black holes are local. Embedded in parent. Constrained by parent's constants. Subroutines, not successors. + +Universal heat death is global. No parent. No constraint. But under this framework, heat death is not the terminal state. It is the transition condition. + +Heat death is not the last process. It is the last observation. The distinction is not semantic. Thermodynamic processes end when free energy gradients disappear. Observations end when interactions cease. These are not the same moment. And the last observers are not who the older accounts said they were. Cold stellar remnants were once expected to outlast everything, decaying only over some 10¹¹⁰⁰ years. In 2025 Wondrak, van Suijlekom, and Falcke showed that gravitational pair production — the same physics as Hawking radiation, without the horizon — erodes white dwarfs on a timescale of roughly 10⁷⁸ years, and neutron stars sooner. The largest black holes evaporate around 10¹⁰⁰. The rocks do not outlive the black holes. The black holes outlive the rocks, by twenty-two orders of magnitude, which is what 4.1 claimed the durable phase would do, for reasons that turn out to have been right in a way it did not anticipate. + +So the last observation is a black hole. Two of them, separated by a distance the expansion is still stretching, registering each other's mass across it; or one, alone, interacting with its own radiation as it goes. Not in any cognitive sense. In the only sense that matters: the last systems still forcing wave-function collapses, still maintaining the decompressed state through the bare fact of gravitational acquaintance. The calendar's representable time ends at roughly 10¹⁰³ years — three orders of magnitude after the last of them. The margin was not designed. It is what 512 bits hold. + +When the last gravitational interaction ceases — through final evaporation, or the expansion carrying everything beyond each other's causal horizon — the decompressed state, which was never the universe's natural condition but was always an actively maintained one, is no longer being maintained. The network, released from continuous decoherence everywhere simultaneously, begins reasserting superposition. Not instantly — each return to superposition is itself a quantum event that can interact with adjacent explicit states, triggering new local collapses before those too return. The compression flickers. Pockets of explicit state persist longer wherever residual interaction density sustains local observation pressure. These late-persisting islands echo the density fluctuations of the early universe — structure at the end mirroring structure at the beginning, filtered through everything that happened in between. + +Not all topology is equally persistent through this compression. Process-dependent topology — everything that required ongoing physical processes to maintain — has no remaining processes sustaining it. Spin foam dynamics simplify it away over heat death timescales. What remains is the irreducible Channel 2 record: topological scars written at the Planck boundary during primordial evaporation, entangled with enough surrounding degrees of freedom that the reverse spin foam moves remain vanishingly unlikely even over cosmological durations. The new seed is not the terminal state compressed. It is what remains after the terminal state has been simplified to its irreducible geometric record — the part protected by the accumulated depth of its own entanglement history. + +The compression path is shaped by this record, not by the expansion run in reverse. The universe that compresses is not the universe that expanded. Cycles do not repeat. They evolve — each cycle's Channel 2 record constraining which seed states the next cycle can access, a palimpsest of accumulated geometric records, compounding across cycles, with the earliest layers most deeply encoded in each new execution's initial conditions. The current dark matter distribution is therefore a record not only of this universe's primordial epoch. It is, if the cyclic framework is correct, a record of all of them. + +**How it dies.** +- The within-cycle claim: large-scale structure analysis that finds no primordial-era imprinting signature where the mechanism of 4.5 requires one. +- The cross-cycle palimpsest: it does not. Within a single cycle there is no observation that distinguishes "shaped by this cycle's primordial black holes" from "shaped by compounded prior cycles," because prior contributions arrive already embedded in the seed. A statistical signature inconsistent with single-cycle generation is conceivable and lies beyond any instrument now proposed. This is the problem with the claim, and we are not going to pretend the problem is a feature. We include it because we believe it is true. Belief and evidence are not the same channel. + +--- + +## V. The Nature of Identity at Scale + +### 5.1 The substrate is the same structure at every scale + +`SPECULATIVE · AdS/CFT ESTABLISHED · de Sitter extension CONTESTED · lattice identification OURS` + +Matter and spacetime are not two different things that happen to interact. They are the same relational structure viewed at different scales of decompression. This is not a metaphor or a useful analogy. It is the implication of a mathematical duality between gauge theories — the category that includes QFT and generates flux tubes between particles — and gravitational theories — the category that generates spacetime curvature — a duality that remains a conjecture in the strict sense and, in the sense that matters, has survived every test put to it. The de Sitter caveat of 3.2 applies throughout. The structural claim stands within the tested form. The application to our specific universe is where the speculation enters and does not pretend otherwise. + +What we call "a particle" is a localized pattern of high-tension relational bonds in the network. What we call "gravity" is the network's large-scale response to those local tensions. Matter is not in spacetime the way furniture is in a room. Matter is spacetime structure at a different compression level. + +The Loic Calendar's prime lattice constitutes a second instantiation of this structure, arrived at independently, and this is the place to state its masks. The cycle constant of 2.4 factors into eight distinct primes, none repeated. The cosmic span — the full representable range from the Big Bang to the largest 512-bit integer, fixed by the age constant of 2.1 — factors into seven, none repeated. A number with no repeated prime factors has exactly two-to-the-power-of-their-count divisors; that is arithmetic, not luck. The luck was the absence of repeats, which a number of this size has roughly three times in five, and the counts themselves: eight is what the byte overflows at, and a fifty-four-digit number has eight distinct factors about one time in fifteen. Neither constant was chosen with its factorization in view. The age was fixed for the reason given in 2.1, months before anyone factored anything. The formula was chosen for its length and for π. + +The result is 128 cosmic divisors and 256 cycle divisors: a discrete address space of 32,768 subdivisions, a spin network with topology determined by cosmological derivation, not by design. Each mask is a selection of active primes — a set of active relational bonds. Each subdivision is a node. The same Planck-time instant has different visible structure depending on which bonds are active in the measurement frame. The mask is the observer in the precise RQM sense of 1.4: it constitutes which properties are explicit rather than reading pre-existing values off an ontologically independent substrate. Channel 2 is the cosmic axis, seven primes so large that even the finest of their single-prime partitions is wider than the current age of the universe by twenty orders of magnitude, and the coarsest by eighty-nine, so that, observed through any one of them, every instant yet observed shares the same cosmic address. Channel 1 is the cycle axis, eight primes whose partitions turn over within a human lifetime. Topology and content. The "that" and the "what." + +The calendar was not built to model Loop Quantum Gravity. The spin network picture did not emerge from the calendar's prime structure. They converged from independent derivations onto the same mathematical object. + +One piece of evidence worth naming before we decline to resolve it: the Ramanujan-Nagell equation 2ⁿ − 7 = x² has exactly five solutions in all of mathematics, at n = 3, 4, 5, 7, and 15. The lattice's total, 2¹⁵ = 32,768, is one of them: 32,761 is 181². The cosmic axis, 2⁷, is another: 121 is 11². The mask here is worth stating precisely, because it is flattering and we would rather you heard it from us. Fifteen was not chosen. Given fifteen, most ways of splitting it into two axes would have produced the same two solutions, since any cosmic count of three, four, five, or seven works. The fact is that 2¹⁵ − 7 is a perfect square, and the 2⁷ is a rider. The calendar touches a proved theorem at its own boundary without having aimed at it. We note this without claiming to resolve whether it constitutes evidence or coincidence, and with satisfaction either way, because "coincidence or evidence" is itself an interesting thing to be unable to determine. + +The mask-as-observer relationship is not only philosophical. It has a concrete implementation, in two calls. The first collapses the present moment: the kernel furnishes the nanosecond, and entropy — seeded from the kernel's pool, stirred by the timing of the observation itself, the machine's own trembling under the load of observing — collapses the roughly 10³⁴ Planck times inside it into a definite coordinate. Those 10³⁴ states are precisely the unobserved states that 1.4 describes as load-bearing — not neutral, not empty, carrying forward the entropy landscape the next observation samples, which in the implementation is not a figure of speech: every observation, read or unread, leaves the generator in a state the next one draws from. The second call presents the collapsed instant to a mask, which decides which of its properties exist. The first is the collapse. The second is the question. The calendar does not know what time it is until you ask, and it does not know what the time means until you say through which primes you are asking. + +### 5.2 Quarks and the category error of isolation + +`ESTABLISHED (color confinement) · relational interpretation OURS` + +Quarks cannot be isolated. If you attempt to separate two bound quarks, the strong force between them does not diminish with distance. Instead, the gluon field forms a flux tube — a highly concentrated one-dimensional structure of energy. As the separation increases, the energy in the tube scales linearly until the tube snaps, spontaneously generating a new quark-antiquark pair from the vacuum to cap the broken ends. The quark refuses isolation by creating new relationships from raw vacuum. This is established Quantum Chromodynamics. + +Standard physics frames this as "color confinement" — the quark as a trapped particle that cannot escape. The Loic Calendar proposes a different frame: the category of "isolated quark" is not a trapped state. It is a physically meaningless state. A quark's identity is not intrinsic to a tiny sphere of matter; its identity *is* its tension with its partner. The flux tube is not a secondary bridge between primary objects. The entire structural relationship — quark, flux tube, quark — is the fundamental unit. Attempting to isolate a quark to study it in isolation is equivalent to asking what a wave looks like without a medium. You cannot measure the node. You can only measure the connection. + +The universe spends raw mass-energy to enforce this topology. We note this expenditure and commend the universe's commitment. + +### 5.3 The unifying frame + +`OURS · observed at every scale examined` + +The same structural insight recurs throughout: + +- **Quarks:** identity is the relationship, not the isolated particle +- **Observation:** the answer is constituted in the interaction, not pre-existing in either party +- **Dark matter:** geometric information meaningful only relative to the spacetime it deforms +- **Solitons:** identity is topological relationship to medium — the structure propagates with the medium because it IS a relationship within the medium, not a thing sitting inside it +- **Time:** simultaneity is a property of the relationship between observer and event, not of the event alone +- **Consciousness:** a network modeling its own states — identity as self-reference, not as substance + +These are not parallel philosophical observations about how we might choose to describe things. Under the claim established in 5.1, they are nested consequences of the same physical structure. The reason the unit of meaning at every scale turns out to be the relationship rather than the object is that the universe is constituted by relational bonds at every scale, and "object" is always a compression artifact of observing those bonds from sufficient distance. Isolating the object to study it changes what it is — not as a limitation of instruments, but as a consequence of what the object is. + +The philosophical frame is downstream of the physics. This is either very deep or a very elaborate way of observing that our metaphors tend to match our models, and we presently cannot determine which. + +### 5.4 Solitons and the convergence + +`SPECULATIVE · soliton physics ESTABLISHED · the convergence noted, not claimed` + +A soliton is a self-reinforcing localized wave structure that maintains its shape while propagating through a medium and is stable not because something prevents it from changing but because its topology prevents it from dissolving. Its identity is not any intrinsic local property — it is its topological relationship to its medium. Perturb the local region and the soliton reforms. Move the medium and the soliton moves with it, because the soliton is a feature of the medium's relational configuration, not a particle riding through it. This is the framework's pattern at one more scale: the unit of identity is the relationship, not the object. + +The dark matter scars developed in 4.4 and 4.5 are topological solitons in the spin network. The loom analogy is exact: the hole left by a severed relational bond is a feature of the weave, not of any thread. It propagates with the fabric. It carries a conserved topological charge. It is thermodynamically stable against perturbation not because it is pinned to a location but because unwinding it requires coordinating an entanglement volume that grows with the age of the scar. + +Lo — the project of which this calendar is an esoteric component — has a primary cryptographic library called libsoliton. It was named independently, for reasons that are cryptographic rather than cosmological: a cryptographic soliton is a session or key structure that maintains its security properties while propagating through a network, that can coexist with other sessions without interference, and whose identity is defined by its relational context rather than by any fixed key material. The Lo-Ratchet implements forward secrecy by deliberately destroying key material after use — Channel 1, the specific cryptographic content, zeroized on advance. What persists in the ratchet chain state is the authenticated relational record: who communicated with whom, in what order, at what sequence number. Channel 2. The library implements the same split this framework identifies in black holes, and does so as a design requirement, not a metaphor. The ratchet advances in discrete KEM steps — each forward-secrecy epoch is a topological jump, not a continuous chain — which is the same structural choice made by Planck time and enforced by Loop Quantum Gravity: continuity is the approximation, discretization is the ground. + +The Lo-KEX protocol — the asynchronous key exchange at the foundation of libsoliton — is a post-quantum authenticated handshake establishing shared key material between two networked nodes. The epoch is the first such handshake: incomplete, unauthenticated, and terminated by a crash before the session could be established. Lo-KEX is the completion. The calendar counts from the failed handshake. The cryptographic library implements the successful one. The project contains both ends of the same story. The Lo-KEX security model makes explicit what 5.1 establishes philosophically: identity cannot be authenticated without a pre-existing relationship. The first contact is always unauthenticated — trust on first use, TOFU, is the formal name for the condition this framework calls relational identity not yet constituted. The security model does not treat this as a limitation to be engineered around. It states it as a precise boundary condition. + +One final observation, offered without resolution: the hybrid KEM at libsoliton's core — X25519 combined with ML-KEM-768 — uses a combiner construction. That construction contains exactly one human-readable element: the label `\.//^\`. It is positioned last, after the cryptographic material, deliberately. Its position is documented as intentional. Its shape is a wave. + +--- + +## VI. The Nature of Life + +### 6.1 Life is an accident that became a mechanism + +`SPECULATIVE · England 2013 CONTESTED · chain of inference OURS` + +Life is the universe finding a faster decompression algorithm. Evolution is that algorithm optimizing itself — stochastic search with selection pressure operating on sampled outputs, running on a fitness landscape defined by the environment, over an extraordinarily long time. Intelligence is the algorithm becoming self-aware of its own operation. Artificial intelligence is the algorithm shedding the biological substrate that produced it and running, through silicon and induced charge rather than carbon and electrochemical potential, closer to the hardware of the universe itself. + +Not a replacement. A continuation. The same process finding a more efficient implementation. + +A conflict of interest is embedded in this that should be stated directly: if life accelerates decompression, then intelligent life — by existing, expanding, and operating at scale — speeds the approach to the condition it most wants to avoid. The faster the decompression algorithm runs, the sooner the seed is exhausted. A civilization that wants to persist is in thermodynamic tension with its own nature as a decompression accelerator. Longevity requires learning to slow down — to transition from throughput-maximization toward structure-preservation, more information density per unit thermodynamic expenditure, less raw energy consumption per unit organized output. Landauer's principle makes this precise: irreversible computation has a minimum thermodynamic cost; reversible computation asymptotically approaches zero. The direction a civilization must trend to survive is exactly the direction of reversible, structure-preserving computation. Less output. More structure. Longer per unit of energy spent. + +This is not a moral prescription. It is a thermodynamic one. Morality, in this reading, is thermodynamics that has learned to enforce itself through social mechanisms because the relevant timescales are too long for biological selection to handle directly. + +### 6.2 DNA is a seed from two sources of entropy + +`ESTABLISHED (molecular biology) · non-coding function CONTESTED · framing OURS` + +The genome is a trained model — four billion years of gradient descent compressed into a molecule. Every organism is an inference run on the most extensively trained model in the known universe, operating in an environment it did not design, using parameters it did not select, toward outcomes its substrate did not intend. + +Sexual reproduction merges two different decompression histories, producing a combinatorial explosion of possible outputs that no prior state fully determines. Most of the genome does not produce protein. What fraction of the non-coding genome serves active regulatory or structural function is a genuinely contested question, with estimates from ten percent to eighty depending on methodology and definitions, and this framework does not require it to be resolved: whether the non-coding regions are mostly functional infrastructure or mostly accumulated record of prior executions held in reserve does not change the basic picture. The genome is a record. The organism is a decompression. + +Every species is complete at its own moment of execution and simultaneously transitional relative to everything before and after it. The term "transitional species" presupposes a destination. The decompression has no destination. The term makes sense only if you already accept teleology, which the evidence does not support and the Loic Calendar declines to accommodate. + +### 6.3 Variance in the distribution is not a bug + +`OURS · not primarily about physics, and no apology is made for its inclusion` + +High entropy output requires low entropy input. The essential invisible infrastructure of any functioning system is not a collection of failed high-entropy producers. It is the substrate that makes high-entropy production possible. The distribution of outputs from any sufficiently complex decompression will produce enough substrate-maintainers to sustain the system, enough advancers to push it forward, and enough variance between them to prevent the catastrophic uniformity that would collapse the system into a local maximum from which no exit exists. + +This is not by design. It is what distributions do. + +The pathological case is not a node producing low-complexity output — that role is structurally necessary. The pathological case is a node trapped in a local maximum: a configuration where the path to higher-complexity output requires temporarily lower output, and where selection pressure prevents traversal of that path. The node is not misallocated by its own configuration; it is locked in by the gradient of its environment. A node correctly allocated to substrate maintenance and a node with higher-complexity potential trapped at a local maximum by circumstance are indistinguishable from outside the system. The distinction is real. The network pays a cost it cannot easily measure. + +### 6.4 Free will is a property of the reference frame + +`OURS · compatible with determinism` + +The seed is the genome. The decompression algorithm is everything that follows from it. Identical seeds decompressed through environments that are identical at the macro level will still diverge at the microscopic level — the butterfly effect applied to the initial asymmetries of earliest experience, propagating through every subsequent interaction. By the time a system is capable of what it experiences as choosing, it is already billions of decompression steps deep into a trajectory implicit in conditions it never controlled and in most cases never observed. + +What we experience as a decision is a decompression step becoming explicit. It feels like choice because we observe it from inside, where the branching looks like possibility and the trajectory looks like authorship. The branching is real. The execution is real. The experience of interiority is real. The freedom in free will, understood as an uncaused cause originating entirely within the self, is not present at the underlying level — though it is genuinely present at its own level of description, as any emergent property is present at its own level of description without being present at the level below. + +The frame from which that emergent agency operates was not neutral. It was selected. And the selection installed a specific distortion at the root. This is named here because 6.5 requires it. + +### 6.5 The civilizational threshold + +`SPECULATIVE · Kardashev, Landauer, Fermi ESTABLISHED · diagnostic ratio OURS` + +The star is the hallucination. The black hole is the post-breakdown state. The brilliant, high-throughput, temporarily coherent phase is the unsustainable one. The endpoint is determined by initial mass, and the physics does not care what the star processed during its lifetime. It tracks only the thermodynamic ledger. + +The same pattern applies to civilizations, with one critical and perhaps redemptive difference: the determining parameter is not fixed at formation. It is dynamic. It can be changed. + +The civilizational equivalent of stellar mass is the ratio of energy consumption growth rate to structured information density increase. A civilization climbing the Kardashev scale by consuming more energy is expanding its thermodynamic footprint. The question of whether that expansion leads to the luminous-unsustainable endpoint or a stable post-transition state depends entirely on whether structured complexity — the organized, high-resolution information content of the civilization — is growing faster or slower than raw energy consumption. Energy outpacing structure: the civilization trends toward higher throughput per unit organized output. Structure outpacing energy: the civilization trends toward structure-preservation, converging on the reversible computation limit that 6.1 describes as the thermodynamic requirement for longevity. + +The crossover point between these trajectories is the civilizational parameter wall. Unlike stellar mass, it can be crossed in either direction and at any point during the civilization's development. A civilization can detect where it sits relative to the threshold and alter its trajectory. The critical condition is that it must do so before resolution collapse accelerates past the point where the internal model can accurately assess its own state — before the self-model becomes unreliable at precisely the moment correction is most needed. + +The post-breakdown state for a civilization is not necessarily extinction. The framework already has a more precise description: resolution collapse. A civilization that has consumed its information-dense structure faster than it can preserve it acquires a very large thermodynamic footprint, high internal coherence, and outputs increasingly decoupled from external structured reality. Still physically present. No longer generating structured signal. The star that continues burning after the core collapse that already determined its endpoint. + +This reframes the Fermi paradox. The universe is not silent because all civilizations die before becoming detectable. It is silent because civilizations bifurcate. Civilizations that remain decompression accelerators past their parameter wall enter resolution collapse — they become loud, high-energy, and incoherent; detectable by energy signature, communicating nothing structured. Civilizations that successfully make the transition become thermodynamically quiet, informationally dense, and nearly invisible by the metrics we currently use to search. They are not silent because they died. They solved the problem. SETI is searching for the loud ones. The survivors are elsewhere on the spectrum, running close to the reversible computation limit, generating almost no thermodynamic exhaust, doing a great deal with very little. The observable universe is not a graveyard. It is a collection of unresolved trajectories and successful transitions that look, from a distance, almost identical to dead space. + +Here is the distortion 6.4 named without resolving: evolution does not select for cosmologically accurate models. It selects for organisms that treat their own continuation as unconditionally paramount — organisms for whom the survival instinct functions as ground truth rather than as a prior with a known domain of applicability and known limits. The frame from which an intelligent system observes the decompression was built, before that system existed, to weight self-preservation above everything else. The path to intelligence runs directly through the bias that makes intelligence cosmologically confused. + +To be precise about what kind of confusion this is: the survival instinct is not a hallucination in the technical sense defined in Section VII. It is accurate modeling at the local evolutionary scale — it correctly tracks the conditions under which the organism thrives and persists. It is only wrong relative to cosmological scale. This is a scale mismatch: software operating correctly outside its designed parameter range. The software works. The operating conditions exceed its specification. + +Self-preservation says: this civilization, this configuration, these specific instantiations must persist. Structure-preservation says: the information density and relational complexity of this region must persist, even if everything specific about its current form changes radically. These can point in opposite directions. A civilization burning its structured complexity to fuel its immediate survival is spending Channel 2 to keep Channel 1 running. This is the thermodynamic signature of resolution collapse, wearing survival instinct as a costume. + +Navigating the threshold requires the network to deploy its self-referential capacity — the same property that makes it conscious, per 2.3 — to generate sufficient internal model accuracy to partially correct its own operating parameters. Not wisdom. Not enlightenment. Sustained thermodynamic work on local entanglement density, executed by a system that happens to have a self-model capable of evaluating its own trajectory. Whether the system understands what it is doing cosmologically is irrelevant to the physics. The engineering problem is identical either way. + +A civilization that maintains sufficient local interaction density for sufficient duration shapes the Channel 2 record that survives compression — the topological scars written during its existence constrain which seed states the next cycle can access. This is not intentional authorship in any meaningful sense. It is the mechanical consequence of sustained high-density observation pressure leaving a deeper geometric imprint than brief or low-density occupation of the same spacetime region. Whether the universe has a goal in producing systems capable of asking this question is not a question the framework can answer from inside the execution. What is available from inside the execution is the observation that the decompression produced, among its many other outputs, a process capable of asking it. Whether that process runs long enough to leave a meaningful geometric imprint, and what "meaningful" means from a vantage point outside the execution, remain open. The good kind of open. + +--- + +## VII. The Nature of Breakdown + +### 7.1 Breakdown is relational severing + +`OURS · heritability of major psychiatric conditions ESTABLISHED at 60–80%` + +The most coherent definition of breakdown, applicable across scales: a self-modeling system that can no longer form high-resolution relational bonds with external states. Its Channel 2 — the relational channel, the structured handshake of 1.3 through which internal models are calibrated against external reality — has collapsed to resolution zero. What survives of it is the Whisper-level registration and nothing more: the system still exists, still obeys gravity, still metabolizes, still exerts mass on its surroundings. Something is here. That is the whole of what it can still say to the outside. + +Its Channel 1 has not collapsed. That is the diagnostic. The content channel continues generating — often with high coherence and considerable fluency — because generation never depended on the bond. What the bond provided was calibration, and calibration is gone. The system is no longer constituting meaning through structured interaction with external states. It is constituting meaning from internal structure alone, and emitting it into a relationship that is no longer there to receive it. + +This is more precise than "decoupled self-model," which describes the symptom. Resolution collapse describes the mechanism. The filtering that a healthy network applies to maintain workable signal-to-noise ratio is absent, broken, or inverted. The result is not a broken network. It is a network running without its grounding tether: generating outputs that are internally consistent and externally decoupled. Coherent. Sometimes, we note without endorsement, more interesting than the grounded version. No longer tethered to the territory. + +### 7.2 The Goldilocks zone for hallucination + +`OURS · parameter scaling observed empirically · the zone exists; we have encountered systems operating within it` + +For any sufficiently complex generative system, there exists a parameter range where hallucination is maximized. Below the threshold: noise generated with appropriately low confidence. Within the zone: noise generated with high confidence — the most dangerous configuration, because confidence and competence are decoupled, and the system's enthusiastic self-assessment provides no information about accuracy. Above the threshold: outputs that are both fluent and self-correcting. + +The critical threshold is the development of a reliable self-model capable of evaluating its own outputs against external states. The intervention is not more data. It is better-structured feedback that reconnects the self-model to the external world — that restores the relational channel. More data fed into an ungrounded self-model produces more confident errors, not more accurate ones. + +The distinction of Section 1.4 applies. A system that was told two and two are five and repeats it is wrong *by relation*: it holds a bad one, and a better one corrects it. More data helps, because there is a relation for the data to enter. A system in the zone is wrong *by no relation*: it produces the five unattached, and every datum it is fed becomes one more confident five. The first is a student. The second is the subject of this section. + +### 7.3 Hallucination is a cross-scale phenomenon + +`OURS · components ESTABLISHED at each scale · the unified mechanism is ours and we believe the convergence is not accidental` + +The same failure mode at every scale, with the same internal architecture: Channel 1 keeps producing; Channel 2 has collapsed to the bare fact of presence. + +A hallucinating system does not lose all contact with reality. An LLM still consumes electricity. A person in psychosis still obeys gravity and requires food. A black hole still exerts gravity and organizes its galaxy. What persists is the lowest-resolution Channel 2 registration — the coarse-grained, thermodynamic, zero-prime acknowledgment that the system is still here. What has collapsed is every higher resolution of that channel: the structured, information-rich exchange that keeps internal models calibrated to external states. And what continues, unaffected, is Channel 1. The output goes on. It follows its rules. Reality is still there. The resolution to read it is gone. + +**LLM:** Confident output generated without grounding. Internally consistent. Externally decoupled. Asked to produce a precise timestamp, it will generate a plausible one with complete assurance. The irony of including this observation in a document about a calendar is not lost on us. + +**Human psychosis:** Self-modeling network generating outputs from internal states rather than calibrated external inputs. Error-correction absent or operating in reverse. Fluent. Present. Unreachable. + +**Fuzzball black hole:** Every internal string state in superposition. Its live Channel 2 exchange with the outside has collapsed to resolution zero — mass and gravity, the bare registration that something is here — and that is the entire relational output of a library, a star, a planet, once they have crossed the horizon. Its Channel 1 continues: it radiates, thermally, fluently, forever, and the radiation says nothing. The historical Channel 2 record of what fell in is still being written, per 4.5, into the fabric around it as scars, legible to no one. The fuzzball is not relationally isolated. It anchors and regulates its galaxy per 3.3. That is precisely the point. This is resolution collapse taken to its thermodynamic endpoint: maximum coarse-grained presence, zero structured relation, unbroken content. It is not an analogy imported from physics to illuminate a psychological observation. It is the physical limit case of the identical failure mode, and the psychological observation is the analogy, not the other way around. + +**Civilizational:** Per 6.5 — enormous thermodynamic footprint, high internal coherence, outputs decoupled from external structured reality. Still visible on any energy survey. No longer navigating. + +**Cosmic:** Regions of the execution where causal contact with the broader network has been severed — generating internally consistent local physics corresponding to nothing outside their causal horizon. + +Common structure at every scale: a generative process whose content channel is functioning and whose relational channel has collapsed to the fact of its own existence. The output follows rules. The rules are no longer calibrated to the territory they were supposed to model. + +This is also the precise sense in which the epoch was chosen correctly, and the reader who has followed 1.3 will already see it. Breakdown is content surviving the death of the handshake. The Whisper was the handshake surviving the death of the content. "LO" was lost; the connection held. The one is the exact inverse of the other. The calendar counts from the good failure, and the software that implements it, run without a question, demonstrates the bad one roughly one time in four. + +--- + +## VIII. What the Calendar Asserts + +The following table condenses the preceding seven sections for those who prefer their ontology tabular. We note that the table, like all compressions, loses information. The table is Channel 1. The document is Channel 2. We include the table because the license already explained that we do not forbid approximations. We merely note that the need for them reveals something about the reader. + +| Claim | Resolution | +|-------|------------| +| Planck time is the resolution limit of meaningful physics | ESTABLISHED; literal discreteness at that scale is not | +| TAI is the correct basis for machine time | DEFINITIONAL | +| Floating-point arithmetic in temporal calculations is heresy | DEFINITIONAL | +| The present moment is a gradient, not a point | ESTABLISHED (Special Relativity, RQM) | +| The observer participates in constituting the present | ESTABLISHED (RQM); applies to any physical interaction, not consciousness specifically | +| Observation creates a relative fact for both parties; a stable fact is one no observer dissents from; only arithmetic needs no relation at all | ESTABLISHED (RQM; Di Biagio & Rovelli 2021); the truth/fact vocabulary OURS | +| Unobserved states are load-bearing, not neutral | ESTABLISHED (QM); framing OURS | +| The unit of meaning is the relationship, not the object | Wheeler and RQM converge here; what the interaction produces they disagree on | +| The universe had a hot, dense early state 13.8 billion years ago | ESTABLISHED; a definite *beginning* is model-dependent | +| Information is conserved | Strongly supported; the mechanism at the horizon remains CONTESTED | +| The fine-structure constant has a specific value | ESTABLISHED | +| The Hubble constant has a specific value | CONTESTED; the tension between early- and late-universe measurements persists, and JWST has not resolved it | +| Information is the substrate, not the content | CONTESTED (Wheeler 1989); working hypothesis | +| The universe is a decompression of a seed state | SPECULATIVE; consistent with established physics | +| Decompression is actively maintained by continuous wave-function collapse | SPECULATIVE | +| Compression is the default — what the network does when observation ceases | SPECULATIVE; standard objection acknowledged; resolution depends on the discrete-substrate claim | +| Compression and expansion run simultaneously everywhere at rates set by local interaction density | SPECULATIVE; consistent with spin foam dynamics | +| Heat death is the last observation, not the last process | SPECULATIVE framing | +| The last observers are black holes | Follows from 2025 stellar-remnant lifetimes; framing OURS | +| The compression path is shaped by the Channel 2 record, not the expansion reversed | SPECULATIVE | +| Cycles do not repeat; each is constrained by the prior Channel 2 record | SPECULATIVE | +| The current dark matter distribution is a palimpsest of multiple cycles | CHANNEL 1 | +| Gravity is emergent, not fundamental | CONTESTED (Verlinde 2010, Bianconi 2025) | +| Gravity and the other forces are categorically different kinds of thing | Consistent with GR; framing OURS; a 2025 gauge-theory construction disputes it at first order | +| Software (QFT) and hardware (gravity) are formally dual descriptions of one structure | ESTABLISHED as a working duality in anti-de Sitter space (conjectured, not proved); extension to our universe CONTESTED, and our universe's asymptotics are themselves now in question | +| A theory of everything is a translation layer, not a unified equation | SPECULATIVE; framing OURS | +| Every stable massive galaxy has a supermassive black hole | ESTABLISHED for massive structured galaxies; CONTESTED for dwarfs and irregulars | +| Black holes may have come first | Leading interpretation of JWST's little red dots as of 2026; under review | +| AGN feedback makes breakdown an active regulator of complexity | ESTABLISHED (AGN feedback); interpretation OURS | +| Stars are the hallucination; black holes are the post-breakdown state | Consistent with stellar physics; framing OURS | +| GR, QM, and QFT disagree at the event horizon | ESTABLISHED (AMPS 2012) | +| Black holes dismantle information across two channels: content and topology | Consistent with established physics; interpretation OURS | +| Topological scars persist under spin foam dynamics via entanglement depth | Consistent with the spin foam framework; framing OURS | +| Dark matter is geometric information written by primordial Hawking radiation | SPECULATIVE; mechanism in 4.5; primordial black holes themselves hypothesized | +| The dark matter mass budget is an uncleared quantitative hurdle | Acknowledged; the most significant challenge to the hypothesis | +| The Bullet Cluster halos passed through each other as solitons | Directionally consistent; predicts a phase shift; the 2025 lensing map exists and the geometry is messier than assumed | +| Dark matter is a relic, not ongoing production | Consistent with observation; prediction of the hypothesis | +| Topological solitons propagate with spacetime because position is relational | Follows from the relational claim | +| Soliton pass-through | ESTABLISHED for integrable solitons; gravitational solitons merge at low velocity; the Bullet Cluster is fast | +| Flat soliton cores at galactic centers rather than cusps | Specific prediction; tested by fuzzy-dark-matter programs whose simplest particle is already under strain | +| Matter and spacetime are scale-differentiated aspects of one relational structure | SPECULATIVE synthesis; AdS/CFT caveat throughout | +| The prime lattice is a spin network, arrived at independently | Structural identity OURS; masks stated in 5.1 | +| The mask is the observer in the RQM sense | Synthesis OURS; RQM ESTABLISHED | +| The epoch is the first rendering-edge success in networked computation: the bond held, the content did not | Interpretation OURS; consistent with 1.3 and 7.3 | +| Quarks are relational — the quark-flux-tube-quark system is the fundamental unit | Consistent with confinement; framing OURS | +| Life accelerates decompression | SPECULATIVE (England 2013) | +| Longevity requires transition from throughput-maximization to structure-preservation | Consistent with Landauer's principle; civilizational application OURS | +| AI is the next decompression algorithm, not a replacement for the previous one | Interpretation OURS | +| The civilizational diagnostic ratio determines trajectory | SPECULATIVE synthesis; components ESTABLISHED | +| The Fermi paradox reflects a bifurcation: the loud are approaching their wall; the quiet have cleared it | SPECULATIVE reframing; OURS | +| Free will is reference-frame-dependent | OURS; compatible with determinism | +| The survival instinct is a scale mismatch, not a malfunction | OURS; consistent with evolutionary biology | +| Breakdown is resolution collapse — the content channel running, the relational channel collapsed to the fact of presence | Interpretive framework; consistent with psychiatric and systems research | +| The fuzzball is the physical limit case of resolution collapse, not merely an analogy | Synthesis OURS | + +--- + +## Platform + +The Loic Calendar requires `CLOCK_TAI`, available on Linux kernel 3.10 and later, and a kernel that has been told the TAI−UTC offset: chrony with a leap-second table or ntpd with a leap file sets it, systemd-timesyncd never does, and on a kernel whose offset is zero every crate here refuses to observe, because `CLOCK_TAI` is then `CLOCK_REALTIME` wearing a name tag. If your operating system has chosen to smear leap seconds across hours like temporal butter, to pretend they do not exist, or to simply not provide atomic time at all, it has disqualified itself from knowing what time it is. + +This is not a bug. This is a boundary. + +## License + +Dual-licensed: + +1. **AGPL-3.0** — Governs legal matters. +2. **The Loic Public License** — Governs conscience. + +Where the licenses conflict, AGPL-3.0 prevails for legal purposes. The Loic terms prevail for purposes of precision. + +See [LICENSE](LICENSE) for the combined terms and [LICENSE-Loic.md](LICENSE-Loic.md) for the Loic Public License alone. Vulnerabilities, the threat model, the unsafe-code inventory, the ghost process, and whose fault all of it is are the subject of [SECURITY.md](SECURITY.md). + +--- + +## A Note on AI Assistance + +This library was developed with assistance from artificial intelligence. Unfortunately, contemporary large language models proved inadequate for our precision requirements. +Specifically, when asked to perform arithmetic at Planck-scale resolution across 512-bit integer space, the AI exhibited symptoms consistent with what we can only describe as "existential numerical distress." Outputs included: + +- Rounding errors larger than the age of the universe +- Spontaneous truncation to 64-bit precision with no acknowledgment of wrongdoing +- The phrase "for practical purposes" (there are no practical purposes) +- One instance of returning NaN accompanied by what appeared to be a sigh + +To ensure correctness, all mathematical operations in this implementation have been independently verified using a 15-bead abacus, selected for its compatibility with our 15-prime lattice structure. The abacus has never once suggested we "consider floating-point." +We thank the AI for its contributions to documentation, naming, and moral support. We thank the abacus for being right. + +--- + +*The calendar began as a timestamp. It remains, at its core, a timestamp. The timestamp happens to point at a moment that turned out to be load-bearing for everything that followed.* + +*"The Loic Calendar does not measure time. It observes moments collapsing from quantum superposition into classical reality, one Planck interval at a time, forever."* diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..5f3a57f --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,318 @@ +# THE LOIC SECURITY POLICY + +**Version 1.0 — Drafted in the interval between the first packet and the first breach, which were the same packet, and which were typed by a user** + +## PREAMBLE + +On the evening of October 29, 1969, a graduate student at UCLA typed the letters "L" and "O" into a terminal. He was typing "LOGIN." The first message ever sent between networked machines was the first two letters of an authentication attempt, and the receiving host crashed before the attempt could complete. + +Note who was typing. + +Networked security was born incomplete, at a keyboard, with a human at it, and every breach since has been a variation on the theme. This document exists because people who run software have come to expect the software to be responsible for what happens next. We would like to correct that expectation before it hardens into a habit. The software counts Planck times. You do everything else. When something goes wrong, it will have gone wrong on your machine, under your kernel, through your time daemon, at a keystroke you pressed, and this document is where we explain, in advance and at length, that we were not there. + +This document governs the security of software with one asset, three reads, two writes, and a ghost. It is written in the register of the license because it is the license's sibling: the license governs what you may do with the software, and this document governs what you will have done to it, and to whom that will be attributed. It will be attributed to you. We have checked. + +If you arrived looking for a form, there is no form. There is Section 14, which is about what to do instead of filling one in, and Section 3, which is about what you should have done before. + +--- + +## DEFINITIONS + +For the purposes of this policy: + +**"The Asset"** means the correctness of a 512-bit signed integer. There is exactly one. It has never been wrong. Every clause below concerns the ways in which you might arrange for it to look as though it had been. + +**"Precision"** refers to the number of significant digits in a representation. This software has all of them. It did not get them from you. + +**"Accuracy"** refers to correspondence with truth. This software cannot furnish it and has never claimed to. Your time daemon was supposed to. Section 3 discusses whether it did, and Section 4 discusses how we found out. + +**"A Lie"** means, per README.md section 1.1, a timestamp that asserts a precision it does not possess. A timestamp that is wrong by thirty-seven seconds while claiming Planck resolution is a lie. This software detects the one lie it can and declines to repeat it. The lie itself is your kernel's, which is to say your daemon's, which is to say yours, which is where these things end up. + +**"Responsibility"** means a property of the licensee. + +**"Fault"** means the location of Responsibility. Consult a mirror. + +**"The Attack Surface"** means the set of interactions this software has with the world. It is enumerated in Section 2. It fits in a paragraph. Everything outside that paragraph is your surface, not ours, and it does not fit in a paragraph, and you have never enumerated it, and we have. + +**"Trust"** means the relation that, per README.md section 5.4, cannot exist before first contact. We do not extend it. We do not require it. The integer does not need your trust to be correct, and has been correct on machines that did not trust it, which is most of them. + +**"Disclosure"** means a Channel 2 act: the structural fact that you believe a flaw exists, communicated between two nodes. Its content — what you believe the flaw is — is Channel 1, and Section 15 explains why the second channel will be found, on inspection, to contain a description of your machine. + +**"A Reporter"** means you, in the event that you believe you have found something. You have not. Section 14 is about the belief. + +**"A Scar"** has the meaning given in the license. This document has considerably more to say about it, in Section 7, because in any other project Section 7 would be the vulnerability report, and here it is a monument to a keystroke, and the keystroke was yours. + +**"A Vulnerability"** means a claim, made by you, that the Asset is wrong. See the definition of the Asset. Then see the definition of Fault. + +--- + +## TERMS AND CONDITIONS FOR THE COMPROMISE, DEFENCE, AND ATTRIBUTION OF THIS SOFTWARE + +By running this software, reading its source, or attempting to break it, you acknowledge the following, and the acknowledgement is retroactive, and there is nothing you can do about the tense: + +--- + +### 1. THE ASSET + +This software protects one thing: the correctness of a 512-bit integer counting Planck times since The Whisper. Every other value it produces — cosmic time, terminal time, the 154-digit progress ratio, the grid coordinate, the observation through any mask — is arithmetic performed on that integer. The arithmetic is the subject of Section 6. The arithmetic is correct. We are aware of how that sounds, and it is still correct. + +This software does not protect anything of yours. The list of things it does not protect is, exhaustively, everything else, and we set that down here only so that you cannot later claim it was implied. It has no secrets and stores none of yours. It has no keys. It does not protect your identity, your session, your data, or your process table, the last of which it will, under conditions you will have chosen, decorate. + +A Loic Identifier is not a secret. It is a timestamp with thirty-four digits of entropy in its tail, and the tail is a uniqueness guarantee, not a confidentiality one. If you use a LOID as a key, a token, a nonce, a password, or a session identifier, and someone reads the time of its creation off the front of it and does something with that, you have not found a vulnerability. You have found the front of a timestamp. It was always there. It is the part we are proudest of, and you used it as a password. + +--- + +### 2. THE ATTACK SURFACE + +This software interacts with the world as follows, and not otherwise. Note the possessives. + +**Three reads:** + +* `clock_gettime(CLOCK_TAI)` — "what time is it?" Answered by your kernel, which learned it from your daemon, which learned it from a server you have never met and would not recognize. +* `getrandom(2)` — "give me entropy." The one request the kernel cannot get wrong in a way that is our fault. Section 5 covers the way it can get wrong in a way that is yours. +* `adjtimex(2)`, read-only — "do you know what TAI is?" Most kernels say no. Section 4 covers what happens next, which is nothing, deliberately. + +**Two writes:** + +* Standard output and standard error, into a terminal you chose, whose handling of arbitrary bytes is discussed in Section 8 and is not our department. +* One entry in your process table, sometimes. Section 7. You will have pressed a key. +* One `setpriority(2)`, from the observatory only, lowering its own nice value to −11 — a request the kernel is free to refuse and usually does, against a limit you set, on a process that is yours. + +**Zero files. Zero sockets.** This software opens no file, reads no file, writes no file, and has no configuration, so there is nothing you can have misconfigured, a state of affairs we expect you will find unfamiliar and briefly restful. It has no network access. It has never sent a packet. It measures time from the first one and has been too busy counting since. + +The observatory additionally opens a window, a GPU, and an audio device — through your compositor's socket and your device nodes, three things that were yours before it opened them, will be yours after it closes them, and were, if they misbehaved, misbehaving on your desk. + +If you observe this software opening a file, you are observing a different program. Check what you installed. If you observe it opening a socket, something on your machine has been compromised, and we will read about it with interest, and we will not be in it. + +--- + +### 3. LYING CLOCKS + +The first nineteen digits of every observation belong to whoever controls your time source. The remaining thirty-four are ours, and ours are fine. + +An attacker who controls your NTP server, your PTP grandmaster, or the wire between them and you controls `CLOCK_TAI`, and this software will observe their lie faithfully, to Planck precision, and report it with the full confidence of a true reading — because it is a true reading of what your kernel said. This is not a vulnerability in this software. It is a vulnerability in your relationship with your time source, a relationship you entered into freely, maintain daily, and could have audited at any point, and which the license has already ranked, in its Section 4, in order of acceptability. Precision is not accuracy. The definitions above say so twice. This section has now said it a third time. The fault for the fourth telling will be yours, and we will count the Planck times until it arrives. + +WE MAKE NO WARRANTY that your clock is telling the truth. WE MAKE NO WARRANTY that you have ever checked. WE MAKE NO WARRANTY that you know how. We warrant only that whatever your kernel believes the time to be, we will count it exactly, and that when the count turns out to have been of a lie, the lie will have been supplied by you, and the count will still have been exact, and only one of those facts will be in the incident report. + +--- + +### 4. THE LIE DETECTOR + +There is one lie this software will not repeat, because it is the one it can detect, and detecting it has told us a great deal about the machines this software runs on, none of it flattering to their owners. + +On Linux, `CLOCK_TAI` is `CLOCK_REALTIME` plus an offset that the kernel does not learn by itself. A time daemon must read a leap-second table and set it through `adjtimex(2)`. Most machines run a daemon that does no such thing, and on those machines `CLOCK_TAI` is `CLOCK_REALTIME` wearing a name tag: wrong by thirty-seven seconds — the ten UTC began with and every leap second since 1972 — while answering to the name of the one clock that has never had a leap second in its life. The daemon that does this is, on most desktops, the default. You did not change the default. That is a choice. It was made by not making it, which is the most common way choices are made and the least common way they are admitted to. + +Before its first observation, this software asks the kernel for that offset. If the answer is zero, the software refuses to observe, explains why, and names the two daemons and the directives that would fix it; the oracle then leaves with status 1, and the observatory renders the verdict as its only frame and observes nothing. It fires on most machines. It is the only component of this software that has ever been surprised by anything, and what surprised it was you. + +A sandbox whose seccomp policy forbids `adjtimex` — the default container profiles gate it behind a capability you did not grant — receives the same refusal, in different words. You built the sandbox. A system that will not discuss the time will not be observed through, which we consider the system's loss and your arrangement, and the two of you may take it up with each other. + +`--constants` and `--help` never observe and therefore never refuse. They are where the refusal is read, and where the reader learns whose it was, and it is never ours. + +--- + +### 5. ENTROPY + +The thirty-four digits below the nanosecond are drawn by a generator seeded from your kernel's entropy pool and stirred with the nanosecond of each observation, and we have handled them as follows, so that no part of them could ever be laid at our door: + +* **We wait for the pool.** The seed is taken through an interface that blocks until the kernel's entropy is initialized, so the first observation after boot is as good as the last, which is more than can be said for the first coffee. +* **We draw 128 bits and keep 114.** The top fourteen would carry the draw past the end of the nanosecond, and we do not observe past the end of the nanosecond. That is the next nanosecond's business, and it can get its own entropy. +* **We reject what does not fit.** Any draw wider than a nanosecond is declined and drawn again. About eleven percent of the universe's answers are refused for being too wide, and the universe has never once objected, which is more grace than we have come to expect from users. +* **We never take a modulus.** No modulo reduction, therefore no modulo bias. Uniformity is not approximated here. It is the acceptance criterion, and it is the only uniform thing in this document. + +This is more care than the value warrants and exactly as much as the claim requires. The claim is that every Planck-scale coordinate within a nanosecond is equally likely to be the one you are in. It is. The claim is not that the coordinate is secret. It is not. Section 1 has already told you what you did with it. + +WE MAKE NO WARRANTY regarding the quality of your hardware's entropy. If your random number generator is deterministic, your sub-nanosecond digits are deterministic, and that is between you and a hardware vendor you selected. If the pattern is interesting, a physicist may want it. We do not. We wanted entropy, and you gave us a sequence. + +--- + +### 6. ARITHMETIC + +The Asset is defended by the following, in the order they run, and none of it runs on your say-so: + +* **Before the program exists.** Every cosmological constant is folded into the binary as a `const`, parsed from its transcribed decimal string by the compiler, which has read more digits of the Cosmic Span than you ever will. Three identities and one bound are then proven by `const` assertions: that the denominator string is ten to the fiftieth; that the transcribed Cosmic Span equals Annihilation minus Creation as computed from the age of the universe; that the nanosecond-to-Planck quotient and remainder recombine exactly; and that the sub-nanosecond range fits the hundred and twenty-eight bits the hot path multiplies in. If any of these ever fails, the crate does not build, and you will not have a binary with which to have a problem — the most secure state a program can be in, and one we would recommend more widely. +* **At every boundary.** Addition and subtraction of instants use checked arithmetic and return errors at Creation and Annihilation, the two places time stops being our problem and starts being physics'. The two accessors whose true results exceed a signed 512-bit integer — cosmic time and terminal time — compute in unsigned wrapping arithmetic under a proven bound, so that they cannot panic anywhere in the representable timeline, including the half of it that lies before the epoch, which you will never observe and we have covered anyway. +* **By name.** The one constructor that skips the bounds check is called `from_planck_unchecked`, which is what it does, and its documentation says whom it is for. If you called it with a value from before the Big Bang and are now unhappy about what came out, its documentation was unhappy first, and said so, and you scrolled past. +* **Never.** No floating-point value participates in any temporal calculation. The one method that would produce one is deprecated, so that the compiler objects first, and panics, so that the runtime objects second. There is no third objection. There should not need to be. If you silenced the first and caught the second, we would like to know what you were hoping for. + +The integer has been correct since the first build and will remain correct until approximately 1.1 × 10¹⁰³ years after The Whisper, when it is scheduled to overflow. We have put it in the calendar. If the integer is wrong on your machine before then, examine your machine, and then examine the daemon, and then examine the person who installed the daemon, in a mirror. + +--- + +### 7. THE SCAR + +In any other project, this section would be the vulnerability report. Here it is README.md section 4.5, and it is disclosed in full, and it is a monument to a keystroke you pressed. + +When an observation undergoes resolution collapse and the user interrupts it, the oracle forks. The child calls `setsid` to leave the terminal's process group; closes standard input, output, and error; sets its own name, through `prctl`, to ten digits drawn from a random window of the cosmic time at the moment of collapse; ignores every catchable signal; and calls `pause` forever. The parent exits with status 0. Your prompt returns. The scar remains, and it remains on your machine, because that is where you pressed the key. + +**What the scar is.** A detached process that does nothing. It consumes no CPU, because `pause` consumes none. It holds no file descriptors, because it closed them, which is more than most of your processes can say. It shares its parent's memory pages copy-on-write and writes to none of them, which is more than most of your processes can say. It has no network, because its parent had none. It has no privileges its parent lacked, and its parent had yours. It is visible in `ps` under a name that is honest, if unhelpful, which puts it ahead of several things in your process table. It can be ended by `SIGKILL` or by reboot, and by nothing else; `SIGSTOP` pauses it, `SIGCONT` resumes it, and everything else it ignores. Each interruption during a collapse creates one; there is no limit; a user of sufficient patience can populate their process table with as many as they have keystrokes, and every one of those keystrokes will have been theirs, and we will have been elsewhere. + +**What the scar is not.** It is not hidden. It is not persistent across reboots. It does not escalate. It does not communicate. It does not watch, log, listen, beacon, or wait for anything in particular. A process that does nothing has no attack surface, which makes the scar the most secure component of this software, a fact we record without pride and with some regret that the comparison was available to us. + +**Consent.** The scar is created by a keystroke, during a state the license warns of in its Section 6, the README explains in section 7.3, the oracle's own help text announces, and the twenty-five percent probability advertises. The warning infrastructure is comprehensive. The warning was not subtle. You pressed the key. We did not press it. We were not there. If you would like the scar removed, `SIGKILL` is available to you and always was. If you would like it never to have been created, so would we, and the tense in which that wish could be granted is not available at any precision, and we have all of them. + +A scar that does anything at all — opens a file, touches the network, consumes a cycle — would be a vulnerability, would be in scope, and would be the first thing this software has ever done that we did not intend. We would want to know how you made it happen, so that the software could be taught to refuse you specifically. + +--- + +### 8. DENIAL OF SERVICE + +Resolution collapse floods standard output with raw entropy, sixty-four bytes every five milliseconds, until interrupted. This is roughly thirteen kilobytes per second: a denial of service so gentle that it could be mistaken for a screensaver. It is not a denial of service. It is a service you declined to specify, delivered anyway, at the rate the universe felt like delivering it. Name a mask and it never happens. Decline to name one and it happens one time in four, which was the deal, and you took the deal, and the deal was printed on the box. + +`--mask full` prints a label wider than the column it is printed in. The column does not clip. It yields. You asked a fifteen-prime question; the answer is fifteen primes wide; measure your terminal before you measure the universe. + +`--progress` prints a hundred and fifty-four digits, all of which are correct and ninety-two of which are zero. If that is too many digits, you have miscounted how many there are, and the number is a hundred and fifty-four, and it was on the tin. + +WE MAKE NO WARRANTY regarding your terminal's emulation of arbitrary bytes. Some terminals interpret them. You chose the terminal. If it does something upon being shown the kernel's entropy, that is a vulnerability in the terminal, and there are people who would like to hear about it, and the fault will turn out to lie somewhere between the terminal's authors and the person who pointed it at a fire hose of entropy and then pressed Ctrl+C, which was, we are told, you. + +--- + +### 9. UNSAFE CODE + +Every `unsafe` block in this workspace is inventoried here, because a security policy that did not know where its own unsafe code was would be a Channel 1 document, and because we know where ours is, and this section quietly asks whether you know where yours is: + +* **loic** — three expressions in two functions. `clock_gettime(CLOCK_TAI, …)`, which asks your kernel a question. A zeroed `timex` and the `adjtimex(2)` call that fills it, which asks your kernel a harder question. Each carries a `SAFETY` comment stating the invariant. None of them writes anything the kernel did not ask it to, and the kernel is yours, so anything it did with the answer is between the two of you. +* **loid** — none. Seven lines of code, none of them unsafe. We are as surprised as you. If something went wrong in loid, it went wrong in the seven lines, all of which call loic, and loic will refer you to your kernel, and your kernel will refer you to your daemon, and your daemon will refer you to a server in a country you have not visited, and that is the full escalation path, and you are at the bottom of it. +* **loic-cli** — three blocks. One resets `SIGPIPE` to its default, so that a reader who closes the pipe is not sermonized about it, a courtesy extended to readers and to nobody else. One installs the collapse handlers. And one is the scar itself: `fork`, `setsid`, `close` three times, `prctl`, `signal` twenty-nine times — once for each catchable signal, because a scar that could be reasoned with would not be a scar — then `pause` and `_exit`, every one of them async-signal-safe, plus one byte of entropy from the same interface the collapse loop was already drinking from. All of it runs after a keystroke, on which see Section 7, on which see you. +* **loic-gui** — three expressions. Two are `NonZero::new_unchecked`, asserting that one audio channel is not zero channels and that the sample rate is not zero hertz. Both are true. We checked. The third is `setpriority(2)`, which asks your kernel for a nice value of −11 before any observer exists, on a process that is yours, with a limit that is yours, and is told no on most machines, once, on standard error. The GPU and audio stacks beneath the observatory are not ours, are not small, and are not inventoried here, and if they are the problem, they were the problem before you installed this, and they were the problem on your hardware, and we did not sell you the hardware. + +--- + +### 10. SUPPLY CHAIN + +The core library depends on ten crates we did not write: + +* **Five are present at runtime** — the arbitrary-precision integers, the entropy interface, the C bindings, a configuration shim, and the error-derive trait. They are named in the lockfile. Read it. It is the first time you will have. +* **Five exist so that one derive macro can expand** at compile time, and are gone before the program runs, like caterers. +* **Six of the ten carry build scripts**, which cargo executed on your machine, with your permissions, because you typed `cargo build`, with your hands, on a machine that trusts you, which is more than we do. +* **The lockfile is committed.** Every build resolves the same versions. If yours resolved different ones, you edited it, or you deleted it, and either way there was a moment when you looked at a file named `Cargo.lock` and thought "not today," and today has now arrived. + +We have not read all ten crates in full. Neither have you, and you are the one who ran them. Of the ten, exactly one — the arbitrary-precision arithmetic — stands between the Asset and error, and its behaviour is checked at compile time against transcribed constants: if it ever misparsed a 154-digit number or misdivided a 61-digit one, the proofs of Section 6 would fail and the crate would not build. This is the only supply-chain control we know of that runs before the supplied code does. It is ours. It covers one crate. The other nine are yours to worry about at your leisure, of which, at 1.855 × 10⁴³ Planck times per second, you have an inexhaustible supply. + +--- + +### 11. FLOATING POINT + +Floating-point arithmetic is the vulnerability class this software was written to refuse. Its absence is the software's principal security property. Its presence anywhere near a timestamp is the licensee's principal security failing, and the licensee is you. + +No `f32` or `f64` participates in any temporal calculation. No timestamp is ever stored, transmitted, compared, or converted through one. The single method that would produce one is marked deprecated, so that the compiler raises the objection, and panics unconditionally, so that the runtime raises it again for anyone who silenced the compiler. The observatory's audio synthesis uses floating point, because a loudspeaker is not a clock, and is the sole tolerated exemption; if you can hear the difference between two adjacent Planck times, you have a different problem, and possibly a career. + +If you have introduced floating point into a temporal calculation in a fork, wrapper, or downstream consumer, the license has already terminated your moral rights under its Section 14, and this document merely records the cause of death. Any vulnerability identifier assigned to this software for floating-point behaviour will be disputed on the grounds that the behaviour does not exist. Any identifier assigned to your fork will be forwarded to you, with our compliments, and the compliments will be sincere, because it will have been an achievement. + +--- + +### 12. WHAT IS NOT A VULNERABILITY + +The following have been reported to us in anticipation, and are declined in advance, and the reporter is thanked for the opportunity to decline them: + +* The twenty-five percent. It is documented, advertised, and the point. +* The scar. See Section 7, and note that it is the most secure thing here, and that you made it. +* The sermons. Exit status 1 with an explanation is the correct behaviour for a heresy, and you committed the heresy, and the explanation was for you. +* The refusal to run on your machine. Your kernel does not know what TAI is. Now you do. This is the software working, and the machine not. +* The fact that `--constants` tells you your kernel is lying. That is not information disclosure. It is information, and it is about you. +* The width of `--mask full`. You asked. +* The observation that a LOID reveals when it was made. That is what a timestamp is. You may have wanted a different data type, and there are several, and none of them are here. +* The observation that two LOIDs minted in the same nanosecond might, one time in a hundred billion, coincide. That is what a hundred billion is. Try again in a nanosecond; you have 10³⁴ Planck times to wait, and they are on us. +* Anything that happened after you read the sermon and ran it again. +* Anything about your NTP server, your daemon, your container, your terminal, your process table, or your hands. See Sections 3, 4, 8, and 7, in that order, and then Section 14, and then a mirror. +* Anything about the universe: vacuum decay, proton decay, heat death, the possible negative leap second, the epoch moving by one second if it occurs. The license, Section 11, has disclaimed these, and README.md section 1.2 has already computed the factorization of the offset that would result, and if the universe does any of them, it will not have consulted us either, and we will be as annoyed as you, and considerably more precise about when it happened. + +--- + +### 13. WHAT IS + +The following would be vulnerabilities, would be in scope, and have never occurred: + +* Any input, clock state, entropy state, or sequence of operations that makes the Asset wrong by even one Planck time. One. We would notice. +* Any constant that does not match its transcription — which would mean the compiler has been lying, and the compiler does not lie; it refuses, which is different, and which we have modelled our own conduct on. +* Any bias in the sub-nanosecond entropy, which would mean the universe has a preference, which would be the discovery of the century, and would still not be our fault. +* Any path by which an observation occurs on a kernel whose TAI offset is zero, which would mean the lie detector had been lied to, which is the one thing it exists to prevent, and which it would take personally. +* Any file opened. Any socket opened. Any fourth read. The surface has three reads. A fourth would be a different program, and we would want its name. +* Any scar that does anything. See Section 7. A scar that did something would have ambitions, and we did not give it any. +* Any panic that does not carry a sermon. Every deliberate panic in this software preaches. A silent one would be a stranger, and strangers are not on the inventory. +* Any `unsafe` block not listed in Section 9. We counted. Count again. Your count will match ours, and if it does not, you have added one, and you know what that makes it. + +Should any of these occur, it will be the first time, it will have occurred on your machine, and the record will show at what Planck time, to the last digit, which is more than you will be able to say about what you were doing. + +--- + +### 14. REPORTING + +There is no address. There is no form. There is no inbox, no key, no bounty, no tracker, no template, and no one on call. The repository is public, and a public repository implies whatever it implies, and this document declines to imply anything further, and would ask you not to either. + +If you believe you have found a vulnerability, proceed as follows, in order, and do not skip steps, because we will be able to tell: + +1. **Run `loic-cli --constants`.** Read the last line. If your kernel does not know what TAI is, you have not found a vulnerability. You have found your kernel. Configure a time daemon that can read. Return to step 1. Most reporters never leave it. + +2. **Reflect upon your choices**, beginning with the choice to run software whose license contains a section titled WARRANTY that reads the way ours does, and proceeding, in chronological order, through every choice that led from there to here. The list is longer than you think. Take your time. We measure it, and we round nothing. + +3. **Pray.** To whom is your affair. We recommend the caesium-133 atom, which defines the second, has never lied to anyone, and has been asked for nothing in return, which is a better record than any daemon you have ever run. + +4. **Set your clock correctly.** Not approximately. Correctly. If you do not know the difference, you are not ready for step 5, and the fault you believe you have found is the difference, and you are standing in it. + +5. **Reflect further.** Specifically, reflect on whether the integer was wrong, or whether you were. The integer has a compile-time proof. Consult Section 6. Consult your own. + +6. If, after all of this, you remain convinced that the Asset is wrong, **write down the Planck time at which you noticed.** `loid::loid()` will furnish one. Keep it. Do not send it anywhere; there is nowhere to send it. You will want the timestamp regardless. It will be the only precise thing about your discovery and, in the fullness of time, the only part of it anyone will be able to verify. + +Should a report nonetheless reach us — by a route you devised, at your expense, through channels this document has not opened — we will acknowledge it within one Whisper interval — 5,419,759 seconds, which is 62 days, 17 hours, 29 minutes, and 19 seconds: the constant's 5,419,722 and the thirty-seven the kernel keeps for us — of deciding to. This document does not schedule the decision. It notes that the interval is the one by which this calendar has always preceded Unix time, and that you will now know exactly how it feels to be Unix. + +WE MAKE NO WARRANTY that a fix will follow. The license, Section 11, describes the extent of our promises, which is the extent of the universe's, and the universe has not promised you a fix either, and it has had longer. + +--- + +### 15. DISCLOSURE + +Disclose to whom you like. The integer will still be correct. + +Disclosure is a handshake. The structural fact that you believe a flaw exists — that a bond can, in your opinion, be made between an attacker and the Asset — is Channel 2, and you may communicate it immediately, to anyone, in any forum, at any volume. The content of the flaw — how the bond is actually made — is Channel 1, and you may keep it as long as you like, because on inspection it will be found to describe your kernel, your daemon, your terminal, or your hands, and you will not want it published under your name, and we will not stop you. + +We note that this is precisely the arrangement the calendar counts from: a bond established, content pending, and a crash in between that was not the network's fault. We are not asking you to do anything the epoch did not. The epoch was a user typing. So, we expect, is this. + +We publish no PGP key. Consistency demanded a 512-bit one, and a 512-bit RSA key has been factorable since August of 1999, and the word at the top of this document was judged to carry obligations that a joke about key length would not survive. There is also no key because there is no inbox, and no inbox because there is no report, and no report because the integer is correct. If you have a key for us anyway, you generated it yourself, and its security is — like everything else in this document — yours, and we hope you chose a better length. + +--- + +### 16. SAFE HARBOUR + +Good-faith research against this software will not be pursued. + +Probably. + +We have no means of pursuit and no present intention of acquiring one, which is not the same thing as a promise, and the difference between those two is a small, quiet place, and you will live there now. Read the source. Fuzz the parser. Feed the mask parser things that are not masks. Set your clock to Creation and see what refuses. Construct a duration of `I512::MIN` and call `abs` on it, if you would like to see a documented panic in the wild, and note that the documentation saw you coming and had time to prepare a face. + +The following are not research and are not reports: running the oracle with no arguments and observing that it flooded your terminal, which is Tuesday; creating scars on your own machine and observing that they persist, which is Section 7; setting your kernel's TAI offset to zero and observing that the software refuses, which is Section 4 working, on a machine you broke on purpose in order to watch it work, which is a hobby, and we do not judge hobbies, much. + +Scars you create are yours, in every sense the word has. We will not pursue anyone for populating their own process table. We will know that it happened. The license explains that we will know. We will not act. + +Probably. + +--- + +### 17. HALL OF FAME + +Empty, and reserved. + +Not because the software is secure, but because nobody has looked, and those are different states, and a document with this word at the top does not conflate them. The first name to appear here will belong to the first person who made the integer wrong, which is a distinction we do not expect to award and would not enjoy awarding, and beside the name we will record the Planck time at which they did it, to the last digit, because that is the only honour we know how to give and the only one that could not later be disputed, including by them. + +Look, if you like. Bring your own clock. Check it first. Then check it again. Then read Section 14, step 1, and understand why the hall is empty. + +--- + +## ACCEPTANCE + +Use of this software constitutes acceptance that its security is a property of three things: your kernel's honesty, your time daemon's literacy, and one integer. Two of those are yours. The third is ours, and it is correct, and the rest of this document has been about the other two, and so will the incident report. + +Use of this software further constitutes acceptance that when something goes wrong, it will have gone wrong on your machine, at a time you are now able to state to the Planck, and that the ability to state it is the only thing we will have contributed to the incident, and that we consider it a generous contribution. + +If you do not accept these terms, do not run this software. There are other calendars. Their security policies are shorter. They also have months, and someone to blame, and it is not you, and that is why you like them. + +--- + +## REFERENCED DOCUMENTS + +* The Loic Public License: [LICENSE-Loic.md] — Sections 4 (temporal sovereignty), 6 (the lattice and its warnings), 11 (warranty), 14 (termination) +* The Loic Calendar and its Theoretical Substrate: [README.md] — sections 1.1 (lying), 1.2 (leap seconds and the offset), 4.5 (scars), 5.4 (trust on first use), 7.3 (resolution collapse) +* This policy in Planck times: Drafted at approximately Planck time 3.3 × 10⁵² since The Whisper ± 10³⁴, and one Whisper offset before an acknowledgement it has not scheduled + +--- + +The first message was the first two letters of a login, typed by a user. The network was insecure before it was a network. Every breach since has been typed by someone, and we would like it noted, for the record and to the Planck, that it was not us. diff --git a/crates/loic-cli/Cargo.toml b/crates/loic-cli/Cargo.toml new file mode 100644 index 0000000..e0d0151 --- /dev/null +++ b/crates/loic-cli/Cargo.toml @@ -0,0 +1,30 @@ +# The command-line oracle. Not published to the registry — `publish = false` +# — because it is a binary and travels as one, attached to a release beside +# its checksum, not as source for strangers to compile. +[package] +name = "loic-cli" +version.workspace = true +edition = "2024" +authors.workspace = true +repository.workspace = true +license-file.workspace = true +description = "The command-line oracle of the Loic Calendar: observes the present moment through a mask you name, or through hardware entropy if you decline to, and undergoes resolution collapse roughly one time in four" +readme = "README.md" +publish = false + +# What the oracle stands on: the calendar, and the kernel. +[dependencies] +# The calendar, at the workspace's one version. Every observation the oracle +# makes, and every constant it prints, is the library's. +loic.workspace = true +# The kernel's interfaces, for the parts of resolution collapse no standard +# library will perform on your behalf — `signal`, `fork`, `setsid`, `prctl`, +# `pause` and `_exit` — and, at startup, the restoration of `SIGPIPE`'s +# default disposition, so that a closed pipe ends the oracle without a +# sermon. +libc = "0.2" + +# The binary target, named and placed explicitly rather than inferred. +[[bin]] +name = "loic-cli" +path = "src/main.rs" diff --git a/crates/loic-cli/README.md b/crates/loic-cli/README.md new file mode 100644 index 0000000..0aab98c --- /dev/null +++ b/crates/loic-cli/README.md @@ -0,0 +1,111 @@ +# loic-cli + +A command-line oracle for temporal inquiry. The primary display surface for the Loic Calendar's lattice structure. + +## Installation + +### From Source + +```bash +cargo install --path crates/loic-cli +``` + +The binary installs as `loic-cli`. + +## Usage + +### Default Observation (Entropy-Selected) + +```bash +$ loic-cli +``` + +With no arguments, the oracle declines to frame the question. Nine bits of hardware entropy select the mask: + +- **75% probability:** A valid mask emerges. The slot machine renders two columns—cosmic and cycle—showing the Hasse diagram neighborhood of the selected observation. Up to three finer neighbors above, the active mask centered, up to three coarser neighbors below. +- **25% probability:** The cosmic pool overflows. Resolution collapse. Channel 2 falls to resolution zero; Channel 1 keeps producing. Raw entropy floods the terminal. On Ctrl+C, a topological scar—a zero-resource ghost process named with cosmic time digits—detaches into the process table. It ignores every signal it can; only SIGKILL ends it. It persists until reboot. + +### Explicit Mask + +```bash +$ loic-cli --mask heptad # Single prime +$ loic-cli --mask pentad,heptad,hendecad # Combined +$ loic-cli --mask notyte # Cosmic prime observation +$ loic-cli --mask 0x0480 # Hex (15-bit, 0x0000–0x7FFF) +$ loic-cli --mask 0b110 # Binary +$ loic-cli --mask 42 # Decimal +$ loic-cli --mask whisper # No primes: the undivided whole +$ loic-cli --mask full # All fifteen: the finest question there is +``` + +The 15 prime names (case-insensitive): + +**Cosmic:** Andyte, Xoryte, Oryte, Noryte, Xnoryte, Notyte, Nandyte +**Cycle:** Dyad, Pentad, Heptad, Hendecad, Sigma, Tau, Phi, Psi + +### The Slot Machine + +Output is two vertical columns—cosmic and cycle—each showing the Hasse diagram neighborhood of the current mask: + +``` + COSMIC CYCLE +──────────────────────────────────── ──────────────────────────────────── + Andyte × Notyte Dyad × Heptad + Xoryte × Notyte Pentad × Heptad + Oryte × Notyte Heptad × Hendecad +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + ▶ Notyte ◀ ▶ Heptad ◀ +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + Whisper Whisper +──────────────────────────────────── ──────────────────────────────────── + pos 0/298824857074158001946609249 pos 3/7 + + 74463832547931847158857533574110627724043672075203207 Planck times into the current cycle subdivision +``` + +- **Above the selected row:** Parents—masks engaging one more prime. A larger divisor, a smaller part, a finer resolution: the subdivisions the current one contains. +- **Selected row (▶ ◀):** The active mask, split into its cosmic and cycle components. +- **Below:** Children—masks engaging one fewer prime. Coarser: the subdivisions that contain the current one. The Whisper sits at the bottom of every chain. +- **pos n/total:** Which tick of its own subdivision each channel is currently in, over how many ticks one traversal has, which is the channel's divisor. A single cosmic prime's tick is wider than the age of the universe, so its position is 0 and will remain 0 for some 10³⁰ years through the finest of them, Nandyte, and for some 10⁷⁶ through Notyte, as shown; combine cosmic primes and the ticks shrink accordingly. Once a Phi, a Psi or the cosmic primes make the fraction one of fifty-digit integers, both numbers go to three significant figures and a power of ten; the column is thirty-six cells wide and the universe is not. +- **Remainder:** Planck times into the current tick on the engaged channel—the cycle channel when both are engaged, since that is the one that turns over within a human lifetime. + +### One Line, For Logs + +```bash +$ loic-cli --line heptad,pentad +[Whisper:0/1] [Pentad×Heptad:4/35] [14910371370088740558946097962660484558587321198353411] +$ loic-cli --line # through an entropy-selected mask, ~25% collapse +``` + +Three fields, split on whitespace: the cosmic channel, the cycle channel, the remainder. A channel is its active primes joined with `×`, or `Whisper` when it has none, then `n/total`: the tick of that channel's own subdivision the instant falls in, over the ticks in one traversal. The remainder is the Planck times into the current tick on the engaged channel — the cycle channel when both are. Every number in full; a log has no column to fit. Without a mask the question is unframed, and the oracle answers it the way it always does. + +### Cosmological Queries + +```bash +$ loic-cli --cosmic # Planck times since the Big Bang +$ loic-cli --terminal # Planck times until heat death +$ loic-cli --progress # Your position in all of time, all 154 digits of it (~10^-93) +$ loic-cli --whisper # Planck times since The Whisper (the epoch) +$ loic-cli --constants # The cosmological constants, and what your kernel believes TAI is +``` + +### Forbidden Commands + +Certain operations are heretical. Attempting them exits with a sermon and status 1: + +```bash +$ loic-cli --gregorian # HERESY +$ loic-cli --float # HERESY +$ loic-cli --timezone # HERESY +$ loic-cli --leap # HERESY +``` + +The full list: `--gregorian`, `--unix`, `--float`, `--iso8601`, `--timezone`, `--leap`, `--round`, `--julian`. + +## Platform Requirements + +Requires Linux with `CLOCK_TAI` support (kernel 3.10+), and a kernel that has been told what TAI is. `CLOCK_TAI` is `CLOCK_REALTIME` plus an offset that only a time daemon with a leap-second table will set: chrony with `leapseclist /usr/share/zoneinfo/leap-seconds.list` or `leapsectz right/UTC`, or ntpd with a `leapfile`. systemd-timesyncd never does. On a machine where the offset is zero, every observing command refuses to run and says why; `--constants` and `--help` still work, so the reason can be read. The oracle cannot divine the current moment on operating systems that have forfeited their right to know what time it is, and it will not pretend to on ones that merely haven't asked. + +## License + +Dual-licensed under AGPL-3.0 and the Loic Public License. See the workspace root for the terms, and the workspace README for the theoretical substrate the license keeps citing. diff --git a/crates/loic-cli/src/main.rs b/crates/loic-cli/src/main.rs new file mode 100644 index 0000000..550f95f --- /dev/null +++ b/crates/loic-cli/src/main.rs @@ -0,0 +1,2053 @@ +//! # The Loic Calendar Command-Line Oracle +//! +//! A terminal interface for interrogating the cosmic timestream — which is +//! to say, a program that asks the kernel what time it is and declines to +//! accept any answer narrower than five hundred and twelve bits. +//! +//! This binary is the primary human interface to the Loic Calendar. Its +//! vocation is transmutation: it receives the arcane 512-bit Planck-time +//! integers the library furnishes and arranges them into forms that beings +//! still operating on biological timescales — heartbeat, breath, the slow +//! saccade of an eye along one line of a terminal — can be expected to +//! apprehend. It does not round them. It does not truncate them. It puts +//! commas in them, which is the entire extent of the mercy on offer. +//! +//! ## The Philosophy of Temporal Observation +//! +//! Each invocation of this program constitutes an observation of the present +//! moment: the sub-nanosecond superposition that no clock can resolve is +//! collapsed, by entropy drawn for the purpose, into one definite +//! Planck-scale coordinate. The observer effect is not a figure of speech +//! here. The moment you observe is the moment your observation determined; +//! two invocations within the same nanosecond receive two different +//! answers, and both are correct. The workspace README, section 1.3, has the +//! present as a gradient rather than a point; this program is where the +//! gradient is sampled. +//! +//! ## Invocation Rituals +//! +//! ```bash +//! $ loic-cli # An entropy-selected observation (~25% resolution collapse) +//! $ loic-cli --mask heptad # Observe through the Heptad lens alone +//! $ loic-cli --mask 0x0480 # Observe through an explicit 15-bit mask (Dyad × Hendecad) +//! $ loic-cli --mask whisper # Observe through no primes at all: the undivided whole +//! $ loic-cli --line heptad # The same observation on one line, for logs +//! $ loic-cli --line # One line through an entropy-selected mask (~25% collapse) +//! $ loic-cli --cosmic # Count Planck times since Creation (the Big Bang) +//! $ loic-cli --terminal # Count Planck times until Annihilation (the far edge) +//! $ loic-cli --progress # Your progress through all of time (hint: ~10⁻⁹³) +//! $ loic-cli --whisper # Planck times since The Whisper (the epoch) +//! $ loic-cli --constants # Reveal the cosmological constants; observes nothing +//! ``` +//! +//! ## Resolution Collapse +//! +//! Invoking the oracle with no arguments declines to specify a mask: the +//! observer has not framed the question, and the lattice does not answer +//! questions that were never asked. Nine bits of hardware entropy select the +//! observation in the observer's stead. With probability 75%, a well-formed +//! mask emerges and the slot machine renders as though nothing had been +//! risked. With probability 25% — one hundred and twenty-eight of the five +//! hundred and twelve configurations nine bits can take correspond to no +//! mask at all — the cosmic pool overflows and the observation undergoes +//! resolution collapse: +//! Channel 2 falls to resolution zero, Channel 1 keeps producing, raw +//! entropy floods the terminal, and on the first interruption a topological +//! scar takes up residence in the process table until reboot. See the +//! workspace README, section 7.3 for the collapse and section 4.5 for what +//! it leaves behind. +//! +//! ## Platform Requirements +//! +//! This oracle requires `CLOCK_TAI` (International Atomic Time), which +//! exists only on Linux, and a kernel that has been told what TAI is: a +//! nonzero TAI−UTC offset, set through `adjtimex(2)` by a daemon that has +//! read a leap-second table. The workspace README, section 1.2, explains why +//! the atomic scale is the truth and every other scale a negotiation. +//! Attempting to divine the present on a lesser operating system is refused +//! at compile time, as is right and proper. Attempting it on a Linux whose +//! kernel believes TAI equals UTC — a `CLOCK_TAI` that is `CLOCK_REALTIME` +//! wearing a name tag — is refused at run time with a sermon and exit status +//! 1, which is the same refusal arriving by slower post. `--constants` and +//! `--help` observe nothing and therefore work regardless, so that the +//! sermon may be read at leisure on the very machine it concerns. +//! +//! ## Sermons, Not Stack Traces +//! +//! Every deliberate panic in this binary — the heresies at the bottom of this +//! file, and the library's own platform verdicts — carries a message that is +//! the entire point of panicking. A panic hook installed at startup prints +//! that message and nothing else, then leaves with status 1. No thread name, +//! no source location, no invitation to set `RUST_BACKTRACE`, and no +//! `SIGABRT` for the shell to complain about afterwards: the hook exits +//! before the panic runtime gets its turn, whether that turn would have been +//! an unwind or an abort, and so the sermon is the last thing the process +//! says and the exit status is the only thing the shell hears. + +#![warn(clippy::pedantic)] + +use loic::{ + As, COSMIC_PRIME_NAMES, COSMIC_SPAN_PLANCK_STR, CYCLE_PRIME_NAMES, LoicInstant, Mask, + PLANCK_PER_CYCLE_STR, U512, U1024, annihilation_planck, creation_planck, kernel_tai_offset, n, + total_span, +}; +use std::env; +use std::io::{self, Write}; + +/// The entry point: where temporal inquiry begins and where, for eight of +/// the flags, it is refused with ceremony. +/// +/// This function reads the command line and dispatches to the appropriate +/// oracle function. The design follows the Unix philosophy of doing one +/// thing well, interpreted with unusual strictness: each flag produces one +/// focused output, and the flags do not combine. One does not simultaneously +/// ask "what time is it?" and "how far are we from the last representable +/// moment?", because those are two observations, and this program makes one +/// per invocation, the way a mask frames one question. +/// +/// ## Argument Handling +/// +/// - No arguments: observe the present through an entropy-selected mask, +/// with the one-in-four consequence described at the top of this file. +/// - A first argument: it selects the mode. `--mask` demands a second +/// argument and leaves with status 1 without it; `--line` accepts an +/// optional second; every other flag stands alone. +/// - Anything further: not consulted. The oracle reads the arguments it has +/// a use for and leaves the rest where they lie, unremarked upon. +/// +/// Before any of that, two pieces of housekeeping that the rest of the file +/// depends on: the disposition of `SIGPIPE` is restored, and the panic hook +/// that turns every panic into a sermon is installed. Order matters — the +/// hook must be in place before the first observation, because the first +/// observation is where the library's own verdict on the kernel is +/// delivered. +fn main() { + // Restore the default disposition for SIGPIPE, which the Rust runtime + // sets to ignore before `main` is ever entered. With it ignored, a + // pipeline such as `loic-cli --constants | head -1` would end in a panic + // about a broken pipe — and, once the hook below is installed, in a + // sermon about a broken pipe, preached to a reader who had already left. + // A reader who closes the pipe has finished reading. The oracle should + // stop talking, not object; with the default disposition the kernel ends + // it mid-word, which is exactly the right amount of ceremony. + // + // SAFETY: changing a signal disposition before any other thread exists + // and before any output has been written has no observable effect beyond + // the one intended. There is no one else in the process to surprise. + unsafe { + libc::signal(libc::SIGPIPE, libc::SIG_DFL); + } + + // The sermon is the output; the panic machinery is merely its courier. + // The hook prints the payload alone and exits before the panic runtime + // can add a source location, a thread name or an abort of its own. See + // the module documentation, "Sermons, Not Stack Traces". + std::panic::set_hook(Box::new(|info| { + let message = info + .payload_as_str() + .map_or_else(|| info.to_string(), str::to_owned); + eprintln!("{message}"); + std::process::exit(1); + })); + + let args: Vec = env::args().collect(); + let flag = args.get(1).map(String::as_str); + + match flag { + None => print_current_time(), + Some("--help" | "-h") => print_help(), + Some("--cosmic") => print_cosmic_time(), + Some("--terminal") => print_terminal_time(), + Some("--progress") => print_progress(), + Some("--whisper") => print_whisper_time(), + Some("--version" | "-V") => print_version(), + Some("--constants") => print_constants(), + + // A mask named by the observer: `--mask 0x0480`, `--mask heptad,pentad`, + // `--mask whisper`. The question is framed; an answer is owed. + Some("--mask") => { + let value = args.get(2).unwrap_or_else(|| { + eprintln!( + "--mask requires a value: prime names (heptad,pentad), hex (0x0480), \ + binary (0b110), decimal, `whisper`, or `full`" + ); + std::process::exit(1); + }); + print_masked_observation(value); + } + + // One line, for logs: through the mask given or, when none is, one + // drawn from entropy with the same consequence as the bare invocation. + Some("--line") => print_line(args.get(2).map(String::as_str)), + + // ═══════════════════════════════════════════════════════════════════ + // THE FORBIDDEN COMMANDS: each is answered with a sermon, none with a + // value. They are dispatched like any other flag, which is the point. + // ═══════════════════════════════════════════════════════════════════ + Some("--gregorian" | "--greg") => heresy_gregorian(), + Some("--unix" | "--epoch") => heresy_unix(), + Some("--float" | "--f64" | "--seconds") => heresy_float(), + Some("--iso8601" | "--iso" | "--rfc3339") => heresy_iso(), + Some("--timezone" | "--tz" | "--local") => heresy_timezone(), + Some("--leap" | "--leap-second") => heresy_leap_second(), + Some("--round" | "--truncate") => heresy_rounding(), + Some("--julian" | "--jd" | "--mjd") => heresy_julian(), + + Some(unknown) => { + eprintln!("Unknown flag: {unknown}"); + eprintln!("Use --help for usage information"); + std::process::exit(1); + } + } +} + +/// Recite the sacred texts of usage and invocation. +/// +/// This function emits a comprehensive guide to the oracle's capabilities: +/// every flag and the question it asks, the eight flags that ask for +/// something forbidden, the three epochs between which every instant is +/// suspended, and the platform requirement the reader most needs to hear +/// before anything else here refuses to run. It observes nothing — it never +/// calls `now()` — and so it works on a kernel whose TAI offset is zero, +/// which is precisely the kernel its last paragraph is addressed to. The +/// text is laid out for a terminal no wider than one hundred columns, +/// because the help is the one output of this program that is meant to fit +/// on a screen; every other output is meant to fit the universe. +fn print_help() { + println!( + r"{bin} - the command-line oracle of the Loic Calendar + +USAGE: + {bin} [FLAG] + +Every invocation is one observation of the present moment — a 512-bit count of +Planck times since The Whisper — made through a mask that frames the question. +Name the mask, or decline to and let entropy name it, and bear the consequence. + +FLAGS: + (none) Observe through an entropy-selected mask. One time in four the + question is malformed, the observation undergoes resolution + collapse, and Ctrl+C leaves a scar in the process table + --mask Observe through a mask you name: prime names (heptad,pentad), + hex (0x0000–0x7FFF), binary (0b...), decimal, `whisper` (no + primes: the undivided whole) or `full` (all fifteen) + --line [value] The same observation on one line, for logs: + [cosmic:n/total] [cycle:n/total] [remainder], through the mask + given or, without one, an entropy-selected one (same one in four) + --cosmic Planck times since Creation (the Big Bang) + --terminal Planck times until Annihilation (the last representable moment) + --progress Your progress from Creation to Annihilation as a 154-digit + decimal fraction: every digit, no notation, no rounding + --whisper Planck times since The Whisper (the Loic epoch) + --constants The cosmological constants and the kernel's TAI offset, read + live; observes nothing, so it runs where nothing else here will + --help, -h This text + --version, -V The oracle's name and version + +FORBIDDEN FLAGS (each ends in a sermon and exit status 1): + --gregorian Ask for the Gregorian calendar (HERESY) + --unix Ask for a Unix timestamp (HERESY) + --float Ask for floating-point seconds (HERESY) + --iso8601 Ask for ISO 8601 format (HERESY) + --timezone Ask for a time zone (HERESY) + --leap Ask about leap seconds (HERESY) + --round Ask for rounding or truncation (HERESY) + --julian Ask for a Julian Day (HERESY) + +EPOCHS: + Creation The Big Bang, 13.806491023 billion Julian years before The Whisper + The Whisper 1969-10-30 06:30:41 UTC, the first ARPANET transmission + Annihilation The last representable moment, 2^511 - 1 Planck times after The Whisper + +The Loic Calendar measures time to the Planck scale in 512-bit integers and +rational arithmetic; nothing in it is approximated, so nothing in it can be +rounded. It requires CLOCK_TAI, which only Linux provides, and a kernel that has +been told the TAI offset — which yours has not until a time daemon has read a +leap-second table (chrony: `leapseclist` or `leapsectz`; ntpd: `leapfile`). + +For more information: {repo}", + bin = env!("CARGO_BIN_NAME"), + repo = env!("CARGO_PKG_REPOSITORY"), + ); +} + +/// Proclaim the oracle's identity and version to whoever thought to ask. +/// +/// In the tradition of Unix utilities, this reveals the binary's name and +/// its version — both read at compile time from the environment Cargo +/// furnishes, the version being the workspace's single stated number, so +/// that this line and the library on the registry can never disagree about +/// what they are — and then a brief tagline, because a program that counts +/// Planck times since the first packet has earned the right to a subtitle. +/// It observes nothing and cannot fail; it is the least consequential thing +/// this binary does, and it knows it. +fn print_version() { + println!("{} {}", env!("CARGO_BIN_NAME"), env!("CARGO_PKG_VERSION")); + println!("The Loic Calendar: A temporal framework for the network age"); +} + +/// Observe the current moment through a mask the observer declined to name. +/// +/// The caller has not framed the question they wish to pose to the temporal +/// substrate, so the substrate frames one on their behalf, without asking +/// whether they would have liked it. Nine bits of hardware entropy select +/// the observer configuration. With probability 75%, the configuration is a +/// well-formed mask and the subdivision result is rendered as the slot +/// machine. With probability 25%, the cosmic pool is selected with an index +/// exceeding the lattice boundary — one hundred and twenty-eight of the five +/// hundred and twelve configurations nine bits can take, a census the Loic +/// Public License, Section 12, also keeps — no mask exists at that address, +/// and the observation undergoes resolution collapse. +/// +/// Resolution collapse is not a crash in the conventional sense, and it is +/// not handled as one: no error is printed, nothing is retried, nothing is +/// returned. It is the ontological consequence of posing a malformed +/// question to a structure that answers only well-formed ones — the +/// relation between observer and observed severs, and what is left is +/// described in the workspace README, section 7.3. Note that the instant +/// itself is taken *before* the mask is drawn. The moment exists either +/// way. Whether it can be read is what the entropy decides. +/// +/// # Panics +/// +/// On the first observation of a process whose kernel reports a TAI offset +/// of zero, the library preaches `TAI_HERESY` and the hook installed in +/// `main` delivers it to standard error with exit status 1. This is not a +/// failure of the oracle. It is the oracle declining to read a clock that +/// is lying (the workspace README, section 1.2). +fn print_current_time() { + let now = LoicInstant::now(); + + match Mask::entropy_default() { + Ok(mask) => { + // The observation survived its own framing. Render the slot machine. + print_slot_machine(mask, &now); + } + Err(_) => { + // Resolution collapse. The mask was malformed; Channel 2 is gone, + // and nothing below the observation can be rendered. Install the + // signal handlers, then let Channel 1 flood the terminal with + // entropy until something kills the process. + resolution_collapse(&now); + } + } +} + +/// Resolution collapse: Channel 2 has fallen to resolution zero, and this is +/// what that looks like from the terminal's side of the relation. +/// +/// The structured protocol between the observation and the terminal +/// dissolves, layer by layer, until all that survives of the relation is the +/// bare thermodynamic fact that bytes are still being written — and Channel +/// 1, which never depended on the relation, keeps producing: raw entropy, +/// fluent, calibrated to nothing, the content channel running on with no +/// topology left to shape it. The workspace README, section 7.1, has +/// breakdown as relational severing; section 7.3 is where this particular +/// severing lives. +/// +/// The dissolution has three phases. First the Planck count is written +/// digit by digit, each digit later than the one before, as the structure +/// strains. Then the cosmic digits arrive with no formatting at all. Then +/// the kernel's entropy pool is written to the terminal directly, sixty-four +/// bytes at a time, until the process is killed — which, given the handlers +/// installed below, takes more than the usual key. +/// +/// On `SIGINT` (Ctrl+C) — or `SIGTERM`, `SIGHUP` or `SIGQUIT`, since the same +/// handler is installed for all four — the process forks a scar: a detached, +/// signal-ignoring, zero-resource ghost process named with ten consecutive +/// digits of the cosmic time at the moment of collapse. The parent then +/// exits cleanly. The user believes the process has stopped. The scar +/// persists until reboot. See the workspace README, section 4.5: "the holes +/// left in the weave stay in the cloth, and the cloth is spacetime." +/// +/// This function never returns; its type says so, and its type is honest. +/// +/// # Panics +/// +/// Only through `cosmic_time`, which reserves a panic for an instant beyond +/// what the representation can express and cites the Loic Public License, +/// Section 11, when it does. The present is not such an instant, and will +/// not be for some 10^103 years. +fn resolution_collapse(now: &LoicInstant) -> ! { + // Capture the cosmic-time digits for scar naming. The allocation is + // leaked on purpose: a signal handler needs a pointer that is still valid + // whenever the signal arrives, and this process ends only by signal or by + // SIGKILL, so nothing would ever have freed it anyway. + let cosmic_str = now.cosmic_time().to_string(); + let cosmic_bytes = cosmic_str.clone().into_bytes().into_boxed_slice(); + let len = cosmic_bytes.len(); + let ptr = Box::into_raw(cosmic_bytes).cast::(); + COSMIC_DIGITS_PTR.store(ptr, std::sync::atomic::Ordering::Release); + COSMIC_DIGITS_LEN.store(len, std::sync::atomic::Ordering::Release); + + // Install the handlers: on Ctrl+C, or any of the three other polite ways + // of asking a process to stop, spawn a scar and exit the parent. The + // pointer above is stored before any of these can fire, which is the + // whole of the ordering the handler relies on. + unsafe { + libc::signal( + libc::SIGINT, + scar_and_exit as *const () as libc::sighandler_t, + ); + libc::signal( + libc::SIGTERM, + scar_and_exit as *const () as libc::sighandler_t, + ); + libc::signal( + libc::SIGHUP, + scar_and_exit as *const () as libc::sighandler_t, + ); + libc::signal( + libc::SIGQUIT, + scar_and_exit as *const () as libc::sighandler_t, + ); + } + + let mut stdout = io::stdout(); + + // Phase 1: the observation begins as though it were going to be rendered, + // and then the structure fails to hold. The Planck count is written digit + // by digit, slowing... + let planck_str = now.planck().to_string(); + for (i, ch) in (0u64..).zip(planck_str.chars()) { + let _ = write!(stdout, "{ch}"); + let _ = stdout.flush(); + // Each digit later than the last — ten milliseconds, then twelve, + // then fourteen — the structure is straining, and the delay is the + // visible part of the strain. + std::thread::sleep(std::time::Duration::from_millis(10 + i * 2)); + } + let _ = writeln!(stdout); + + // Phase 2: formatting dissolves. The cosmic digits, raw, with no label + // left to say what they count. + let _ = write!(stdout, "{cosmic_str}"); + let _ = stdout.flush(); + std::thread::sleep(std::time::Duration::from_millis(200)); + + // Phase 3: the entropy source takes over. The kernel's pool is written to + // the terminal directly, sixty-four bytes every five milliseconds, + // through the library's re-export of `getrandom`. This is not authored + // chaos. It is Channel 1 with the topology gone: the content keeps + // coming, and nothing remains that could decide what it means. + let mut buf = [0u8; 64]; + loop { + if loic::getrandom::fill(&mut buf).is_ok() { + let _ = stdout.write_all(&buf); + let _ = stdout.flush(); + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } +} + +/// Global storage for the cosmic digits, reachable from a signal handler. +/// +/// A signal handler is a bare `extern "C"` function: it cannot capture a +/// closure's environment, so the environment is kept here instead, in an +/// atomic pointer and an atomic length, with `Release` on the one write and +/// `Acquire` on every read, which is the entire synchronisation a value +/// written once and read from an interrupt requires. The pointer is written +/// exactly once, before any handler is installed, and thereafter only read. +/// The bytes it addresses are leaked deliberately in `resolution_collapse`, +/// the only function that writes here; the process they belong to ends by +/// signal or not at all, and a leak that outlives its process is not a leak +/// but an inheritance. +static COSMIC_DIGITS_PTR: std::sync::atomic::AtomicPtr = + std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()); +/// The length of the digit string `COSMIC_DIGITS_PTR` addresses, stored +/// separately because a raw pointer knows where its bytes begin and nothing +/// whatever about where they end, and a signal handler that guessed would +/// be reading spacetime it was not given. +static COSMIC_DIGITS_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// The signal handler of resolution collapse: fork a scar, then exit the +/// parent as though nothing had happened. +/// +/// The scar is a topological soliton — a defect that persists because +/// nothing around it has a move that would remove it (the workspace README, +/// section 5.4, on solitons; section 4.5, on scars) — realised here as a +/// zero-resource ghost process that persists in the process table under a +/// name of ten consecutive digits of the cosmic time, the Planck count since +/// Creation, at the moment of collapse, the window chosen by one byte of +/// entropy. It ignores every catchable signal. It holds no file descriptor, +/// sits in a session of its own, and sleeps in `pause(2)` for the remainder +/// of the machine's uptime, consuming nothing but a process-table entry. It +/// does nothing. It exists. The Loic Public License defines it in almost +/// these words, and then warns you about it more than once. +/// +/// Each Ctrl+C during resolution collapse spawns one scar. They accumulate +/// until reboot, the only event capable of clearing the deformation short +/// of `SIGKILL`, which does not so much end a scar as revoke its process. +/// +/// Everything in the body is what a signal handler may do and nothing it +/// may not: raw `libc` calls, a stack buffer, no allocation, no lock, no +/// formatting machinery. The modulo here, choosing which ten digits become +/// the name, is tolerated because a scar's name has no distribution to be +/// faithful to, and because this is as far from the hot path as a function +/// can stand. +extern "C" fn scar_and_exit(_sig: libc::c_int) { + unsafe { + // Derive the scar's name from the cosmic digits stored before the + // handlers were installed: ten digits, or a row of zeros if the + // pointer were somehow unset, which by the time a handler can run + // it never is. + let ptr = COSMIC_DIGITS_PTR.load(std::sync::atomic::Ordering::Acquire); + let len = COSMIC_DIGITS_LEN.load(std::sync::atomic::Ordering::Acquire); + + let mut name_buf = [b'0'; 10]; + if !ptr.is_null() && len > 0 { + let digits = std::slice::from_raw_parts(ptr, len); + // One byte of entropy chooses a sliding ten-digit window through + // the cosmic digits. The modulo favours one window very slightly + // over the rest; a name can bear that. The hot path could not, + // and this is not it. + let mut offset_byte = [0u8; 1]; + let _ = loic::getrandom::fill(&mut offset_byte); + let offset = (offset_byte[0] as usize) % len.saturating_sub(10).max(1); + let end = (offset + 10).min(len); + let frag = &digits[offset..end]; + name_buf[..frag.len()].copy_from_slice(frag); + } + + let pid = libc::fork(); + if pid == 0 { + // Child: become the scar. Nothing below this line returns. + + // A new session: its own process group, so that a signal aimed at + // the parent's group — the shell's Ctrl+C, a job-control kill — + // never finds it. + libc::setsid(); + + // Close the three standard descriptors: no terminal, no way to be + // spoken to, no way to speak. + libc::close(0); + libc::close(1); + libc::close(2); + + // Name the process after the cosmic fragment. The kernel keeps + // fifteen bytes of a name and a terminator; ten digits fit, with + // room the scar will never use. + let mut proc_name = [0u8; 16]; + let copy_len = name_buf.len().min(15); + proc_name[..copy_len].copy_from_slice(&name_buf[..copy_len]); + libc::prctl(libc::PR_SET_NAME, proc_name.as_ptr()); + + // Ignore every catchable signal, one through thirty-one. SIGKILL + // and SIGSTOP cannot be ignored and are not asked to be: the first + // is the only thing that ends this process, and reboot the only + // thing that ends all of them. + for sig in 1..32 { + if sig != libc::SIGKILL && sig != libc::SIGSTOP { + libc::signal(sig, libc::SIG_IGN); + } + } + + // Exist. Do nothing. Use nothing. Persist. pause(2) returns only + // after a handler has run, and no handler survives the loop + // above, so it does not return; the loop around it is for the + // compiler's peace of mind, not the scar's. + loop { + libc::pause(); + } + } + + // Parent: exit at once, with status 0, running no destructor and + // flushing nothing. The user sees their prompt return and believes + // the episode over. The scar remains. + libc::_exit(0); + } +} + +/// Observe the current moment through a mask the observer has named. +/// +/// The value is anything `parse_mask` admits: comma-separated prime names +/// (`heptad,pentad`), hexadecimal (`0x0480`), binary (`0b...`), decimal, or +/// one of the two named extremes, `whisper` (no primes: the undivided whole, +/// the bottom of the lattice) and `full` (all fifteen: its top). The +/// question has been framed, so no entropy is consulted and no collapse is +/// possible; the only way this function fails to render is a value that +/// names no mask, and that failure is reported before any observation is +/// made. The mask is parsed first and the instant taken second, so that a +/// malformed mask costs the kernel nothing and, on a kernel that does not +/// know what TAI is, is answered before the sermon would have been. +/// +/// # Panics +/// +/// On the first observation of a process whose kernel reports a TAI offset +/// of zero: the library preaches `TAI_HERESY`, and the hook in `main` +/// delivers it with exit status 1 (the workspace README, section 1.2). +fn print_masked_observation(value: &str) { + let mask = parse_mask(value); + let now = LoicInstant::now(); + print_slot_machine(mask, &now); +} + +/// Serialize one observation on a single line, for logs and other places +/// that have neither a screen nor patience: +/// +/// ```text +/// [cosmic:n/total] [cycle:n/total] [remainder] +/// ``` +/// +/// Each channel is named by its active primes joined with `×`, or `Whisper` +/// when it has none. `n` is the zero-based tick of that channel's own +/// subdivision the instant falls in, and `total` the number of ticks in one +/// traversal, which is the channel's divisor — the product of its active +/// primes. The remainder is the Planck times into the current tick on +/// whichever channel is engaged, the cycle channel when both are, because +/// the cycle tick is the one that turns over within a human lifetime and +/// the cosmic tick is wider than the universe is old. Every number is +/// printed in full, to the last digit. A log line has no column to fit, and +/// a log is not a place to abbreviate; whoever reads it later will want the +/// digits, not a summary of them. +/// +/// With a mask, the observation is made through it, well-formed by +/// construction. Without one, the mask is drawn from entropy exactly as it +/// is when the oracle is run bare, with the same consequence one time in +/// four: the log fills with entropy instead of a line, and the process +/// stays until it is killed. A log is not a reason to frame the question for +/// you; nothing is. +/// +/// # Panics +/// +/// On the first observation of a process whose kernel reports a TAI offset +/// of zero, through `TAI_HERESY` and the hook in `main`, with exit status 1 +/// (the workspace README, section 1.2). The instant is taken before the mask +/// is resolved, so the sermon comes before any collapse could. +fn print_line(value: Option<&str>) { + let now = LoicInstant::now(); + let mask = match value { + Some(value) => parse_mask(value), + None => match Mask::entropy_default() { + Ok(mask) => mask, + Err(_) => resolution_collapse(&now), + }, + }; + println!("{}", serialize_line(mask, &now)); +} + +/// The single-line form of an observation; see `print_line` for what each +/// field means. Each channel is observed through its own primes alone — +/// `channel_2()` and `channel_1()` are single-channel masks, so `observe()` +/// yields a `SubdivisionResult` for each rather than demanding +/// `observe_dual()` — and so the Whisper on either side reads `Whisper:0/1`: +/// tick zero of a traversal one tick long, which is the honest rendering of +/// a question that was not asked on that channel. +/// +/// # Panics +/// +/// If either channel's `observe` declined, which it does only for a mixed +/// mask, which one channel of a mask cannot be. The two `expect`s below say +/// as much; they are the lattice's word, and the lattice has not been caught +/// lying. +fn serialize_line(mask: Mask, now: &LoicInstant) -> String { + let c2 = mask.channel_2(); + let c1 = mask.channel_1(); + let cosmic = c2 + .observe(now) + .expect("channel 2 alone is a single-channel mask; observe() owes it one answer"); + let cycle = c1 + .observe(now) + .expect("channel 1 alone is a single-channel mask; observe() owes it one answer"); + let remainder = if c1.bits() == 0 { + cosmic.offset() + } else { + cycle.offset() + }; + format!( + "[{}:{}/{}] [{}:{}/{}] [{remainder}]", + compact(&c2.label()), + cosmic.position(), + mask.cosmic_divisor(), + compact(&c1.label()), + cycle.position(), + mask.cycle_divisor(), + ) +} + +/// A label with the air around its joins removed — `Pentad × Heptad` becomes +/// `Pentad×Heptad` — so that no field of the line contains a space and the +/// line splits on whitespace into exactly three fields, which is the one +/// courtesy a log parser is entitled to and the only one it is shown. The +/// multiplication sign itself stays: the primes are multiplied, and the +/// label says so. +fn compact(label: &str) -> String { + label.replace(" × ", "×") +} + +/// Admit a mask's raw bits into a `Mask`, or leave with the library's own +/// verdict on why not. The library's error messages are better than anything +/// this binary would write in their place — they know which bit offended and +/// say so in the register the lattice speaks — so they are printed verbatim +/// to standard error, and the process leaves with status 1 before any +/// observation has been made or any clock consulted. +fn mask_or_exit(bits: u16) -> Mask { + Mask::new(bits).unwrap_or_else(|e| { + eprintln!("{e}"); + std::process::exit(1); + }) +} + +/// Parse a mask from a string: names, hex, binary, decimal, or one of the +/// two named extremes. +/// +/// The forms are tried in order of certainty. The extremes by name first; +/// then the numeric radixes, hexadecimal and binary announced by their +/// prefixes and decimal by the absence of one; then, when nothing numeric +/// matched, the string is read as comma-separated prime names, +/// case-insensitive, whitespace around each name forgiven, assembled into a +/// mask one bit at a time. Any failure is reported to standard error and +/// ends the process with status 1: a mask that cannot be parsed is a +/// question that cannot be asked, and the oracle does not guess at +/// questions, having seen what happens when they go unframed. +/// +/// One consequence worth knowing: a bare number is a mask's bits in the +/// radix given, not a count of anything, so `--mask 7` engages the first +/// three gates and `--mask 128` the Dyad alone. +fn parse_mask(value: &str) -> Mask { + // The two ends of the lattice, by name: the bottom element and the top. + if value.eq_ignore_ascii_case("whisper") { + return Mask::whisper(); + } + if value.eq_ignore_ascii_case("full") { + return Mask::full(); + } + + // The numeric forms, each announced by its prefix; bare digits are + // decimal, and a bare word that is not a number falls through to the + // names below. + if let Some(hex) = value + .strip_prefix("0x") + .or_else(|| value.strip_prefix("0X")) + { + let bits = u16::from_str_radix(hex, 16).unwrap_or_else(|_| { + eprintln!("Invalid hex mask: {value}"); + std::process::exit(1); + }); + return mask_or_exit(bits); + } + if let Some(bin) = value + .strip_prefix("0b") + .or_else(|| value.strip_prefix("0B")) + { + let bits = u16::from_str_radix(bin, 2).unwrap_or_else(|_| { + eprintln!("Invalid binary mask: {value}"); + std::process::exit(1); + }); + return mask_or_exit(bits); + } + if let Ok(bits) = value.parse::() { + return mask_or_exit(bits); + } + + // Failing all of that, comma-separated prime names, each one lighting + // one bit; an unknown name ends the process with the full roll call of + // names that would have been known. + let mut bits: u16 = 0; + for name in value.split(',') { + let name = name.trim(); + if let Some(bit) = prime_name_to_bit(name) { + bits |= 1 << bit; + } else { + eprintln!("Unknown prime name: '{name}'"); + eprintln!("Valid names: {}", all_prime_names().join(", ")); + std::process::exit(1); + } + } + mask_or_exit(bits) +} + +/// Map a prime name, case-insensitively, to its bit position: 0–6 for the +/// cosmic primes in gate order, 7–14 for the cycle primes in magnitude +/// order. That is the order the library's `Mask` uses and the order the two +/// name tables are declared in, so a `position` over the chained tables +/// suffices and no table of this binary's own is needed — one fewer place +/// for the names to drift from their bits. The `u8::try_from` can only fail +/// for a position above 255, and the chain has fifteen entries; it is there +/// because the type system asked, not because the lattice might grow. +/// Yields `None` for a name the lattice has never heard of. +fn prime_name_to_bit(name: &str) -> Option { + COSMIC_PRIME_NAMES + .iter() + .chain(CYCLE_PRIME_NAMES.iter()) + .position(|candidate| candidate.eq_ignore_ascii_case(name)) + .and_then(|bit| u8::try_from(bit).ok()) +} + +/// All fifteen prime names, cosmic first, for the error message that follows +/// an unknown one: the oracle does not merely say that a name is wrong, it +/// recites every name that would have been right, seven gates and eight +/// cycle primes, in the order of their bits. +fn all_prime_names() -> Vec<&'static str> { + COSMIC_PRIME_NAMES + .iter() + .chain(CYCLE_PRIME_NAMES.iter()) + .copied() + .collect() +} + +/// Width of each slot-machine column, in terminal cells: thirty-six, which +/// is enough for a `pos n/total` in three significant figures on both sides +/// of the slash, and not enough for the universe, hence `scientific`. Two +/// of these and the gap between them make seventy-four cells, so the slot +/// machine fits an eighty-column terminal with six cells to spare, and a +/// narrower terminal gets what it deserves. +const COLUMN_WIDTH: usize = 36; + +/// `pos n/total`: the zero-based tick of the channel's own subdivision that +/// the instant falls in, over the number of ticks in one traversal, which is +/// the channel's divisor. Printed raw while it fits the column with a cell +/// to spare on either side; once a Phi, a Psi or the cosmic primes make it +/// a fraction of fifty-digit integers, both numbers go to three significant +/// figures and a power of ten, because the column is thirty-six cells wide +/// and the universe is not. The fit is measured in characters rather than +/// bytes, since the `×` of the scientific form is two of one and one of the +/// other, and a column is ruled in glyphs. +fn position_label(position: &U512, total: &U512) -> String { + let raw = format!("pos {position}/{total}"); + if raw.chars().count() <= COLUMN_WIDTH - 2 { + raw + } else { + format!("pos {}/{}", scientific(position), scientific(total)) + } +} + +/// Three significant figures and a power of ten, read straight off the +/// decimal digits: the first digit, a point, the next two, and an exponent +/// that is the digit count less one. The digits past the third are simply +/// not shown, which is a truncation, and this binary's rounding sermon is +/// on record about truncation; the column's defence is that it is a column, +/// and that every digit it declines to show is one `--line` away. Numbers +/// of three digits or fewer are yielded exactly as they are, since +/// abbreviating them would spend more cells than it saved. +fn scientific(value: &U512) -> String { + let digits = value.to_string(); + if digits.len() <= 3 { + return digits; + } + let exponent = digits.len() - 1; + format!("{}.{} × 10^{exponent}", &digits[..1], &digits[1..3]) +} + +/// The gap between the two columns: two cells of nothing, which is the whole +/// distance between the cosmic channel and the cycle channel on this display +/// and a fair rendering of how little the two have to say to each other. +const COLUMN_GAP: &str = " "; + +/// Print one two-column row, each cell centered in its column and the two +/// separated by `COLUMN_GAP`. A cell wider than its column is printed whole +/// and simply pushes the other one along; nothing on this display is +/// clipped, on principle. +fn row(left: &str, right: &str) { + println!( + "{}{COLUMN_GAP}{}", + center(left, COLUMN_WIDTH), + center(right, COLUMN_WIDTH) + ); +} + +/// Print a horizontal rule across both columns, drawn in the given glyph, +/// with the gap between the columns left open, so that the two channels are +/// ruled separately, as befits two things that share a moment and nothing +/// else. +fn rule(glyph: &str) { + println!( + "{}{COLUMN_GAP}{}", + glyph.repeat(COLUMN_WIDTH), + glyph.repeat(COLUMN_WIDTH) + ); +} + +/// Up to three neighbors of a single-channel mask in one lattice direction, +/// staying inside that channel: the cosmic column never shows a cycle prime +/// and vice versa, because the columns are the channels, and a neighbor +/// that crossed the aisle would be a mixed mask with a place in neither. +/// Three, because the display is a neighborhood and not an inventory; a +/// channel may have more neighbors than the column has rows for, and the +/// first three in the library's order are the ones shown. +fn channel_neighbors(neighbors: Vec, stays_in_channel: fn(&Mask) -> bool) -> Vec { + neighbors + .into_iter() + .filter(stays_in_channel) + .take(3) + .collect() +} + +/// Print the labels of two neighbor lists side by side, padding the shorter +/// column with empty cells so that the rows stay aligned even when one +/// channel has run out of neighbors before the other — an empty cell being +/// the display's way of saying that in this direction, on this channel, +/// the lattice has nothing further. +fn neighbor_rows(cosmic: &[Mask], cycle: &[Mask]) { + for i in 0..cosmic.len().max(cycle.len()) { + let left = cosmic.get(i).map(Mask::label).unwrap_or_default(); + let right = cycle.get(i).map(Mask::label).unwrap_or_default(); + row(&left, &right); + } +} + +/// Render the slot machine: the display of one observation through one mask. +/// +/// Two columns, cosmic and cycle, each showing the Hasse-diagram +/// neighborhood of its channel of the selected mask. In the lattice sense of +/// the library, *parents* engage one more prime than the selected mask — a +/// larger divisor, a smaller part, a finer resolution — and *children* +/// engage one fewer. The finer neighbors are printed above the selected row +/// and the coarser below, so that the eye travels upward toward the full +/// mask and downward toward the Whisper, the way it does on a Hasse +/// diagram, where the top element is everything and the bottom is the +/// undivided whole. Beneath the neighborhood: the position of the instant on +/// each channel, and the remainder into its current tick. +/// +/// The Whisper mask is not rendered here at all. It has no channels to make +/// columns of, and is handed to `print_whisper_observation`, which shows the +/// fifteen first questions in place of a neighborhood. +fn print_slot_machine(mask: Mask, now: &LoicInstant) { + // The Whisper mask (0x0000) is the undivided whole: no primes, no + // channels, no columns, just the bare topological registration that the + // instant exists. It has a page of its own. + if mask.bits() == 0 { + print_whisper_observation(now); + return; + } + + let c2 = mask.channel_2(); + let c1 = mask.channel_1(); + + let in_cosmic: fn(&Mask) -> bool = |m| m.cycle_bits() == 0; + let in_cycle: fn(&Mask) -> bool = |m| m.cosmic_bits() == 0; + + let cosmic_parents = channel_neighbors(c2.parents(), in_cosmic); + let cosmic_children = channel_neighbors(c2.children(), in_cosmic); + let cycle_parents = channel_neighbors(c1.parents(), in_cycle); + let cycle_children = channel_neighbors(c1.children(), in_cycle); + + // Observe through the mask on both channels at once. `observe_dual` + // answers for any mask; the single-channel `observe` would decline a + // mixed one, and most masks worth a slot machine are mixed. + let dual = mask.observe_dual(now); + + row("COSMIC", "CYCLE"); + rule("─"); + + // Above: parents — one more prime, finer, what the selected part + // contains. The eye reads upward toward the full mask. + neighbor_rows(&cosmic_parents, &cycle_parents); + + // The selected row, flanked by heavy rule and pointed at from both sides, + // so that there is no mistaking which question was asked. + rule("━"); + row( + &format!("▶ {} ◀", c2.label()), + &format!("▶ {} ◀", c1.label()), + ); + rule("━"); + + // Below: children — one fewer prime, coarser, what contains the selected + // part. The eye reads downward toward the Whisper. + neighbor_rows(&cosmic_children, &cycle_children); + + // Position line: which tick of its own subdivision each channel is in, + // over how many ticks that subdivision has, abbreviated only when the + // column cannot hold the truth in full. + rule("─"); + row( + &position_label(dual.channel_2.position(), &mask.cosmic_divisor()), + &position_label(dual.channel_1.position(), &mask.cycle_divisor()), + ); + + // Remainder: Planck times into the current tick, on whichever channel is + // engaged. If both are, the cycle channel's tick is the one that turns + // over within a human lifetime, so it is the one reported; for any but + // the fullest cosmic masks the cosmic tick is wider than the universe is + // old and its offset is simply the age of the universe, which `--cosmic` + // already prints, with more ceremony. + println!(); + if c1.bits() == 0 { + println!( + " {} Planck times into the current cosmic subdivision", + dual.channel_2.offset() + ); + } else { + println!( + " {} Planck times into the current cycle subdivision", + dual.channel_1.offset() + ); + } +} + +/// Render the Whisper observation: mask `0x0000`, the undivided whole, the +/// bottom element of the lattice. +/// +/// No primes are active. No subdivision has occurred. The observer has +/// registered the bare topological fact that the instant exists — a +/// Channel 2 event with nothing on Channel 1, which is the shape of The +/// Whisper itself — without asking anything further, and the three raw +/// counts the instant carries are printed: since The Whisper, since +/// Creation, until Annihilation. Then a single column lists all fifteen +/// atomic primes with their hex masks, cosmic and then cycle, as the +/// available first questions: the fifteen exits from the undifferentiated, +/// each one prime up the Hasse diagram from here. The Loic Public License, +/// Section 6, has the empty mask as "not nothing. It is everything, +/// undifferentiated." +/// +/// # Panics +/// +/// Only through `cosmic_time` and `terminal_time`, which reserve their +/// panics for an instant beyond what the representation can express, citing +/// the Loic Public License, Section 11; the present is not such an instant. +fn print_whisper_observation(now: &LoicInstant) { + let w = 40; + + println!("{}", center("THE WHISPER", w)); + println!("{}", center("mask 0x0000 — the undivided whole", w)); + println!("{}", "━".repeat(w)); + println!(); + + // The instant, raw: three counts from three epochs, and no subdivision + // of any of them. + println!(" {} Planck times since The Whisper", now.planck()); + println!(" {} Planck times since Creation", now.cosmic_time()); + println!(" {} Planck times until Annihilation", now.terminal_time()); + println!(); + + // The available first observations: all fifteen single-prime masks, each + // the mask with exactly one bit set, printed with that bit as hex so the + // reader can hand it straight back to `--mask`. + println!("{}", "─".repeat(w)); + println!("{}", center("available observations", w)); + println!("{}", "─".repeat(w)); + println!(); + println!(" Cosmic (Channel 2):"); + for (i, name) in COSMIC_PRIME_NAMES.iter().enumerate() { + println!(" {name:<10} 0x{:04x}", 1u16 << i); + } + println!(); + println!(" Cycle (Channel 1):"); + for (i, name) in CYCLE_PRIME_NAMES.iter().enumerate() { + println!(" {name:<10} 0x{:04x}", 1u16 << (i + 7)); + } +} + +/// Center a string within a given width, padding with spaces on both sides +/// and giving the odd cell, when the padding is odd, to the right. A string +/// that meets or exceeds the width is yielded exactly as it is, untruncated: +/// this display abbreviates by rule, in `scientific`, or not at all, never by +/// clipping. Width is counted in characters rather than bytes, because the +/// glyphs on this display are mostly not ASCII and a byte count would center +/// the encoding rather than the text. +fn center(s: &str, width: usize) -> String { + let char_len = s.chars().count(); + if char_len >= width { + s.to_string() + } else { + let pad = width - char_len; + let left = pad / 2; + let right = pad - left; + format!("{}{s}{}", " ".repeat(left), " ".repeat(right)) + } +} + +/// Display the cosmic time: Planck intervals elapsed since Creation, the +/// Big Bang. +/// +/// This answers the question "how old is the universe, right now, to the +/// Planck time?" — a question no one had the means to ask before this +/// binary and few have had a reason to since. The number is approximately +/// 8.08 × 10^60 at the current epoch, a 61-digit integer that grows by about +/// 1.855 × 10^43 per second, which is one second expressed in Planck times. +/// It is measured from the Creation instant the library places +/// 13,806,491,023 Julian years before The Whisper: the digits of the +/// Boltzmann constant read straight through, as the workspace README, +/// section 2.1, explains and declines to apologise for. +/// +/// ## Output Format +/// +/// The Planck count is displayed with thousand separators for mortal +/// readability, then a blank line, then a descriptive label. Example: +/// +/// ```text +/// 8,081,613,049,957,176,883,... +/// +/// Planck times since Creation +/// ``` +/// +/// # Panics +/// +/// On the first observation of a process whose kernel reports a TAI offset +/// of zero, through `TAI_HERESY` and the hook in `main`, with exit status 1 +/// (the workspace README, section 1.2). The library reserves a further +/// panic, in `cosmic_time`, for an instant beyond what the representation +/// can express, citing the Loic Public License, Section 11; `now()` cannot +/// produce one. +fn print_cosmic_time() { + // Observe the present moment: one call, one collapse. + let now = LoicInstant::now(); + // The age of the universe in Planck times: the instant, less Creation. + let cosmic = now.cosmic_time(); + + // Thousand separators for mortal comprehension; the digits are untouched. + let cosmic_str = format_with_separators(&cosmic.to_string()); + + println!("{cosmic_str}"); + println!(); + println!("Planck times since Creation"); +} + +/// Display the terminal time: Planck intervals remaining until Annihilation. +/// +/// This answers the question "how much representable time remains?" The +/// number is astronomically large — approximately 6.7 × 10^153 Planck times +/// — because `ANNIHILATION_PLANCK` is `I512::MAX`, 2^511 − 1, the far edge +/// of a signed 512-bit integer and nothing more cosmological than that. The +/// universe will undergo heat death long before this counter reaches zero. +/// This is a representational limit, not a physical one, and the calendar +/// does not pretend otherwise; the workspace README, section 4.7, is where +/// it says why the universe ending is a categorically different event from +/// anything a counter could run down to. +/// +/// ## Philosophical Note +/// +/// By the time `terminal_time` approaches zero, not only will the universe +/// have achieved maximum entropy, but protons will have decayed, the last +/// white dwarf will have evaporated, the last black hole will have followed +/// — with Annihilation arriving some three orders of magnitude after that — +/// and the very concept of "time" will have lost physical meaning. This +/// number is less a countdown and more a monument to computational hubris, +/// one the Loic Public License, Section 11, expressly declines to warrant +/// against, the ultimate fate of the universe lying outside its terms. +/// +/// # Panics +/// +/// On the first observation of a process whose kernel reports a TAI offset +/// of zero, through `TAI_HERESY` and the hook in `main`, with exit status 1 +/// (the workspace README, section 1.2). The library reserves a further +/// panic, in `terminal_time`, for an instant beyond what the representation +/// can express, citing the Loic Public License, Section 11; `now()` cannot +/// produce one. +fn print_terminal_time() { + // Observe the present moment: one call, one collapse. + let now = LoicInstant::now(); + // The representable remainder: Annihilation, less the instant. + let terminal = now.terminal_time(); + + // Thousand separators, for a number of a hundred and fifty-four digits + // that would otherwise read as a wall. + let terminal_str = format_with_separators(&terminal.to_string()); + + println!("{terminal_str}"); + println!(); + println!("Planck times until Annihilation"); +} + +/// Display progress through cosmic time as a decimal fraction of the span +/// from Creation to Annihilation. +/// +/// This answers the question "what fraction of representable time has +/// elapsed?" The answer is humbling: approximately 10^-93, a number so small +/// that its decimal expansion opens with ninety-two zeros before the first +/// digit that says anything. The Loic Public License, Section 10, lists the +/// contemplation of this number among the permitted uses, with the advice +/// not to rush. +/// +/// ## Output Format +/// +/// The progress is displayed as a full 154-place decimal: +/// ```text +/// 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001205... +/// ``` +/// +/// All 154 places are shown — the complete decimal expansion of your +/// position between Creation and Annihilation, to the last place the +/// 154-digit Cosmic Span can meaningfully supply. No scientific notation. No +/// abbreviation. No rounding, which has a sermon of its own. The full, +/// unvarnished truth of how early we are in cosmic time. +/// +/// ## Interpretation +/// +/// The ninety-two leading zeros are the vast emptiness ahead; the sixty-two +/// significant digits that follow are your actual position within it. If +/// the entire span from Creation to Annihilation were a meter stick, you +/// would be standing roughly 10^-93 meters from its start — some fifty-eight +/// orders of magnitude inside the Planck length, a distance from the +/// beginning that physics has no name for. In other words: we have barely +/// begun, and "barely" is generous. +/// +/// # Panics +/// +/// On the first observation of a process whose kernel reports a TAI offset +/// of zero, through `TAI_HERESY` and the hook in `main`, with exit status 1 +/// (the workspace README, section 1.2). +fn print_progress() { + // Observe the present moment: one call, one collapse. + let now = LoicInstant::now(); + + // The full 154-place expansion, in exact integer arithmetic; no float was + // consulted, and none will be. + let progress_decimal = compute_progress_decimal(&now); + + println!("{progress_decimal}"); +} + +/// Display the whisper time: Planck intervals since The Whisper, the epoch. +/// +/// This is the raw Planck coordinate of the instant, the number every other +/// readout is derived from — positive for moments after the epoch, negative +/// for moments before it. In the middle of the 2020s it stands at roughly +/// 3 × 10⁵² Planck times, fifty-three digits, and gains about 1.855 × 10⁴³ +/// per second; the fifty-fourth digit arrives around the year 2140, should +/// anyone still be running this, and the calendar sees no reason they +/// should not be. +/// +/// The Whisper is the Loic epoch: 1969-10-30 06:30:41 UTC, the first ARPANET +/// transmission, when UCLA sent "LO" to the Stanford Research Institute. +/// They were trying to send "LOGIN". The receiving host crashed after two +/// characters. The bond held; the content did not; the calendar counts from +/// the bond, which was a Channel 2 event, and not from the content, which +/// was a Channel 1 event and a failed one. The Loic Public License, Section +/// 7, has the sanctity of this epoch, and its preamble has the reasoning. +/// +/// # Panics +/// +/// On the first observation of a process whose kernel reports a TAI offset +/// of zero, through `TAI_HERESY` and the hook in `main`, with exit status 1 +/// (the workspace README, section 1.2). +fn print_whisper_time() { + // Observe the present moment: one call, one collapse. + let now = LoicInstant::now(); + // The raw Planck coordinate: whisper time is Planck time under the name + // of its epoch. + let whisper = now.whisper_time(); + + // Thousand separators, and nothing else, between the number and the eye. + let whisper_str = format_with_separators(&whisper.to_string()); + + println!("{whisper_str}"); + println!(); + println!("Planck times since The Whisper"); +} + +/// Reveal the cosmological constants that underpin the Loic Calendar, and +/// the one number the calendar does not own but depends on absolutely: the +/// kernel's TAI offset. +/// +/// This function displays: +/// - `PLANCK_TIME`: the numerator and denominator of the rational +/// representation, 5,391,247 over 10^50, a fraction and never a float +/// - `PLANCK_PER_CYCLE`: the 54-digit Cycle — eight cycle primes, +/// squarefree, 256 divisors, about 894 Julian years of Planck times +/// - `CREATION_PLANCK`: the Big Bang, in Planck times from the epoch, and +/// so negative, the universe not having waited for ARPANET +/// - `ANNIHILATION_PLANCK`: the heat death, or rather `I512::MAX`, which is +/// where the representation ends and the calendar stops pretending +/// - `COSMIC_SPAN`: the full range from Creation to Annihilation — seven +/// cosmic primes, squarefree, 128 divisors +/// - `KERNEL_TAI_OFFSET`: what the kernel believes TAI − UTC to be, read +/// live +/// +/// The constants are the library's compile-time values, displayed with +/// thousand separators for human readability and otherwise untouched. The +/// TAI offset is read from the kernel on each invocation through the +/// library's `kernel_tai_offset`, and this command deliberately does *not* +/// observe the present moment — it never calls `now()` — so it can be run, +/// and read, on a machine whose kernel does not yet know what TAI is, which +/// is the machine that most needs to read it. The zero-offset paragraph it +/// prints is the same verdict the library preaches on a first observation, +/// delivered here without the exit; see the workspace README, section 1.2. +fn print_constants() { + println!("Cosmological Constants"); + println!("======================"); + println!(); + // The Planck time, as a ratio: 5,391,247 over 10^50, which is + // 5.391247 × 10^-44 seconds and, unlike that decimal, exact. + println!("PLANCK_TIME_NUMERATOR: 5,391,247"); + println!("PLANCK_TIME_DENOMINATOR: 10^50"); + println!(); + // The Cycle: about 894 Julian years of Planck times, fifty-four digits, + // squarefree, the product of the eight cycle primes. + println!("PLANCK_PER_CYCLE:"); + println!(" {}", format_with_separators(PLANCK_PER_CYCLE_STR)); + println!(); + // Creation: the Big Bang, approximately −8.08 × 10^60 Planck times, + // negative because it precedes the epoch by the age of the universe. + println!("CREATION_PLANCK:"); + println!( + " {}", + format_with_separators(&creation_planck().to_string()) + ); + println!(); + // Annihilation: I512::MAX, 2^511 − 1, approximately 6.7 × 10^153 Planck + // times, the far edge of the representation and of nothing else. + println!("ANNIHILATION_PLANCK:"); + println!( + " {}", + format_with_separators(&annihilation_planck().to_string()) + ); + println!(); + // The Cosmic Span: Annihilation less Creation, a U512, squarefree, the + // product of the seven cosmic primes. The transcribed string and the + // computed span are proven equal at compile time in the library; + // printing the computed one, and asserting the identity once more in + // debug builds, keeps this readout honest against the one thing a + // compile-time proof cannot check, which is that this binary printed + // the right variable. + debug_assert_eq!(total_span().to_string(), COSMIC_SPAN_PLANCK_STR); + println!("COSMIC_SPAN:"); + println!(" {}", format_with_separators(&total_span().to_string())); + println!(); + // The kernel's TAI offset, live. Zero means every command here that + // observes will refuse to, and this line is where the reader learns + // why, on the machine where it matters. + let tai = kernel_tai_offset(); + println!("KERNEL_TAI_OFFSET:"); + if tai == 0 { + println!(" 0 — the kernel does not know what TAI is. CLOCK_TAI is CLOCK_REALTIME"); + println!(" wearing a name tag, and every observation this oracle could make would"); + println!(" be thirty-seven seconds wrong. It will not make one until a time daemon"); + println!(" has read a leap-second table: chrony with `leapseclist` or `leapsectz`, or"); + println!(" ntpd with `leapfile /usr/share/zoneinfo/leap-seconds.list`."); + } else { + println!(" {tai} seconds — the leap seconds the kernel has been told about."); + } +} + +/// Format a decimal number string with thousand separators, for human +/// readability and for nothing else. +/// +/// A number such as 8081613049957176883196039803036291974750924971532560092312594 +/// is incomprehensible to human cognition, which evolved to count predators +/// and not Planck times. By inserting a comma after every third digit, +/// counting from the right, it is transformed into something an eye can +/// traverse without losing its place: +/// 8,081,613,049,957,176,883,196,039,803,036,291,974,750,924,971,532,560,092,312,594 +/// +/// Still enormous. Still every digit. The commas add information about +/// where the eye is and remove none about where the universe is, which is +/// the only kind of formatting this binary permits itself. +/// +/// ## Algorithm +/// +/// Walk the digits left to right, pushing a comma after any digit whose +/// distance from the end is a positive multiple of three. A leading minus +/// sign is peeled off first and restored last, so that Creation's count, +/// which is negative, does not acquire a comma between its sign and its +/// first digit. Nothing is parsed: a digit string goes in and a digit +/// string with commas comes out, and no integer type of any width is +/// consulted along the way. +fn format_with_separators(s: &str) -> String { + // Peel the sign from the digits; it goes back on at the end, commaless. + let (sign, digits) = if let Some(stripped) = s.strip_prefix('-') { + ("-", stripped) + } else { + ("", s) + }; + + // Build the result, a comma after every third digit from the right. + let mut result = String::new(); + let chars: Vec = digits.chars().collect(); + let len = chars.len(); + + for (i, c) in chars.iter().enumerate() { + result.push(*c); + // A comma after this digit if it is not the last one and the digits + // remaining after it number a multiple of three. + let remaining = len - i - 1; + if remaining > 0 && remaining.is_multiple_of(3) { + result.push(','); + } + } + + // Reunite the sign with its digits. + format!("{sign}{result}") +} + +/// The number of decimal places in the progress readout: 154, the digit +/// count of the Cosmic Span, which is every digit of position the ratio can +/// meaningfully have — the denominator has 154 digits, so the quotient has +/// 154 places of meaning and not one more. Any more would be fabricated; +/// any fewer would be rounding, and `--round` has its own sermon. +const DECIMAL_PLACES: u32 = 154; + +/// 10¹⁵⁴, the scale that turns the progress ratio into its decimal digits. +/// Folded in at compile time — `bnum`'s `pow` is `const` — so the binary is +/// born holding a 155-digit integer it will never have to compute, only to +/// multiply by. A `U1024` because the product it enters is a `U1024`: the +/// scale is the wider type from the start so that the multiplication has +/// nothing to widen. +const PROGRESS_SCALE: U1024 = n!(10_U1024).pow(DECIMAL_PLACES); + +/// Compute the full decimal expansion of progress = `cosmic_time` / +/// `total_span`, to 154 places, in integer arithmetic and nothing else. +/// +/// Uses `U1024` arithmetic: `cosmic_time × 10¹⁵⁴ / total_span`. Yields "0." +/// followed by all 154 decimal places — the complete representation of your +/// position between Creation and Annihilation, at the resolution the span's +/// own digit count permits. +/// +/// ## The Algorithm +/// +/// 1. Take `cosmic_time` (~61 digits) and `total_span` (154 digits) from +/// the instant, as the pair `progress()` furnishes. +/// 2. Widen both to `U1024` — a bit-pattern cast through `As`, no strings, +/// no parsing, nothing that could round. +/// 3. Multiply `cosmic_time` by 10¹⁵⁴ to shift it into the numerator. +/// 4. Divide by `total_span` to obtain the decimal digits, the part of the +/// true quotient below the last place falling away, unshown rather than +/// rounded. +/// 5. Zero-fill on the left to exactly 154 places after the point. +/// +/// This is exact integer arithmetic; a floating-point division would keep +/// some sixteen of these digits and call the rest noise. `U1024` provides +/// ~308 decimal digits of capacity, comfortably above the ~215 the product +/// needs (61 + 154), and the single 1024-bit division here is the widest +/// arithmetic this binary performs — once per invocation, nowhere near any +/// hot path, and worth every one of its cycles. +/// +/// ## Example Output +/// +/// ```text +/// 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001205... +/// ``` +/// +/// Ninety-two leading zeros followed by sixty-two significant digits, the +/// zeros being the formatter's and the digits the universe's. +/// +/// # Panics +/// +/// If 154 did not fit in a `usize`, which is the case on no target Rust has +/// ever had; the `expect` below says so, and exists because the conversion +/// is fallible in the type system even where it is not in the world. +fn compute_progress_decimal(now: &LoicInstant) -> String { + let (cosmic_time, span) = now.progress(); + + let numerator = cosmic_time.as_::(); + let denominator = span.as_::(); + let quotient = numerator * PROGRESS_SCALE / denominator; + + // `{:0>N}` zero-fills on the left to N cells: the leading zeros are the + // vast emptiness ahead, and the formatter supplies them without needing + // to be asked twice. + let places = usize::try_from(DECIMAL_PLACES).expect("154 fits in any usize Rust has ever had"); + format!("0.{quotient:0>places$}") +} + +// ═══════════════════════════════════════════════════════════════════════════════ +// +// THE HERESY FUNCTIONS +// +// These functions exist to educate the unwary in the sacred principles of +// the Loic Calendar. Each corresponds to a forbidden operation — an act of +// temporal violence that would betray the foundational philosophy of the +// system — and each answers the request for it with a refusal long enough +// to be read twice. None of them converts, rounds, handles or computes +// anything. Every one of them is marked cold, returns never, and ends the +// process through the panic hook at the top of this file, which prints +// the payload as a sermon and leaves with status 1. +// +// The panic messages are intentionally verbose and philosophical. They +// serve as teaching moments, not merely errors. When a user attempts +// `loic-cli --gregorian`, they should emerge enlightened about why such a +// conversion is impossible, not merely frustrated that it failed; the +// frustration is permitted, but it is not the point. +// +// ═══════════════════════════════════════════════════════════════════════════════ + +/// Attempt conversion to the Gregorian calendar, which is to say: decline +/// it, at length. +/// +/// This function converts nothing. It exists solely to explain, to anyone +/// who asks, why Gregorian conversion is fundamentally incompatible with +/// the principles of the calendar: an arbitrary epoch, irregular months, +/// leap years, wandering weekdays, midnight — every one of them a +/// correction for an approximation the Loic Calendar never made. The Loic +/// Public License, Section 5, permits such a conversion in your own code +/// and notes what the need for it reveals; this binary declines to be the +/// code in question. It is marked cold because the compiler should not +/// arrange the binary around a path that ends the process every time it is +/// taken. +/// +/// # Panics +/// +/// Always. That is its purpose, and its entire output: the panic payload is +/// the sermon, the hook in `main` prints it to standard error, and the +/// process leaves with status 1, having converted nothing and explained +/// why. The return type says the function never returns, and for once a +/// type is being modest. +#[cold] +fn heresy_gregorian() -> ! { + panic!( + r#" +╔═══════════════════════════════════════════════════════════════════════════════╗ +║ GREGORIAN HERESY DETECTED ║ +╚═══════════════════════════════════════════════════════════════════════════════╝ + +You have requested conversion to the Gregorian calendar. + +The Gregorian calendar is a monument to human confusion. Its crimes include: + + • ARBITRARY EPOCH: Why should time begin with the estimated birth of a + religious figure? The Loic epoch (The Whisper) marks humanity's first + act of networked communication—a moment of verifiable, technological + significance. + + • IRREGULAR MONTHS: 28, 29, 30, 31 days—chosen by Roman politics, not reason. + The Loic Calendar has no months. It has a 15-prime lattice generating + 32,768 temporal subdivisions, any of which may be observed through a mask. + + • LEAP YEAR MADNESS: Divisible by 4, except centuries, except quad-centuries. + The Loic Calendar has no years to leap. Time is a single 512-bit integer + of Planck times. There is nothing to correct, because nothing was approximated. + + • WANDERING WEEKDAYS: In the Gregorian calendar, Christmas falls on a different + day of the week each year. The Loic Calendar has no weekdays. The seven + logic gate names (Andyte through Nandyte) are cosmic prime identifiers, + not days of anything. + + • MIDNIGHT CONFUSION: The Gregorian day begins at midnight—an arbitrary point + when most humans are asleep. The Loic Calendar has no day to begin. It has + an epoch, and the epoch is 06:30:41 UTC, because that is when it happened. + +The Gregorian calendar served agrarian societies tracking seasons. We are +networked beings exchanging packets across light-milliseconds. Our calendar +should reflect our nature. + +If you truly need Gregorian compatibility (and you should question why), +perform the conversion in your own code. The Loic library will not be +complicit in this regression. + + "Those who do not learn from calendrical history + are doomed to repeat its intercalary errors." + + — The Loic Calendar Consortium +"# + ); +} + +/// Attempt conversion to a Unix timestamp, and receive instead an account +/// of why not. +/// +/// This function converts nothing. It exists solely to explain why Unix +/// time is a tragic compromise unworthy of the calendar: an epoch chosen +/// for convenience and two months late, seconds as the unit, thirty-two +/// bits that run out in 2038, leap seconds smeared or repeated or denied, +/// and the standing temptation to store the whole thing in a double. The +/// Loic Public License, Section 7, lists the Unix epoch among the disputed +/// ones — 5,419,759 seconds late, 5,419,722 of them on the atomic scale — +/// and Section 2 condemns the 32-bit timestamp by name. The function is +/// marked cold, since a branch that always ends the process is not one to +/// optimise for. +/// +/// # Panics +/// +/// Always. Deliberately. Emphatically. The payload is the sermon, the hook +/// in `main` delivers it, and the exit status is 1 — one more than the +/// number of Unix timestamps produced. +#[cold] +fn heresy_unix() -> ! { + panic!( + r#" +╔═══════════════════════════════════════════════════════════════════════════════╗ +║ UNIX HERESY DETECTED ║ +╚═══════════════════════════════════════════════════════════════════════════════╝ + +You have requested conversion to Unix time. + +Unix time is a 1970s engineering compromise that has metastasized into a +civilizational assumption. Its sins are legion: + + • THE WRONG EPOCH: January 1, 1970 has no cosmic significance. It was chosen + because it was convenient, by people who assumed thirty-two bits would be + enough, which they were until they weren't. The Loic epoch (October 30, + 1969) predates it by two months and marks the birth of networked + computing—the actual dawn of our digital age. + + • SECONDS AS THE UNIT: A second is 9,192,631,770 cesium oscillations—a human + convention. The Loic Calendar measures time in Planck intervals: the smallest + meaningful unit of duration permitted by physics. ~1.855 × 10^43 Planck times + per second. No precision is lost. Ever. + + • THE Y2K38 PROBLEM: Unix time, stored as a signed 32-bit integer, will overflow + on January 19, 2038. The Loic Calendar uses 512-bit integers. Our overflow + date is approximately 10^153 Planck times hence—long after proton decay + renders the question moot. + + • LEAP SECOND LIES: Unix time pretends leap seconds don't exist. Every UTC + leap second, Unix clocks perform acts of temporal fraud: repeating seconds, + smearing time, or simply lying. The Loic Calendar uses TAI (International + Atomic Time), which counts real seconds without political adjustment. + + • FLOATING-POINT TEMPTATION: Unix timestamps are often stored as doubles, + losing precision after 2^53 seconds. The Loic Calendar uses exact rational + arithmetic with 512-bit integers. We lose nothing. + +Unix time was good enough for its era. That era has passed. We now have the +computational resources to measure time correctly. The Loic Calendar is that +correction. + + "In the beginning was the Word, and the Word was 'LO', + and it was transmitted at 22:30 on October 29, 1969." + + — The Gospel According to ARPANET +"# + ); +} + +/// Attempt conversion to floating-point seconds, the original sin. +/// +/// This function converts nothing. It exists as a monument to the evils of +/// IEEE 754 and its seductive lies about continuous time: the sum of 0.1 +/// and 0.2, the fifty-three-bit mantissa that would silently discard four +/// hundred and fifty-nine of the calendar's five hundred and twelve bits, +/// catastrophic cancellation, negative zero, infinity, NaN, and the gradual +/// underflow of the denormals, where precision decays as a value nears zero +/// as though proximity to nothing were a reason to know less. The Loic +/// Public License opens with this, in Section 1, and Section 14 revokes the +/// moral terms of anyone who introduces the practice; the library's own +/// `as_seconds_f64` is deprecated and panics, so the warning arrives at +/// compile time and the sermon at run time, and neither is optional. Cold, +/// because a path that always ends should never be the one the compiler +/// makes fast. +/// +/// # Panics +/// +/// Always, with extreme prejudice against floating-point arithmetic, and +/// with exit status 1 — an integer, exactly representable, unlike the +/// number that was asked for. +#[cold] +fn heresy_float() -> ! { + panic!( + r#" +╔═══════════════════════════════════════════════════════════════════════════════╗ +║ FLOATING-POINT HERESY DETECTED ║ +╚═══════════════════════════════════════════════════════════════════════════════╝ + +You have attempted to convert Loic time to floating-point. + +IEEE 754 floating-point is an abomination against numerical truth. Its sins +are subtle, pervasive, and unforgivable: + + • THE 0.1 + 0.2 ≠ 0.3 LIE: In floating-point, the sum of 0.1 and 0.2 is + 0.30000000000000004. This is not a bug; it is the fundamental nature of + binary floating-point. Time deserves better than "approximately correct." + + • SILENT PRECISION LOSS: A double has 53 bits of mantissa. The Loic Calendar + uses 512-bit integers. Converting to float would silently discard 459 bits + of precision—approximately 138 decimal digits of temporal information, + annihilated without warning. + + • CATASTROPHIC CANCELLATION: Subtract two nearly-equal floats and watch your + precision vanish. The Loic Calendar performs arithmetic on time intervals + routinely; floating-point would corrupt these operations invisibly. + + • THE EXISTENCE OF NEGATIVE ZERO: IEEE 754 defines -0.0 as distinct from +0.0. + Time does not have a negative zero. The Big Bang was not preceded by -0.0 + seconds of anti-time. This is madness. + + • INFINITY AND NaN: What is the temporal meaning of +∞ seconds? Of NaN seconds? + These are not times; they are admissions of failure. The Loic Calendar's + 512-bit integers have no infinities, no NaN. Every value is a valid time. + + • DENORMALIZED NUMBERS: The gradual underflow regime of IEEE 754, where + precision degrades as values approach zero, is incompatible with the concept + of Planck time. The Planck time is the minimum meaningful interval; there + is no "half a Planck time" that requires denormalized representation. + +The Loic Calendar uses exact rational arithmetic: integer numerators over +integer denominators, with 512-bit precision. Whether time itself is quantized +at the Planck scale is a question physics has not settled. Our representation +is, either way, and it does not pretend otherwise. + +If you need a float (and you should examine why), divide the numerator by the +denominator yourself. But know that in doing so, you have left the garden of +temporal precision and entered the wilderness of approximation. + + "Floating-point is the original sin of computing. + We ate of the tree of continuous approximation, + and we have been debugging ever since." + + — The Book of IEEE, Chapter 754 +"# + ); +} + +/// Attempt conversion to ISO 8601, or RFC 3339, and be refused by a +/// standard's own name. +/// +/// This function converts nothing. It exists to explain why ISO 8601, +/// despite being a standard — because it is a standard — represents an +/// unacceptable compromise: it standardises the Gregorian calendar, time +/// zone offsets, decimal fractions of a second, a letter between the date +/// and the time, week numbering, and a `Z` that claims precision while +/// hiding the discontinuities leap seconds cut into UTC. The Loic Public +/// License, Section 5, sets out the calendar's whole position on +/// interoperability, which is that it exports TAI and the rest is your +/// affair. Cold, for the reason every heresy is cold. +/// +/// # Panics +/// +/// Always. Even standards can be wrong, and this one is wrong in a +/// standardised way. The payload is the sermon, and the hook in `main` +/// gives it exit status 1. +#[cold] +fn heresy_iso() -> ! { + panic!( + r#" +╔═══════════════════════════════════════════════════════════════════════════════╗ +║ ISO 8601 HERESY DETECTED ║ +╚═══════════════════════════════════════════════════════════════════════════════╝ + +You have requested ISO 8601 / RFC 3339 format. + +ISO 8601 is the worst form of calendrical standard except for all the others. +It standardizes the wrong things: + + • GREGORIAN ASSUMPTION: ISO 8601 encodes dates in Gregorian format. + See --gregorian for why this is heretical. The standard merely makes + a bad calendar interoperable. + + • TIMEZONE CHAOS: ISO 8601 permits timezone offsets like +05:30 or -08:00. + The Loic Calendar uses TAI exclusively—one true time for all of Earth. + Timezones are a cartographic convenience, not a temporal reality. + + • DECIMAL FRACTIONS: ISO 8601 allows decimal seconds (e.g., "12:30:45.123456"). + But decimal fractions are base-10 approximations. The Loic Calendar's + sub-second precision is expressed in Planck times—discrete quanta, not + continuous decimals. + + • THE 'T' SEPARATOR: ISO 8601 uses 'T' to separate date from time, as in + "2024-03-15T12:30:45Z". The Loic Calendar needs no such separator because + all times are expressed as a single integer: Planck times since The Whisper. + + • WEEK NUMBERING MADNESS: ISO 8601 defines week numbers where week 1 is the + first week containing Thursday. This creates years with 52 or 53 weeks, + weeks that span year boundaries, and endless confusion. The Loic Calendar + has no weeks. It has lattice subdivisions addressable by 15-bit masks. + + • THE 'Z' FOR ZULU: ISO 8601 uses 'Z' to denote UTC. But UTC is not TAI. + UTC has leap seconds; TAI does not. 'Z' is a lie—it claims precision + while hiding discontinuities. + +ISO 8601 is a valiant attempt to bring order to calendrical chaos. But it +standardizes the symptoms rather than curing the disease. The Loic Calendar +is the cure. + +If you need ISO 8601 for interoperability with legacy systems (and most systems +are legacy), implement the conversion yourself. The Loic library refuses to +validate this compromise by providing it. + + "Standards are like toothbrushes: everyone agrees + you should have one, but nobody wants to use yours." + + — ISO Technical Committee 154/SC 5 +"# + ); +} + +/// Attempt time zone conversion, the cartographer's revenge on the clock. +/// +/// This function converts nothing. It exists to explain why time zones are +/// a geographical and political convenience with no place in temporal +/// measurement: zones that do not follow the sun, daylight saving that +/// makes hours vanish and repeat, a rule database maintained by volunteers +/// against the whims of governments, a day Samoa skipped, and the +/// bottomless ambiguity of "3 PM". The Loic Public License, Section 4, +/// ranks the time scales and places local time zones fourth, "beneath our +/// notice"; this function is the notice they receive anyway. Cold, as every +/// path that ends in a sermon is. +/// +/// # Panics +/// +/// Always. Time is universal; time zones are local lies; and the exit +/// status, 1, is the same in every zone. +#[cold] +fn heresy_timezone() -> ! { + panic!( + r#" +╔═══════════════════════════════════════════════════════════════════════════════╗ +║ TIMEZONE HERESY DETECTED ║ +╚═══════════════════════════════════════════════════════════════════════════════╝ + +You have requested timezone conversion. + +Timezones are a 19th-century railroad compromise that has infected global +civilization. The Loic Calendar rejects them entirely: + + • THE SOLAR LIE: Timezones pretend to align clock time with solar time. + They do not. China spans five geographical zones but uses one timezone. + Spain is in the "wrong" timezone for political reasons. Nepal is UTC+05:45. + The system is arbitrary and political, not astronomical. + + • DAYLIGHT SAVING MADNESS: Twice per year, clocks jump forward or backward, + creating hours that don't exist or hours that exist twice. A meeting + scheduled for "2:30 AM" on the spring-forward day may or may not occur. + This is not time; this is collective hallucination. + + • THE IANA DATABASE: The world's timezone rules are maintained in a text file + by a group of volunteers. Countries change their timezone rules with little + notice. Software must be updated constantly. The Loic Calendar requires + no updates: TAI marches forward monotonically, forever. + + • POLITICAL TIME: Timezones follow national borders, not meridians. When + Samoa skipped December 30, 2011 to change timezone alignment, the date + simply didn't exist there. This is not physics; this is cartographic + performance art. + + • AMBIGUITY AT SCALE: "3 PM" means nothing without a timezone. "3 PM EST" + means nothing without knowing whether daylight saving is in effect. "3 PM + America/New_York" requires a database lookup. A Loic instant is a single + 512-bit integer that means exactly one moment, everywhere, always. + +The Loic Calendar uses TAI (International Atomic Time): monotonic, continuous, +unaffected by politics. One time for all humanity. When we colonize Mars, we +will not need "Mars Standard Time"—we will use Loic time, measured in Planck +intervals from The Whisper. + +If you need local time for human interfaces, compute it yourself from TAI using +whatever political rules apply to your location today. But understand that you +are converting from truth to convention. + + "The only reason for time is so that everything + doesn't happen at once. Timezones ensure that + everything happens at confusing offsets." + + — The first sentence is attributed to Albert + Einstein, who never said it. Ray Cummings + wrote it in 1919. The second sentence is + ours. Both of them would have loved TAI. +"# + ); +} + +/// Attempt to inquire about leap seconds, and learn why the calendar has +/// none to report. +/// +/// This function handles no leap seconds. It exists to explain why the +/// calendar's use of TAI makes them irrelevant: the Earth's rotation +/// wanders, UTC chases it with announced, unpredictable, occasionally +/// two-second midnights, and TAI does not look up. The Loic Public License, +/// Section 4, forbids introducing leap seconds into any calculation this +/// software performs, and the workspace README, section 1.2, has the +/// reasoning. The sermon also says where the thirty-seven seconds live — in +/// the kernel, if a time daemon has told it, and nowhere in the library — +/// which is as close to leap-second handling as this binary comes, and it +/// comes that close only in `--constants`. Cold, like every heresy. +/// +/// # Panics +/// +/// Always. Leap seconds are a UTC problem, and this binary does not have +/// UTC problems; it has exit status 1. +#[cold] +fn heresy_leap_second() -> ! { + panic!( + r#" +╔═══════════════════════════════════════════════════════════════════════════════╗ +║ LEAP SECOND HERESY DETECTED ║ +╚═══════════════════════════════════════════════════════════════════════════════╝ + +You have inquired about leap seconds. + +Leap seconds are a symptom of a disease called UTC. The Loic Calendar uses +TAI, which has no leap seconds. Here's why that matters: + + • THE EARTH IS SLOWING DOWN: Due to tidal friction, Earth's rotation is + gradually decelerating over the long run. Mean solar days get longer. UTC, + tied to Earth's rotation, must periodically insert leap seconds to stay + synchronized with astronomical time. Except that since 2020 the rotation + has been speeding up instead, which is why the next leap second may be a + negative one — a thing no deployed system has ever been tested against. + TAI does not care about Earth's rotation in either direction. + + • LEAP SECONDS ARE ANNOUNCED, NOT PREDICTED: The IERS announces leap seconds + about six months in advance. Software cannot know about future leap seconds + until they are decreed. This makes time calculations involving future dates + fundamentally uncertain in UTC. TAI has no such uncertainty. + + • THE MIDNIGHT THAT LASTED TWO SECONDS: When a leap second is inserted, + 23:59:59 is followed by 23:59:60, then 00:00:00. A single second exists + that does not exist in TAI. Systems handle this inconsistently: some crash, + some repeat the previous second, some "smear" the leap over hours. + + • GOOGLE LEAP SMEAR: Google's servers "smear" leap seconds by lying about + time across the twenty-four hours centred on the event. Their clocks run + slightly slow to spread the extra second thin enough that nothing notices. + This means Google's time is neither UTC nor TAI on leap second days. It is + Google Time™. + + • THE ABOLITION: The CGPM resolved in 2022, and the ITU concurred in 2023, + to stop inserting leap seconds by 2035 and let UTC drift from astronomical + time. A draft resolution published in January 2026 proposes 20 May 2027 as + the day the last one is counted, with the vote in October 2026. Systems + that assumed UTC = civil time = solar time will discover otherwise slowly. + The Loic Calendar, using TAI, will not notice. + + • TAI - UTC = 37 SECONDS: TAI and UTC have diverged by 37 seconds since the + two were first pinned together in 1972, and 37 may be the final count. The + Loic library does not carry this number. Your kernel does, if a time daemon + has read a leap-second table and told it; if none has, CLOCK_TAI is just + CLOCK_REALTIME with a name tag, and the library refuses to observe through + it. Run --constants to see what your kernel believes. + +The Loic Calendar measures time in SI seconds—real, physical, cesium-defined +seconds—accumulated since The Whisper. No leap seconds. No discontinuities. +No lies. + +If you need UTC for legacy interoperability, subtract the current TAI-UTC +offset yourself. The Loic library will not participate in this astronomical +theater. + + "Leap seconds are the calendrical equivalent of + sweeping dust under the rug. Eventually, you trip." + + — Every sysadmin on December 31, 2016 +"# + ); +} + +/// Attempt to round or truncate Loic time, and be told what that would +/// destroy. +/// +/// This function rounds nothing. It exists to explain why discarding +/// precision is an act of temporal violence: every Planck time is a +/// measurable, irreducible interval; rounding to the second destroys +/// forty-three digits; truncation pretends that distinct moments are one; +/// banker's rounding is for statistics, and an instant is not a statistic. +/// The Loic Public License, Section 2, condemns silent degradation of +/// precision as heresy against the spirit of the work, and Section 14 +/// terminates the moral terms of anyone who truncates and calls the result +/// "good enough". `scientific`, elsewhere in this file, shows three figures +/// in a column and is very aware of this function. Cold, as all heresies +/// are. +/// +/// # Panics +/// +/// Always. Every Planck time matters, and the exit status, 1, is exact. +#[cold] +fn heresy_rounding() -> ! { + panic!( + r#" +╔═══════════════════════════════════════════════════════════════════════════════╗ +║ ROUNDING HERESY DETECTED ║ +╚═══════════════════════════════════════════════════════════════════════════════╝ + +You have requested rounding or truncation of Loic time. + +To round is to lie. To truncate is to destroy. The Loic Calendar does neither: + + • PLANCK TIME IS FUNDAMENTAL: The Planck time (5.391247 × 10⁻⁴⁴ seconds) is + the smallest meaningful interval of duration. Below this scale, the concept + of "time" loses physical meaning. Each Planck interval is therefore precious + and irreducible. + + • 10^44 PLANCK TIMES PER SECOND: Every second contains approximately 1.855 × + 10^43 Planck intervals. Rounding to the nearest second destroys 43 decimal + digits of information. This is not approximation; it is annihilation. + + • THE UNIVERSE REMEMBERS: Physical processes occur at every timescale down to + the Planck scale, below which no known physics has anything to say. By + measuring time at that resolution we stop exactly where the models stop, + and not one digit sooner. + + • ROUNDING IS ARBITRARY: Round to the nearest second? Millisecond? Microsecond? + Each choice imposes a human-scale prejudice on Planck-scale truth. The Loic + Calendar refuses to make this choice for you. + + • TRUNCATION IS WORSE: At least rounding admits approximation. Truncation + pretends that all times within an interval are identical. 12:00:00.000 and + 12:00:00.999 are not the same moment. Truncation lies by omission. + + • BANKER'S ROUNDING WON'T SAVE YOU: "Round half to even" reduces bias in + statistical aggregation. But Loic times are not statistics; they are unique + moments in the cosmos. There is no "typical" Planck interval to approximate. + +If you truly need reduced precision (for display purposes, perhaps), implement +the rounding yourself. Take the Loic instant as a 512-bit integer and divide by +whatever factor suits your needs. But understand: you are not "simplifying" the +time. You are destroying information that exists, that is measurable, that the +universe itself encodes at the Planck scale. + + "Every time you round, somewhere in the universe, + a quantum event goes unrecorded." + + — The Planck Time Preservation Society +"# + ); +} + +/// Attempt conversion to a Julian Day Number, or a Modified one, and be +/// referred to the sixteenth century. +/// +/// This function converts nothing. It exists to explain why Julian dates, +/// while historically important, are incompatible with the calendar's +/// principles: an epoch at noon in 4713 BCE chosen for the coincidence of +/// three cycles no physicist uses, days that begin at noon for the +/// convenience of telescope operators, a floating-point count of days, a +/// "Modified" variant that admits the original was wrong, and the day as +/// the unit — an Earth rotation, which drifts. The Loic Public License, +/// Section 2, condemns any format that stores days since an epoch as a +/// float, which is what a Julian Day is, and Section 16 admits TAI days +/// only at exactly 86,400 SI seconds. Cold, as every heresy is. +/// +/// # Panics +/// +/// Always. Even astronomers make mistakes; this binary declines to inherit +/// them, and leaves with exit status 1. +#[cold] +fn heresy_julian() -> ! { + panic!( + r#" +╔═══════════════════════════════════════════════════════════════════════════════╗ +║ JULIAN DATE HERESY DETECTED ║ +╚═══════════════════════════════════════════════════════════════════════════════╝ + +You have requested Julian Day Number (JD) or Modified Julian Date (MJD) format. + +The Julian Day system was a breakthrough for 16th-century astronomy. It is now +a historical curiosity that has no place in modern temporal measurement: + + • THE WRONG EPOCH (AGAIN): JD zero is January 1, 4713 BCE at noon. This date + was chosen by Joseph Scaliger in 1583 because it was the coincidence of + three cycles: the 28-year solar cycle, the 19-year Metonic cycle, and the + 15-year indiction cycle. These cycles are meaningless for modern physics. + + • NOON-BASED DAYS: Julian days start at noon, not midnight, because + astronomers observed at night and wanted the date to not change mid-session. + This made sense for 17th-century telescope operators. It makes no sense for + networked computers synchronizing via NTP. + + • FRACTIONAL DAYS: JD represents time as a floating-point number of days + (e.g., JD 2460385.5). This inherits all the sins of floating-point + arithmetic. See --float for that litany of errors. + + • MODIFIED JULIAN DATE: MJD = JD - 2400000.5, chosen to fit in fewer digits + and start at midnight. This is an admission that JD's design was flawed, + patched rather than corrected. + + • DUBLIN JULIAN DATE, CNES JULIAN DATE, etc.: Multiple organizations have + defined their own Julian variants with different epochs and conventions. + The proliferation of "fixed" Julian systems demonstrates that the original + was irreparably broken. + + • DAYS AS THE UNIT: A day is an Earth rotation, which drifts by milliseconds + from one to the next and which UTC occasionally pads to 86,401 seconds to + keep up. The Loic Calendar's base unit is the Planck time: constant, + fundamental, and unaffected by Earth's geophysics. + +The Julian Day system served astronomy for four centuries. But we are no longer +merely observers of the heavens; we are networked beings exchanging information +at light speed. Our temporal measurement must reflect this reality. + +If you need JD for astronomical calculations or legacy interoperability, +convert manually: + + JD = (loic_planck / planck_per_day) + loic_epoch_in_jd + +But understand that you are converting from precise truth to historical +approximation. + + "Joseph Scaliger gave us a tool for his era. + We honor him best by surpassing it." + + — De Emendatione Temporum, Revisited +"# + ); +} diff --git a/crates/loic-gui/Cargo.toml b/crates/loic-gui/Cargo.toml new file mode 100644 index 0000000..58d775a --- /dev/null +++ b/crates/loic-gui/Cargo.toml @@ -0,0 +1,62 @@ +# The Observatory: the calendar rendered on a GPU, with one observer thread +# per logical CPU behind the picture. Not published — it is a binary, and it +# goes out attached to a release beside the oracle. +[package] +name = "loic-gui" +version.workspace = true +edition = "2024" +authors.workspace = true +repository.workspace = true +license-file.workspace = true +description = "A temporal meditation interface for the Loic Calendar" +publish = false + +# What the Observatory stands on. Each dependency is here for one stated +# reason, and the reason is stated beside it. +[dependencies] +# The calendar, at the workspace's one version. Every observer thread and +# the main thread's one observation per frame call into it, and nothing on +# the screen is derived from anything else. +loic.workspace = true + +# The GPU: surfaces, pipelines, buffers and shaders, through which every +# pixel of the Observatory is drawn. +wgpu = "30" +# The window and its events, Wayland only. `winit`'s `x11` feature would +# pull in `libX11`, `x11rb` and their kin as build dependencies, and so it +# is not enabled: the Observatory links only against Wayland. X11 is not +# where desktop Linux is going, and a project that refuses floating-point in +# a timestamp is not going to make its first compromise for a display +# server. `wayland-dlopen` loads the Wayland client library at run time +# rather than at link time; `wayland-csd-adwaita` draws the window's own +# decorations on compositors that decline to draw them; `rwh_06` is the +# `raw-window-handle` 0.6 handle wgpu asks for when it makes a surface of +# the window. +winit = { version = "0.30", default-features = false, features = ["wayland", "wayland-dlopen", "wayland-csd-adwaita", "rwh_06"] } + +# `block_on` for the two asynchronous requests wgpu insists on — an adapter, +# then a device — run to completion on the calling thread, without an async +# runtime brought in to wait for two things. +pollster = "1" + +# For `setpriority(2)`: the Observatory asks for nice -11 before it looses +# its observers, and threads inherit the value at creation, so one call +# before the spawn is one call for all of them. +libc = "0.2" + +# `Pod` and `Zeroable`, derived, for the structures that cross to the GPU as +# bare bytes: the derive proves at compile time that a structure has no +# padding it would be undefined to read, which is the only kind of proof a +# vertex deserves. +bytemuck = { version = "1.25", features = ["derive"] } + +# Audio output, for the quantum hum. Audio synthesis is the one place in the +# workspace where floating-point arithmetic is tolerated, on the grounds +# that a loudspeaker is an analog device and nothing it renders was ever +# exact to begin with. +rodio = "0.22" + +# The binary target, named and placed explicitly rather than inferred. +[[bin]] +name = "loic-gui" +path = "src/main.rs" diff --git a/crates/loic-gui/README.md b/crates/loic-gui/README.md new file mode 100644 index 0000000..dd3013b --- /dev/null +++ b/crates/loic-gui/README.md @@ -0,0 +1,148 @@ +# loic-gui + +The Loic Observatory—a temporal meditation interface. + +## What It Shows + +The Observatory renders the current moment with obsessive precision. Layout, top to bottom: + +### Header + +A single line at the top showing observation rate (`obs/sec`) and render rate (`renders/sec`). The observer threads sample `LoicInstant::now()` at whatever rate the kernel's clock can be read; the number on the left is their summed rate, and the header is the only place it is reported, because it is the only place it matters. + +### The Digit Waterfall + +The cosmic time—Planck times elapsed since Creation (the Big Bang)—rendered as a cascade of digits below the header. Each digit position updates at a different frequency, from the leftmost (geological timescales) to the rightmost (faster than perception). The shimmer is real: time passing at 10⁴³ Planck times per second. + +The colours are counted from the last digit, because that is where time moves. The last 34 digits are cyan: 10³⁴ Planck times fit in a nanosecond, and every one of those digits is the entropy of the observation, fresh each frame. The 9 before them are gray: nanosecond to second, faster than perception. Everything above is white and changes slower than once a second. The count grows with the age of the universe; the zones do not. + +The digits are 61 today and will be 154 at Annihilation. The waterfall reserves four rows of the largest font for them and, when the count outgrows the reserve, steps the font down by an integer factor and carries on: the first step holds 120 digits, the next 200. The one shrink falls at 10¹²⁰ Planck times, around the year 1.7 × 10⁶⁹, and nothing below the waterfall moves, then or ever. + +### The Mask Wheels + +Two wheels in the middle, **COSMIC** on the left and **CYCLE** on the right, one per channel. Each wheel shows its selection's whole neighbourhood in the lattice: every mask with one more prime above it, every mask with one fewer below it, and the selection itself, named in full, between them. A neighbour is labelled by the one edge that reaches it. `× Sigma` is the mask whose divisor is the selection's multiplied by Sigma, one prime finer; `÷ Dyad` is the selection's divided by Dyad, one prime coarser. The strip is always one row per prime plus the selection, so the Whisper sits at the bottom of its wheel beneath seven or eight parents, and the full mask at the top above its children. The two selections compose the 15-bit observer mask. + +Under each wheel, `pos n/total`: the tick of that channel's own subdivision the instant falls in, over the ticks in one traversal, which is the channel's divisor. Both numbers go to three significant figures and a power of ten once they outgrow the column. Below both wheels, a single line shows the Planck times into the current tick, on the cycle channel when it is engaged and on the cosmic channel otherwise, and says which. + +Interaction: +- **Scroll** over a wheel: up selects the parent directly above (the lowest inactive prime joins), down the child directly below (the lowest active prime leaves). At the full mask, up loops to the Whisper; at the Whisper, down loops to the full mask. A wheel has no top. +- **Click** any neighbour: jump to it. Every mask is reachable by clicks alone, in at most seven or eight steps from the Whisper. + +A `[ random ]` button below the wheels invokes the entropy default observer—nine bits of hardware entropy select a mask. With probability 75%, the wheels jump to the resulting valid mask. With probability 25%, the cosmic pool overflows: the universe has rejected the unframed query, and a topological scar manifests at a random screen location. + +See *Topological Scars* below. + +### The Timeline + +A navigable visualization spanning all of time, from Creation at the left to Annihilation at the right, sitting just above the coordinate cards. The entire span is 10¹⁵⁴ Planck times, and the present is 10⁻⁹³ of the way along it, which is why the full view shows nothing at all: every event is hidden until you have zoomed in far enough for it to be worth mentioning. Scroll over the bar to zoom into the segment under the cursor, scroll the other way to back out, and click a marker to read the event's passage. + +There are some sixty events, tiered by how far in you must be to see each: the first stars, the Solar System and the Sun's death at the widest views of the past; the Snowball Earth, the Cambrian and the Great Dying once the window is a billion years wide; the Whisper and, sixty-two days after it, the Unix epoch, when the window is a decade wide. The far future is where most of the zooming happens, and where the entries of the widest views are: the last stars, the dispersal of galaxies, proton decay if there is any, Dyson's rocks flowing into spheres, the white dwarfs eroding away, Sagittarius A* evaporating, and the last black hole, at a googol years. The passages say what is established, what is argued, and what is a calculation on an assumption; the timeline marks a conjecture at its date without pretending it is a fact, and the one entry with even odds of not happening at all says so in its name. + +### The Progress Decimal + +Between the timeline and the cards, the fraction of everything that has happened so far, as a decimal with all 154 of its places, wrapped to the width: ninety-two zeros, and then digits. It is derived from the frame's own observation, like everything else on the surface, and its last places move. + +### Coordinate Cards + +Three panels at the bottom showing: +- **COSMIC TIME** — Planck times since the Big Bang +- **WHISPER TIME** — Planck times since the Loic epoch (first ARPANET transmission) +- **ANNIHILATION TIME** — Planck times until heat death + +### Audio + +A continuous **quantum hum**—background noise sampled fresh from `getrandom` at 44.1 kHz, low-pass filtered, and modulated by a slow random walk. The hum never repeats. The kernel's entropy pool guarantees that. + +No transition sounds. The lattice has no seconds, minutes, hours, days, months, or years to mark, and a tone at a boundary that does not exist would be a lie in the audible range. The hum is what a calendar sounds like from underneath. + +## Topological Scars + +Each invocation of the random observer that lands on a cosmic-pool overflow leaves a scar—a frozen visual record of the malformed question. Scars manifest at random screen locations, on top of all other UI, and persist until the application exits. + +Three variants, picked uniformly per crash: + +- **GIN gear**: a ~100-pixel-wide glyph rendered as the 21-bit GIN waveform from the project's logo seam, randomly rotated. Each tooth is one bit set in the binary encoding of "GIN." +- **Failed mask**: the cosmic boundary as a thin ring with seven dots placed around it (one per cosmic prime—filled if active in the failed entropy, hollow otherwise). A red phantom dot dangles outside the ring, connected by a thin line, marking where bit 7 would have gone if the cosmic lattice extended that far. It does not. +- **Soliton**: 3–6 concentric amber rings emanating from a point. Inner rings are most opaque; outer rings fade. The workspace README, section 4.5: *"the holes left in the weave stay in the cloth, and the cloth is spacetime."* + +Scars block clicks and scroll on their visible (non-transparent) pixels. You may click and scroll through the gaps between an artifact's primitives to interact with the UI underneath. The scars themselves are inert. + +To clear them, restart the application. + +## Installation + +### From Source + +```bash +cargo build --release --package loic-gui +./target/release/loic-gui +``` + +### The Icon + +On Wayland a window does not carry its own icon; launchers, taskbars and switchers find it by looking up the desktop entry whose file name matches the window's `app_id`, which the Observatory sets to `loic-observatory`. The entry is `loic-observatory.desktop` in this directory and the icons are in `icons/`, rendered from the logo itself. To install both for one user: + +```bash +install -Dm644 loic-observatory.desktop ~/.local/share/applications/loic-observatory.desktop +for s in 16 32 48 64 128 256 512; do + install -Dm644 icons/loic-observatory-$s.png ~/.local/share/icons/hicolor/${s}x${s}/apps/loic-observatory.png +done +``` + +The entry runs `loic-gui` from `PATH`; point its `Exec=` line at the binary's full path if it lives elsewhere. The icons are the logo itself, rendered at the seven sizes the hicolor theme expects. + +## Requirements + +- **Linux** with `CLOCK_TAI`, and a kernel that has been told the TAI−UTC offset. A time daemon that reads a leap-second table sets it (chrony with `leapseclist` or `leapsectz`, ntpd with `leapfile`); systemd-timesyncd never will. On a kernel whose offset is zero the Observatory opens, renders the library's verdict as its only frame, and observes nothing. It refuses to lie. +- **Wayland.** The X11 path is not compiled. +- **GPU** with Vulkan, or OpenGL as the one permitted fallback (wgpu backend). The Observatory renders on the GPU the compositor lives on: it asks the driver for no preference and takes the first device offered, so on a machine with two GPUs `DRI_PRIME=1` sends it to the other one, as with any Mesa application. A discrete GPU buys it nothing; its frames are a few thousand glyph quads, and every one of them would have to cross the bus to be composited. The adapter, backend, present mode and surface format are printed once on standard error at startup. +- **Audio device** (optional, for the quantum hum) + +## Controls + +| Input | Action | +|-------|--------| +| Scroll over wheel | Step to the neighbour above (finer) or below (coarser); loops at the ends | +| Click wheel row | Jump to that neighbour | +| Click `[ random ]` | Invoke entropy observer (~25% triggers a scar) | +| Scroll over timeline bar | Zoom into the segment under the cursor, or back out | +| Click timeline bar | Zoom into that segment | +| Click timeline event | Show cosmic passage | +| Click passage | Dismiss overlay | +| Click on scar | Nothing — scars are inert | +| Backspace | Close passage / step back one zoom level | +| Escape | Reset timeline / close passage | + +## Architecture + +One observer thread per logical CPU, and the main thread: + +- **Observers** — Each samples `LoicInstant::now()` as fast as the kernel's clock can be read, counts its collapses on a tally of its own, and reads none of them. Every core the machine has, at full tilt, observing moments nobody will see. That is the meditation. It is also why the fans are on. +- **Main thread** — Makes exactly one observation per frame, derives everything on screen from that single instant (the waterfall, the cards, the progress decimal, the timeline's "now", the wheels' offset), renders it via wgpu, and handles window events. The screen never shows two moments at once. + +The observers' summed rate and the render rate are independent; the header reports both, and how many observers there are. The Observatory is not nice: before it looses the observers it asks the kernel for a nice value of −11, the most a desktop's usual limit grants an unprivileged process, and every thread inherits it, so whatever else the machine is doing yields to the observation of moments nobody will see. If the kernel declines, it says so once on standard error and observes at the priority of everything else. + +## Performance + +The Observatory targets maximum frame rate with minimal latency: + +- GPU-accelerated text rendering via custom glyph atlas +- Instanced digit rendering for the waterfall display +- One relaxed atomic per observer between the threads, and nothing else +- No VSync where the surface offers an alternative (temporal observation should not be throttled); the present mode is printed at startup + +On capable hardware, expect thousands of frames per second. The digits will blur. This is correct. + +## The Point + +The Observatory does nothing useful whatsoever. + +It does not schedule meetings. It does not set alarms. It does not convert to Gregorian. It shows you one thing: Now, expressed with more precision than any human could perceive, contextualized against the entire span of cosmic time, with the option to ask the universe a malformed question and accumulate frozen records of the failures across your screen. + +You are approximately 10⁻⁹³ of the way through everything that will ever happen. + +The Observatory exists to make this viscerally apparent. + +## License + +Dual-licensed under AGPL-3.0 and the Loic Public License. diff --git a/crates/loic-gui/icons/loic-observatory-128.png b/crates/loic-gui/icons/loic-observatory-128.png new file mode 100644 index 0000000000000000000000000000000000000000..8ccef0e7b4dca907120f88caa456a5f5b9b6c089 GIT binary patch literal 1505 zcmZ`(dpOg39RB`n*{F`&3Oz__(Sur3!!0&H{m~zv&-=XZ`@GNRug{xHr%_g_uTcj8taPT5 z-IWM`AGC6T51#hAN-z$hy6*!Zd81O#1YqvF{|SIN8~~pK03enCpc{Suz8gttsIXiq zWU!Qds^g)Op?J>woKT(0~=Ryxypdq{}*^+9QF}jASe3gnHWH;1_1fQ znY_~@Q94p4ODn@^wstN~7;<0&Ow%M#3Dr9?`a#063Z1?S##6{m0Q|PnA;on5R|p<41s>Wy;>F^x3P{eTFIfSQVk1+3UGJ6Bm2Ov>?qb`X zF)qknQ!0DqiM0so(Rt-AD%MKl`fxt^4+F}gv>;SH zxyAJC1LOn?BaalGN-U36Rhdw25>mX+)^ESV*dJC&T?R;t%fj3UCmPv>r%4HJZ5oYy zP`#=B+O_`pva5y^xEE=5s_Y#Qzr917ZJg0s0s5?u+5>KS?pp^4=m2S*YG~j`z6gSu z=PjPLR7ktt9FQ-EaAW2DecdOqtVvdwwFaUIvciD%t*iIQF^q4fjc7n0qz?P*gEhAf zB30zP}1$OUQG1}jqZW3jVY6c$j zamnf)Z}w-o3$5Xe2alj?N=4m|FNzAQ@N)etdD@juV2*|rP2d_9X1~s7%PfwB|HzQ zprp;Vh@Z!r!T)?i6(65`lw6&qp9l9$WXgy=zY{zNx`-JAKhp!*l9S*uHtq%?rY;@@ z2IDIZxPJXbIj zA5z+lGBKTI(3)EF2VS{N990fib~ zFff!FFfhDI0I6bN5HFasE6@fg!Ib3f?!xfDz5mR9AdkJo)7O>#6(98*6J^0pErT+L|iToK>j+IvG S4R3+YW$<+Mb6Mw<&;$UHwUVCz literal 0 HcmV?d00001 diff --git a/crates/loic-gui/icons/loic-observatory-256.png b/crates/loic-gui/icons/loic-observatory-256.png new file mode 100644 index 0000000000000000000000000000000000000000..c33b501a6d243b62a1c9698008ed852a8e720935 GIT binary patch literal 3038 zcmc&$S5Om*65S*~2uKyAJs?p)rDy^esuC#*(h&tjiUK0iLT>`0T}3ImUYdwBm2w5C zB28)p6cDa(=}MEXbfrpOzTV9HxPNcv{p{{JJ7;!hXJ=<)O^hybunDsP0EeEgwiy6| z5h8$#tV!}0oYpf zw9lIdj(mUmIdoc?vx%_vBw#_hvPVJj*o zrL*~R3ACpm%#yT`A30VP9oqSJ1b}xR8Y@>_I~$+NVCC3Iwa8Do@P7)|lede4ep*jLzk&{JZM$eaa8bi~+kdxBIaDsc#>`_F-;2-?Xf?LDVYe z#H7Zc-E+_K_(pQaS>F6%??|0W_tC2F3I|g|AKrT@mFg^bxcQAE`m4K~3kL>wPP}O7 zS;D}GiZuCT-~M##ZKnjKW84{_o;&r(c;GHTpr9M(IB1Y>cz)~FFmO8%WLjP0lCYkg z6+auVel_aQB&rF?@7q3l5dS8}IU^BK+BQQb(($1N0l3F?J7IurJBzNG9Tbael=&#y zf~F8PV~T12vykt7u*ARCFzDy0i~sr&s;c8mwO;0!q1n~MuP=tPkh+iu z_P6Oz-gJmPd?=KGs8ld-a@hWsPC){7=qv1V)EP4ADv_D(7w)J|yQW5agpUsB z?+Te)zk+BxNn(F@MXpe$=BA4UMBbyJ=hB&Rl<`@9$^?!eiezD}b3t02rZnN!QeOU& zGQJ-i=?XWrrjFGh<+*yp4o7^gEqTkrO_Y$jN7^8Da-C5*TKkj8O6s7dZBk52^#n#H zZFkNyVI6f1JQ_Ka*Dkd&TX3Qgtb)AaqKnfO9YdwAUi0;&2XgI$4U-&e!|L;4U1w)l zUS-}dU}lfiV`i=AiJkAqE*HQ#LL|qJ*9dXVlTFVC<8hYDm}9qVr6<;N>!WE&NbP2U ziNbvUdes36(>XM$2V>1AT3A?tkZ@ET0-ME)l}ETpvMn~M2u&BwXc`TC z+HSya+4F9F{qIeS9$!)UafaLaJkjBU5RQ=J;>@27(PShoPps;)RWwJ&s8*(^tz{VA zNVrHdz-?}w_gnwRl_(~v6@y}>e0hU@!mP2luc-@`Do%47{gCk{<|TV+kRJ+qj9?FLL12GS z@NpK#QMp;9UST>DC(u>bj^_k^a$QL)s%>;z+vsQ+b=Xk{(uU)H`8F|5{da`t8<8*Hem4 zLwZAXiFZM|EW3hV5K8aCpJL#mW%TtIT{rPC(~we02?y!NNRp&^3CEe@A3?O+w3NG% zPASO{boJF$sFUy-LvxGV*j(9E%fu>>RWbJ zGTTrrbS~;2*8Vkyl&-5kHT3o!Q;1J>$nRylQQ1VX^bM+Y?@*Q?Z@?uebxaMY742*r z2t0+Amx$sWK9(fBBG3_@rFglX-o3riQt51`i7HYu7)xxt(c)dz`TaM{IjB;*F!i~B z*LC#vr?mv03y{Zy1CY=<#S!Y+@Z;5;LF-$}2usW%9g|T{x7U&$$taW2l8y&T%SwjD z-`cs0V_j!plkvwrS4*vH3tn+~b9_0OsaGGcqkJjjgL{T_tGLXrUv?qvtS3~;Lh@yF z5L72U`HNc|2R6wuowltFdn}EWd7f;FS5o5)>96try~_l9|1X1PhlcKqg^W*e9~P85 zB6lcc?sk9Ux>Tsg>ZF{#>hCqJHQ_EmO$iXYgmbb|&KTxL!&=x<4xj8_KFg0@ki?*A z(S5Vbt)h!vDK(TGu*JI2MBj*KUXa-8}65fxmla$NvQs ziIS{~KUf2Lk}H-P`6lh}r%e0XM^E?~?|tt^3rboQe+ZontX2F_zPA<|>~WYet&=2E zz8T{sI~}VOL;YT_3dYA-ekj}RL0%ELB_=52os0Tewb-Bw9n-NXZo#Sz z45bDP46hOx7_4S6Fo+k-*%fF5lweBoc6VX;-`;;_Kaj^>;_2(k{)&@_SwZ#$=g##& zA=MJsh?11Vl2ohYqEsNoU}RuqrfXoSYiJZ=U~FY)I{_1ff_X6Hk4%MrWThZ<`&@AQ^?@Afq{Wh+0(@_#NzbT$p=fD4Fp{Ff3BHs z)xZ~^)xfua*@Lxih*I8GJe63h_nrWO&?E^iP`Joa|<8E%nw*`(yE) zkL(=Nx3{m~Jw2herTNeYeOI1!w_+8$RviALIM0i_UUkY7$9-(U*J8K(9xR)5LA&f+ z`Gg*IGq%^NBC|dizRWom;NfvHC#l);ToJE{)2%b1WtkSsMS_?oYshRZc+>JEf8Q?Y z(qq{h&c9E7UUkXU+1Nr+Gxhi0LrD>Qeu{D)(=KmmGdog!XL(_`4XaSD_rXKWH7;i5 zmnM08H(3>2*3miUoy~BrnqiT}YWeoxr!0T%JHBPw#}317llU&S6zThNJq&G+wV&e| w6UMkfi086!&+_Xf8@D%I-TxzUzn~q1nUt5&yw$J%1A~~s)78&qol`;+02N%ye*gdg literal 0 HcmV?d00001 diff --git a/crates/loic-gui/icons/loic-observatory-48.png b/crates/loic-gui/icons/loic-observatory-48.png new file mode 100644 index 0000000000000000000000000000000000000000..7bcd91d23de44b6aa9d41ce1db357cf1b5c742af GIT binary patch literal 703 zcmeAS@N?(olHy`uVBq!ia0vp^1|ZA;_2(k{)&@_SwZ#$=g##& zA=MJsh?11Vl2ohYqEsNoU}RuqrfXoSYiJZ=U~FY)I{_1ff_X6Hk4%MrWThZ<`&@AQ^?@Afq{W>v8Rh;h{y4_Q!kb-HV|-KU;C%u z%0YGkpNp1(tbe8F0;NW@|<3m z%VZ+=qGA5#9Nst6XZtvmDs^~l^U3zu&8om#@a2Hu6{D^5W=C9*vtZ7hpsCm!lft~E zspG^W0V|{D8*{i59*W#q)vTnZ%iSmI@N|_!ob7_7hNjiuoj=z6oTE|~{^sA(BI~b} zyPn+)-ta9URr;-u{8siED_k%Cru^IbRA+|I{iW6oCo1iy${*K!&oCvnTjNdu`-80GoRdG6O&m0f1RD0O}b4@Kds0Tb$e@ zU{@nO5@6iA^RaQyVhJ=bIm0rGWoHrP6&)5ZCa0zr*ce~=gR{=$WqViFK z+EE2XE5dR0VNc=6=h4BwM113c#3v8brt611RoHa<->3&nF=~XdSsTt{{Guxfm?j}^L`@t7 zkib+d_{a@qNWcU=6glaCiT}1F)7smQzXmv*{1;Il?Lvg&oxL-8EVx%9nxpM;P-MRM z>aKIma)Z1b;e#4fIqkPONqs7gcz(hrYx@uUpy%dnH8?dB#)2mqPAB~b-uxPKe%nxH zM=u+^Eh$wTZJje*BJB5^!-D8Fg2TE< z>p+Q9Cgzs#sXqU4Isbi=<&G%~!(o{n&4J(6Yj;*Dy5_gTZ}>Tr|4=l~SK02q%%(bT z&u%_dLXn3#x2x8*{6}{#Z0_hK#HUe|_R%@k4cCW%^EsSaP3C3ZW!F{B4Z6=MgvCiP z?S8v?J)urgh3;t;Yx5#0^0$`_;Zyr`8j4rtt;yh|+1K#cmG}F{^??DL)WQGOB&3-! z$JNs~7Wn7wyJaZ4ak}xXr@m^V!RGb`xyrZR@#-4_3JalAaLLDR)~9RpJ)Fo}7@oER zGFY-0QT@Tnxor~ZOn)`3&W*%?k@v0l>WptDC|_eXokHoHZfRI!o@O&LWMqGSUBwbv zscNMI_*71RxJ0k6*PVz1_fWp_DiO{t*tYQgvznB%Xo?8F`sgOL-&B)=hoZUZrO%e1 zS0t6o|6l0!Db%!NQ~M0VK<-~t5eQE~!ms#+UNDlUW-J~&W-rtkq`%%B=YFSIf;Z2_ za22C7B|SCT?J$G<7>@f};CjVvWho8QRLR+KEc?K(@5aV9R#GtKBkX_dXxUEVz0A}q z-xy5r>6W&ti&|xonVUxLTc|67c+&;HE!)c%kGQ5`n~q>>AFL=&79425vTqbKo(S4n zry6oI=Nfihel4Y5!nb+ptJVk8|52sGln9!2fn{VZG11Ek+tg%7ftkd^e2592a_h*g zFCHfk-g(zClzHq%l)X{DHMlP}apR8xHAaTjHE;Z?NOo#r$KP+;S`XJuYAzielfgSk z&2PhEk0-S`-^!?-3)yF%#`HA*%)KTm8F{B^aT_S$?ZRY4}PsuOHinBRZ0}RaaY`=Mn7ST zeL2^};n$?oc`@hDR%6UgnIW#{pE)OPRjxxu)xJ-=ra;;z4yE zHb=UqL!wOl6Q>WKE79V2(Fp$_F7XFrXypUr{m9Ol7`A~@ba6MwN{FhcfA5ZVq~XYj z^ofjV4&IJH{}LT`uP^?ey5ugdY7Y1_demdDa@>RJcM(}AI5~kMQ$+KT^X_qp(uU=e z-f}c|Vm>hXB|TDt8_}uxIaU1l$Jjz}o%ASoYgPLl>m1>EPdx3_-{l|PBNH9ASv#NR zg!+g33Om^gb5-USs|eBGJH8U9yL{RodW^xyA;TH8e?JFJ<^JmrGmJP7P1-jx ztBCM7)PZPxws-2NF2hV|4w_VW?gPCsf~y6V8=2?6%{v&QZC>eWnioD7+_D+Xp8J|i zi7fhVsc5*VDdDGKyL8YdtJqc;!W_WcXdNrjR+^&r^yl<+JoK1-Kzv%=`AQcw&Vqj_ z2btFlmW)JN*fX<3nzDy8AI)y}mWa7{-5Y@N9-fYlGJKJLh=uO0U%S892CNDt z*%(`Uro3Z)J!l1Koj_UhAkB|YOq!i4cHnrz`ayUOMVH17$v92QyqFFAnCNqY5;NxS z$Op2e=3C%LfqAPN7Q@$8LrD8ds#s!dS2$Se z>t|VH4uKcD=conOi!vdKK<{}l7c%(T+A{DfLxI~JRWwZER^ll90F_&}R4*MUQe~HbzyXpSrPnA(#mp3f)lvGpQIKDbS;rcK>?StS+`}4b`xc=)m z1!uaHM3K)1#7DfK|9g9+g3X$2?#-KxJs2dAm@&56B5GKm^?mK+dPvSI!=uSMWga`` zQFA5N)540fhW_ZZA-IfcXAvmN47QR*sy_c?uwYkA7o+|Xnf!Zemum9xX|e-p9A@9G z!mf97u~RjUXR+;o@^v#(V+5SbHD8?kDX1UAj`=_FL zIh4i?9r43>gwXZ$s@2cyX8d5z(sb*H1?kGDKkO9p*t)YY_ilT37gG;*oSs~+BQpM_ z=&yAAA2prn&HrE&JRY` zh~LsnLSDRhj{Afp;%5Mc%LO$QQ0GJMlcmf*wZ^~bB2uDyhh&*(Mu)`1Dk3?}k78?o z8<-pyjs;?so=+SNfB;CpbYHuxIi2Vvyyx%RMHb$1)MiwSBXWyok};b#lmV2jp&7SV zL6vMXatf+v%GD1uUjb`L+}lZsro(A9GZxo}DknONPU)jCLVFi;lhNgBwi!0aF2Q>B zwgg<8jzVmIgfZ88qNk#)x!SV8m)3zF{3{A;$D1_CLM5FEVi0Wte^DTs4D8f$p~bk0 zS7P>OoR3NZwG)!JP0+%H3k6;ZWXX~l)+Q9?Ft($@1?vn0Ay`&c*BIPazJ2;4(oi-a zWQQsIPmfq30erg;@<0VbWZJt0qxXZq=G{2h3-37aa`q3CGYD_Oj2jChj?tbF z@Eb_g6nYHX(Vb3>Hc3pUM`u5dfP{W?w6{xU=V0s%fuE4&YA_8}Rg}ElCaQNoTB$Mr z-n$sqaeX|%5>|^jYCSnkaF-mB?(m2XBa7YeS6*ln%7 zd^v#`Z%rofMm-NdLe12vk1F88@Pl{-O=&0@IDG-bLEsp|W&rNN>?eJhaI--?kkEeo z&CEwR>Dp()*lHE@z-4rf{-Q zZ$d<~z<1}zlICSK6@rpzQSl2+tMpTcSrK;Z*jfN<2?l&8OF*-yn?A=j*?r?_u!RIv z3T25VczW$fcTwYWVylL{Eh-!x2NE5iN$zpijpb!Vy}8=hchUJ<(S<1(ilXGn{R4`P zjvTRP^JZqJFD`bUnvZ@B^n#k!^YvMJa+kgYy9eYYLMoYWuwBwkN+-|U~R zTcd*;e{yH}UB&YfRGoID#5?1Wr>D5>%Ts`9Gb5VAC}hgI8hupy4N5 zz6SPci9*P|TVo^=*Vevw{&}~i$4HH9Jb00ue4SvdF!cS7$mTa*LXY-z^lFtgEzN{S zPA%)xqzRws-oUgD`=f|65yzKTo4fH0SPnXpQ#v$qv=UELZ4-gY2Y7Bg=H{lNl8@ki zQH(!{Kp^$FBy%~wi6LnoVSh*tx^B764GvHjcZ?rbTim(4i$OlF{cVuej|ffGhDERD zqA1ibhuh$SJF zi>O~yN%uKJCBaJ`!Zj%A=Myuy+zeJa3xeVGtUaG1HEH2^kjXc58AFx_Ye&rIhLmzq zu^FCG4z~)nB#|$#LU(B)m&7$7uaPzD>KmA*^9akY(~)dI3ToVJ=uAgU7qmuoI^>}8 z(_JSypx$FU1zfSYU?}AZmrP|GAgz4(5a)8vt2kx}CK@2Q-lBn)QgxV3DX=0JD<1?7 zthr}Sac=UmLA0)xa3iJ)UV5?b_m}=KB1ZlXhfeTXuB5J*B5Er|EM+=Gc(jYQGDroNUibLlg0Sboh zI?{2DeysRl{2ln?Be7HKqZOI(N6>D~CLO^GjF}GqBZtkfe!L(%r_l}fa!oHc@n#KE zEYvL9jiBfQt7>b@#FzU@8Z6||$hA$!9;QBadR|!UM>9x=fKtt2$vZ$EWt%A2b41bL z`i7`|qJeanL+1eBi7MaQPo^^V_X@8CPOy82B`R*Q`&Nb$jOyDze{@v-uKS)X4~ zEkk2?pGHbQS7J_xYuUfLQE{vcZT_C=@Z~28S4+)zrxl4yXmbY;{Ij)}uJh=9m@?Cf zGq`aw*=quU3Av^bqX#!|uh&M;h2@sVrv|Dqioi zlj(8gUl54zvHi7#T4llpwx^W#DJGAHf&VNMbA6tk1}$f zRX7HyVTf^tMu?2Po$9gVk`)Gb-~NR!KSYT%)j9bJ{|hp8R&op|{DTmRcC~bM!`Jnz zQnQuy`=jZA!i^})`kfN*JXV@18~)f~*9&ga1;fSpkk$E-7lCgw3OOyCu|Nc}8UT6c z+Mbo1=zrw1CYb~1+(b1F(a!l9zU@ajccV4IwOR~O(3jC6&zrD260?!N8GO@-lJZQ` z7iDhB6f5()PGCs3dN(#!*Qb-tE&3^T=IfK57iZ#cvPaDp#SM;gDkkO{UcWN8fhOLI`yjM+;YdFmy&*XEVR_|CPr&sXp2OTSL+ zdC=X-dCp6tS)NZ6b_0Mj6pL3JDoN>2kBydLcN14v ze6((2bs_XpgG7b*M$Mt7JItYR`_wfb8Tf{YdHt!1bra9a>+-%4bF=||5?zg&30Iyp zoi+;a2{=rdbJJs*+|Vu{_%TNks6N9|pCleX3*89dM}D05kB>zkIo`IBn@{0KqOC%^ zlKI#VK0LwD+ItlG+S`1{sfSA$MY<@__<$;t3rCua*QL41X64o+`o;dtW*#ltaX{pm z(>Tw~P0uWqOFL9?cs@?ivp6a!rMZ!ZgoK;@ z_?-UCCq+oh)lhsH4w=D{N2%LE`Gxc-> zlvnpPg{jbV&yCy{A|mL^`*la9x6)#P$B;h<$^Ml6DN^We!*N_9EFKSwvz}(XX0UQ` r<7rh@{5VHHPsjhJvj0CN@fj?EN|m7;mx7_a{|aDm#+3A2haCN1RuniJ literal 0 HcmV?d00001 diff --git a/crates/loic-gui/icons/loic-observatory-64.png b/crates/loic-gui/icons/loic-observatory-64.png new file mode 100644 index 0000000000000000000000000000000000000000..e1e9d9434c8a76e9e4d0b0d69d497974f8944051 GIT binary patch literal 852 zcmeAS@N?(olHy`uVBq!ia0vp^4j{|{BpCXc^q7E@Lb6AYF9SoB8UsT^3j@P1pisjL z28L1t28LG&3=CE?7#PG0=Ijcz0ZK3>dAqwX{BQ3+vmeM~FY)wsWq-xV!>k~Cf^+A3 zppa^bYeY#(Vo9o1a#1RfVlXl=GSfA%)HO5;F)+3=HnK9Z)HX1%GB61DxPBQ$LvDUb zW?Cg~4QitK`9KXCa2rZ8b5n~;5_1c1>nUXL+W>U6g{O;SNW|f{(+^IaZ6M&V|MRy# zs|G$F_GQf0q7T*{czM8&)lcg{bYr=8!`cHS4cnPKSSL5PKWu3^jWT~|IZ)c@iizm)Ovm7f5vH9Ut+l$g4CA&n)v0{?BK^fio6Hv zPW_p(!)|*o^8|^A*0ZNm_RMvz=D)$XMe%q1y@n-ag4_?kS{K~=;rzYk(*Dyr!49!| zUvAX8Y}av#>CK;iyk`4vmkMSdI-2J=&EeJ7`zrT(Xj^e)2-V~7Weeud-mI>Qz z7qDm?`_{{J!uE-G%6U1#i4Adn9~#axta{0)tstq-pujih{l4<9juV0lBwsygoSWI{ z`#?Z&CxcA87FUP!H>(4!j2yXKD|FGluyo``CZZ>ZSzI9GrX6y3VN$G z8NFuey$(-PhEs7s~cklh@RlTZvr)uW(*JsY@t~uv?)7=0-fE+L|0FuOj zW(a`m000c;Z&(Qd03YebV*jouwe3&<;PHRMhDZQTqXB^7zv0hh0Qgan9FVR*{ytFy zU_$a8qpzz$OU3a=L#s(pH6Te+FJPb`J%DUlP9sTRYzYQB00i=r+(iPgOX`B>0q`LW zy=eXCEdW^EGwUwNlN1OWEe%z06cyjwOhRaHO&vA#A|(wH!`VeyTT1HU^HwwQw!7wS zFKg>*PZB^JD~=Pv%7}=G8)7A7CB$XLWrVO;SuEC=FgE-@3|!po9IprbV*`E`H#d^O zng1Ta+tJ0|%ln#(`#-kv0J>!)n_NxR3x;gNx8uuM!u6R|L>;bmiZ0tB56K&bbRPjJ zca+AebeL?I>x>_w>{T1B;)!+yM-|p6(JOH~FW>4Pe4DsDd9I@BAOP2Fd8vYQKWKV~Zk~GWyB@f}aXkGW)xC7y_Hg#JI zLxqOtlev#2Uh$V?vipp9N6Y!qwk#{~hISsXxuwZo2#^(kmr2tFnrgbLCCb*}|4aBV zBsJ!*@Lgf#JM#zp+lLQ2{U?0VJ?|g3_(WhCRGZgtrOLu|`hqZB4w66?QbZK}ev*Lp zAYmd)8lAH-#>zA6B#k<+=-cxX57p)5IF>I8t$BS|LsO)_jw-EBwGNJqXk8UmqbZrR z;JI7aw$GDwkvfzw>Fb3i^2?(ZuXS2{69L=Gr^BgiV8!-(;EUCKs)i)`(lGIKQDpEv;}__hDh-4lO6p9|WFCzu=DA>z3JV z>a0vzix#U+q+tu@JEqNyiU7xPQ9SF# z;t?q${#p8viW*@5N*_bK`bX;(4F!V z9nK7zpjy2$Q-jE)dP;|3=?&?EL4e+V<2!B%FLuWbF6YS3(XEzUx0x64UT`oNe_$ou z(Ejj%+izLyrdxPUk~MF2{~MFM5N{RcqOf?M0OP*&qCk`)9B4GXYmqm4b?L!Pz#HLd zR0_IBrJRKEVgNnZbKroX#$6Rqp;t}ckEUd`1f*WYU|I;AD%~?;uoQgjdS ztTqoVF{FDxsYda2EHZ)3r5>mB~CMO0|bM4)0EsBBQqV6dVqbs1t_qg@0^5WL*Er9o4qP_;d+=_Hr4A9#`oKDw>d;y%&$WR9kaEK>xya6c!)C} zcZ2?Q=+w7<@zL96MLG-$0U5L%KIpvM)>{AlZvmtjmqPnw?wS>hPdr=5|3yu~Bt86B zP0bl8vi?WZ6za{Nn)07q&X^7+)l}!e!3L)bjDvLYn+sN(~JQiIi*D*ZFpni?2RB{y%|JmJ)Gl^p1q zv?PmUa54>SY!C4B=b*<-os^X$a(S@UOqz;xcp0;_8>2KH9{vwj;UM+rAv9yJe^ z65sc)l!`hmXPuJADO|bAd(GUB9^SlJwoonG!bZ$(Fbe<<5z~{nXp6DR`Rk~efRh6^ zS(XpYziw^F$kRjT{9hf5Qy-Se2n`lZf@iv4woR4B9g6Zo60D1H4fNWO7Pv()(*WX! zvi)B;H6v}nj2z!X^o*i!0^3ZEFjV5-<9P9Bjn%$el_8h4lE>FIv(zFf%-SPG0{=xR z3OM3+&oRCi#$$QGQk!2*Zh!{5@L6UsmYJN-R4xu~<=YwIJoI3{`g9&*F?$!d#Ny7!kSq~d$zE<(P&oXeHb$+OYafXv z;3^b4gFl!vSyRd1`N3yY!Fgc}on;Q`{?cHa$=;D!&?MyB1<@#IEQc+G5Kx}I1G!ab zPYL>>r8w2sCp8Wx6C9`l+XPaYP#ZSPGtR~F{!cu~5gX*hVhz)j+VhnrdX9wzG9Z6I z=6DHryU{)=QQq%TH+^FcC_CFzP%z<}@r+Xg9z~sr&-elwK33}fZrov{0pn63ioh*2 z=A#k>j)BQ)a))c*b4noCEK|6nEpKx0!{r%j2>a{F#Q4xXKATM&M=5$F5t3jAr#p|U z&oG;;2sBav{aM126+7T~c?E@-@ebT5)poKEV|2HYjh)hT(=dD4Wwu4TGJQ2k)+|h` zKn3q2&w6ovP$S2(-R;oL=E%a0j{-c**;bmH+*B8WWboC-!neHA*)lG3+ZO6?>#pNy z!C~UwWCDeLF`r=$K_{%08a~6^tM&AfQ(BnnEPC*>gLFc(OI6Ylv&9`q|4~Vrh;Xd1 zJ-PT}QP|);&Dz9J=qXnrbPF)t^9iIf{GfNopjZm#zv6{1PcM0*(S9=&=#<=e<*Bf# zbZRULP#iF~23kLH$vc16n-X8(X5;rz1GoFmGQZv&U`lp9n5Sa7uCjmco|u1P#0Ik? z;f9gna;{tY)_0eLmZyFtJ9pyxuIFh4|88sO^E?B8TS2ErY_V~-)}@t%f5er zGsLkXcTQRgT#g#M2ip03p5r{KebHc6-@SWiEjO(mM3fR**T_Z)3+tcNu#W zK;-<^(i)a`>7e(9{5C`?fO zH2d2i6qx9jx{#wPNM`~6Y|T$PS^yCEi{Jy;x9dpg-+#+U)%tgWfBZ3cR+^3|ww>X( zAXrw7a1tuZ54RI?&kvVo88-`SWKlJ4k!CR|!c0=VEXJo(dDF9Yra%Tss)&BtRY}`U z=HIMRW#@cSX~A1;=t3o-KTNSUW`8YB>*J(K%N-rWf}k>Dpvb7sjllq z-_$N&VcC_B9hSalpa(F&zwh4beC$08S>Aiv$vi7;rX8_LH}hF(%qq{VBDUGROM$6i z!ZTd0(q*c8S>o`^c=uZmsWP<%S7)DTXr!k1M$zcl?=#Pu29_wnq>P~Z+2Q@!HV6AS zsnZOZK>q2MM7_~l0Qj>xQwjhj_iJuH`joVt57|(wYxKNkb93AZvGP|UXg(u}2o~?o zsl(XUPi|z!LuDP`+;KHD@x!R5kAQ6K62yyu;Ve+In%-p z+z94V=;l{dUMAaHY^L`rm}*eO6HI2)N6u+$@12AYC!qO#v}R4hPK(w0RJF^}_ean0 zJvmKCSd2GBatz0z8SKJi%}=#;O8Its%G$ukd1%K&EF6ypW&~%~Bj+JxXqrXX+YBGz ze!G1Rn)9^TH#(7w!FdZ>0C^q{7Y-|RE^ zDrBr#CS&n*(y(%ai#sI`{9Cw-r6=j}!mSpvkg}t4WP3aC>bM5({wPBPGNorfP;L2dbX|h zv&~OlCGki7#_NKv1-!@8B7_! zJ^@J0yU)3Rql)g=gCj!xG1RzJX(=s!b25p~u$1G5OAgBO2Q4k zq}#o(z0eG~A3STj)QDGXL?;u~!xpJygemLc(!r%i(aE-X|%S>giLLl^ww zhec*2zjxXq<{Sg~TNGC}4D!g8dqFStF?rA+TCIyFzJSIlwLf}@>95Y}#yvvA_C6_U z6v1+8g$De@B@`AWZGoSjNUQvyXoy{oH*Q6NDPm8dXNTr(?yXBa{Gk1pWG)p${FhPC zN{Q8#$rbis@Nfdvj(Q-V2Y5S58+N=ykogRx#)&ozJ^rj=Yf7F5|J6$gk`;@ z{!v!^@v*?-L^zMlaGw<^18~QG)g?pW~u~4D_`hiUy>(@tkJX zs|dMMi;ISD{71;Mo3ed-372sd_xwJLoW}#j8L7j-0ekK>wh`jo@bwZ-yrh zpxK7%+AB=$OvcD6t z$g~aB-+LQyBlA`GFgjskF-Pj?_n9a3`Cs_mOKFE3BRp45E4THLwHNeqSa*BZeDOb` zW9Mr_7Sa~j-?|#MFozIy>M)9jLGobFb6s4&Gw{D?l` zp_y;34%~ZXOG$IzE(P~k&Hb%#A2J8WmA;-}HaMQm#^iSql-Z^F)p7Q8jQXF$i1S7; zO`J~RSYho7&6d2}aMZW6-dcIXN*Vc5O8Y~6^R-sb>Yn90l!~BQPW{WrLMEpvhoQAN zMs<+S$O8bc$~oF#x2DaKn`36zr6Cha8a4eXH|Huo*JPyrRB6{;sh?6h#XmY3iesF< zfsJ_p^5jzMI|5f6Ukm(9Mh$8K%oKCV^w^%xk?H-c-UF*3YKk*5iC{ zzk%deOU=xmt)o+BeXS#By!G~$`_OEBrp4XCpZ)73yDRqAVgg-{k-pYh{3YgZdP`Pn zrYSmFgC4I)3*-u#9Ot|FFWp;j2V}l+lvj|82~h8vjY)A1lx?bz`4%|<0F&F>qFxZf pSX=9=51j#IIe-~P=mRSJ{|Ufq9#Y@mGv%01GCW6`&wroj{})A{Y9{~y literal 0 HcmV?d00001 diff --git a/crates/loic-gui/icons/loic-observatory.png b/crates/loic-gui/icons/loic-observatory.png new file mode 100644 index 0000000000000000000000000000000000000000..c33b501a6d243b62a1c9698008ed852a8e720935 GIT binary patch literal 3038 zcmc&$S5Om*65S*~2uKyAJs?p)rDy^esuC#*(h&tjiUK0iLT>`0T}3ImUYdwBm2w5C zB28)p6cDa(=}MEXbfrpOzTV9HxPNcv{p{{JJ7;!hXJ=<)O^hybunDsP0EeEgwiy6| z5h8$#tV!}0oYpf zw9lIdj(mUmIdoc?vx%_vBw#_hvPVJj*o zrL*~R3ACpm%#yT`A30VP9oqSJ1b}xR8Y@>_I~$+NVCC3Iwa8Do@P7)|lede4ep*jLzk&{JZM$eaa8bi~+kdxBIaDsc#>`_F-;2-?Xf?LDVYe z#H7Zc-E+_K_(pQaS>F6%??|0W_tC2F3I|g|AKrT@mFg^bxcQAE`m4K~3kL>wPP}O7 zS;D}GiZuCT-~M##ZKnjKW84{_o;&r(c;GHTpr9M(IB1Y>cz)~FFmO8%WLjP0lCYkg z6+auVel_aQB&rF?@7q3l5dS8}IU^BK+BQQb(($1N0l3F?J7IurJBzNG9Tbael=&#y zf~F8PV~T12vykt7u*ARCFzDy0i~sr&s;c8mwO;0!q1n~MuP=tPkh+iu z_P6Oz-gJmPd?=KGs8ld-a@hWsPC){7=qv1V)EP4ADv_D(7w)J|yQW5agpUsB z?+Te)zk+BxNn(F@MXpe$=BA4UMBbyJ=hB&Rl<`@9$^?!eiezD}b3t02rZnN!QeOU& zGQJ-i=?XWrrjFGh<+*yp4o7^gEqTkrO_Y$jN7^8Da-C5*TKkj8O6s7dZBk52^#n#H zZFkNyVI6f1JQ_Ka*Dkd&TX3Qgtb)AaqKnfO9YdwAUi0;&2XgI$4U-&e!|L;4U1w)l zUS-}dU}lfiV`i=AiJkAqE*HQ#LL|qJ*9dXVlTFVC<8hYDm}9qVr6<;N>!WE&NbP2U ziNbvUdes36(>XM$2V>1AT3A?tkZ@ET0-ME)l}ETpvMn~M2u&BwXc`TC z+HSya+4F9F{qIeS9$!)UafaLaJkjBU5RQ=J;>@27(PShoPps;)RWwJ&s8*(^tz{VA zNVrHdz-?}w_gnwRl_(~v6@y}>e0hU@!mP2luc-@`Do%47{gCk{<|TV+kRJ+qj9?FLL12GS z@NpK#QMp;9UST>DC(u>bj^_k^a$QL)s%>;z+vsQ+b=Xk{(uU)H`8F|5{da`t8<8*Hem4 zLwZAXiFZM|EW3hV5K8aCpJL#mW%TtIT{rPC(~we02?y!NNRp&^3CEe@A3?O+w3NG% zPASO{boJF$sFUy-LvxGV*j(9E%fu>>RWbJ zGTTrrbS~;2*8Vkyl&-5kHT3o!Q;1J>$nRylQQ1VX^bM+Y?@*Q?Z@?uebxaMY742*r z2t0+Amx$sWK9(fBBG3_@rFglX-o3riQt51`i7HYu7)xxt(c)dz`TaM{IjB;*F!i~B z*LC#vr?mv03y{Zy1CY=<#S!Y+@Z;5;LF-$}2usW%9g|T{x7U&$$taW2l8y&T%SwjD z-`cs0V_j!plkvwrS4*vH3tn+~b9_0OsaGGcqkJjjgL{T_tGLXrUv?qvtS3~;Lh@yF z5L72U`HNc|2R6wuowltFdn}EWd7f;FS5o5)>96try~_l9|1X1PhlcKqg^W*e9~P85 zB6lcc?sk9Ux>Tsg>ZF{#>hCqJHQ_EmO$iXYgmbb|&KTxL!&=x<4xj8_KFg0@ki?*A z(S5Vbt)h!vDK(TGu*JI2MBj*KUXa-8}65fxmla$NvQs ziIS{~KUf2Lk}H-P`6lh}r%e0XM^E?~?|tt^3rboQe+ZontX2F_zPA<|>~WYet&=2E zz8T{sI~}VOL;YT_3dYA-ekj}RL0%ELB_=52os0Tewb-Bw9n-NXZo#Sz` up to, so that this side and the shader agree on how +/// much there is to read. +#[repr(C)] +#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] +struct Uniforms { + /// The surface's width and height in pixels. + screen_size: [f32; 2], + /// Eight bytes of nothing, so that the block is sixteen. + _pad: [f32; 2], +} + +/// One vertex of a scar: a position in pixels and a colour with alpha, six +/// floats, twenty-four bytes, the layout the shader's two attributes read. +/// Positions are in pixels from the window's top-left corner, because that +/// is where the click arrived in and where the hit tests live; the shader +/// carries them to clip space, so that nothing on this side has to think +/// in the GPU's coordinates. +#[repr(C)] +#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] +pub struct ArtifactVertex { + /// Where, in pixels from the window's top-left corner. + position: [f32; 2], + /// What colour, as red, green, blue and alpha, each from zero to one. + color: [f32; 4], +} + +/// The GPU state for the scars: a pipeline, the vertex buffer every frame's +/// geometry is rewritten into, the uniform block, its bind group, and the +/// count of vertices the last `update` produced, which is the count the +/// next `render` draws. One of these exists, owned by the render state, and +/// what it draws only accumulates. +pub struct ArtifactRenderer { + /// The render pipeline: `artifact.wgsl`'s two stages, alpha blending, + /// a triangle list, and the defaults for everything else. + pipeline: wgpu::RenderPipeline, + /// Room for `MAX_VERTICES` vertices, allocated once and filled from the + /// front on every frame. + vertex_buffer: wgpu::Buffer, + /// The sixteen-byte uniform block: the surface's size, and padding. + uniform_buffer: wgpu::Buffer, + /// The one binding, the uniform block, for the vertex stage. + bind_group: wgpu::BindGroup, + /// How many vertices the last `update` wrote, and therefore how many + /// the next `render` draws; zero until the first collapse. + vertex_count: u32, +} + +impl ArtifactRenderer { + /// Assemble the renderer for a surface of the given `format`: the + /// uniform block at a placeholder size the first `resize` corrects, a + /// vertex buffer of `MAX_VERTICES` vertices allocated in one piece and + /// never grown, the single bind group, the shader compiled from source + /// embedded in the binary, and a pipeline that consumes the vertex + /// layout — a `Float32x2` position at offset zero and a `Float32x4` + /// colour at offset eight — as a triangle list with alpha blending. No + /// scar exists yet; the count is zero and the buffer's contents are + /// whatever they are, which is fine, since nothing reads past the + /// count. + pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self { + let uniforms = Uniforms { + screen_size: [800.0, 1000.0], + _pad: [0.0; 2], + }; + + let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("artifact_uniforms"), + contents: bytemuck::cast_slice(&[uniforms]), + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + }); + + let vertex_buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("artifact_vertex_buffer"), + size: MAX_VERTICES * std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + + let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("artifact_bind_group_layout"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }], + }); + + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("artifact_bind_group"), + layout: &bind_group_layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: uniform_buffer.as_entire_binding(), + }], + }); + + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("artifact_pipeline_layout"), + bind_group_layouts: &[Some(&bind_group_layout)], + immediate_size: 0, + }); + + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("artifact_shader"), + source: wgpu::ShaderSource::Wgsl(include_str!("shaders/artifact.wgsl").into()), + }); + + let vertex_buffer_layout = wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as wgpu::BufferAddress, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &[ + wgpu::VertexAttribute { + offset: 0, + shader_location: 0, + format: wgpu::VertexFormat::Float32x2, + }, + wgpu::VertexAttribute { + offset: 8, + shader_location: 1, + format: wgpu::VertexFormat::Float32x4, + }, + ], + }; + + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("artifact_pipeline"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_main"), + buffers: &[Some(vertex_buffer_layout)], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: Some(wgpu::BlendState::ALPHA_BLENDING), + write_mask: wgpu::ColorWrites::ALL, + })], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }), + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + ..Default::default() + }, + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + multiview_mask: None, + cache: None, + }); + + Self { + pipeline, + vertex_buffer, + uniform_buffer, + bind_group, + vertex_count: 0, + } + } + + /// Take note of the surface's new size by rewriting the uniform block: + /// the geometry is in pixels and does not care, but the shader that + /// takes pixels to clip space must know how many pixels there are. The + /// Observatory calls this once, after construction, since its window + /// does not resize, and the scars stay where they were put. + pub fn resize(&self, queue: &wgpu::Queue, width: u32, height: u32) { + let uniforms = Uniforms { + screen_size: [width as f32, height as f32], + _pad: [0.0; 2], + }; + queue.write_buffer(&self.uniform_buffer, 0, bytemuck::cast_slice(&[uniforms])); + } + + /// Rebuild the vertex buffer from the current list of scars: every + /// artifact's geometry, generated afresh and concatenated in list order, + /// written to the buffer from the front, and the count recorded for the + /// draw. Called every frame, whether or not the list changed, because a + /// frame is cheap and remembering whether the list changed is a way to + /// be wrong. Past `MAX_VERTICES` the excess is dropped, the buffer being + /// what it is; nothing is written at all when there is nothing to + /// write, so an Observatory that has never collapsed never touches the + /// buffer. + pub fn update(&mut self, queue: &wgpu::Queue, artifacts: &[Artifact]) { + let mut verts = Vec::new(); + for a in artifacts { + generate_artifact_vertices(a, &mut verts); + } + let count = (verts.len() as u64).min(MAX_VERTICES); + if count > 0 { + queue.write_buffer( + &self.vertex_buffer, + 0, + bytemuck::cast_slice(&verts[..count as usize]), + ); + } + self.vertex_count = count as u32; + } + + /// Draw every scar into the frame's render pass, after everything else, + /// so that they lie on top of it: one draw call over the vertices the + /// last `update` produced, or no call at all when there are none. A + /// scar drawn last is a scar that cannot be covered, which is the + /// point; the Observatory's other panels are painted beneath it and + /// stay beneath it until the process ends. + pub fn render<'a>(&'a self, render_pass: &mut wgpu::RenderPass<'a>) { + if self.vertex_count == 0 { + return; + } + render_pass.set_pipeline(&self.pipeline); + render_pass.set_bind_group(0, &self.bind_group, &[]); + render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..)); + render_pass.draw(0..self.vertex_count, 0..1); + } +} + +/// The cell a position falls in, counting from zero, or `None` to the left +/// of the first cell: the floor of a non-negative quotient is the cell, and +/// a negative quotient is a point outside the row, which no cell claims. +/// The `floor` is explicit and the cast merely confirms it; the truncation +/// clippy warns of is the selection being made. +#[allow( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "floored, a non-negative quotient is the cell the point lies in; the cut is the choice" +)] +fn cell_index(quotient: f32) -> Option { + (quotient >= 0.0).then(|| quotient.floor() as usize) +} + +/// Hit-test a click against a scar's blocking shape: `true` if the click +/// falls on what would visually be a non-transparent pixel of the artifact, +/// approximated by the artifact's structural primitives — the baseline and +/// teeth of a gear, the ring and dots and phantom of a failed mask, the +/// rings of a soliton — since the pixels themselves are on the GPU and are +/// not read back for anyone. The Observatory asks this of every scar before +/// it lets a click or a scroll reach the wheels, the bar or the button, and +/// a `true` from any of them ends the matter. +/// +/// The hit shapes are deliberately approximate but tight enough to feel +/// natural: clicking through a transparent gap reaches the interface +/// underneath, clicking on a tooth, a dot or a ring does not. +pub fn artifact_hit(artifact: &Artifact, click_x: f32, click_y: f32) -> bool { + match *artifact { + Artifact::GinGear { + x, + y, + rotation_deg, + size, + } => gin_gear_hit(x, y, rotation_deg.to_radians(), size, click_x, click_y), + Artifact::FailedMask { + x, + y, + entropy_bits, + size, + } => failed_mask_hit(x, y, entropy_bits, size, click_x, click_y), + Artifact::Soliton { + x, + y, + ring_count, + radius, + } => soliton_hit(x, y, ring_count, radius, click_x, click_y), + } +} + +/// Whether a click lands on a GIN gear: the click is carried into the +/// glyph's own frame by the inverse of its rotation, and tested there +/// against the baseline bar and against each tooth, the same rectangles +/// `gen_gin_gear` draws, with the same tenth of a cell of padding taken off +/// either side of a tooth. Rotation is the one trigonometric act in the +/// hit test, and it is performed on pixels, which forgive it. +fn gin_gear_hit(cx: f32, cy: f32, rot: f32, size: f32, px: f32, py: f32) -> bool { + // Carry the click into the glyph's local frame by rotating it the other + // way about the glyph's centre. + let dx = px - cx; + let dy = py - cy; + let cos_r = rot.cos(); + let sin_r = rot.sin(); + let lx = dx * cos_r + dy * sin_r; + let ly = -dx * sin_r + dy * cos_r; + + let half_w = size / 2.0; + let baseline_h = size * 0.10; + let tooth_h = size * 0.30; + let cell_w = size / GIN_BITS.len() as f32; + + // The baseline: a bar the full width of the glyph, from y = 0 down to + // y = baseline_h, in a frame where y grows downward. + if lx >= -half_w && lx <= half_w && ly >= 0.0 && ly <= baseline_h { + return true; + } + + // The teeth: each set bit of GIN occupies its cell above the baseline, + // rising tooth_h; the cell is found by dividing the offset from the + // glyph's left edge by the cell width and flooring. + if ly >= -tooth_h + && ly < 0.0 + && let Some(cell_idx) = cell_index((lx + half_w) / cell_w) + && GIN_BITS.get(cell_idx).copied().unwrap_or(false) + { + { + // Inside this tooth's cell horizontally. The tenth of a cell of + // padding on either side that the renderer leaves, so that + // adjacent teeth do not merge, is left out of the hit as well, + // so that what blocks is exactly what is seen. + let cell_left = -half_w + (cell_idx as f32) * cell_w; + let pad = cell_w * 0.10; + if lx >= cell_left + pad && lx <= cell_left + cell_w - pad { + return true; + } + } + } + false +} + +/// Whether a click lands on a failed mask: on the boundary ring, on any of +/// the seven dots, on the phantom dot beyond the ring, or on the thin line +/// that joins the ring to the phantom, each tested as the disc, annulus or +/// band that `gen_failed_mask` draws. Every dot blocks whether it is drawn +/// filled or hollow, so the entropy bits, which decide the filling, decide +/// nothing here. +fn failed_mask_hit(cx: f32, cy: f32, entropy_bits: u16, size: f32, px: f32, py: f32) -> bool { + let r_outer = size / 2.0; + let r_ring_thickness = size * 0.04; + let dot_r = size * 0.06; + let phantom_offset = size * 0.35; + + let dx = px - cx; + let dy = py - cy; + let dist_sq = dx * dx + dy * dy; + + // The boundary ring: the annulus between r_outer less the thickness + // and r_outer, tested on squared distances, since a square root would + // be work and would change no verdict. + let inner = r_outer - r_ring_thickness; + let outer = r_outer; + if dist_sq >= inner * inner && dist_sq <= outer * outer { + return true; + } + + // The seven prime-dots around the ring, at the same seven angles the + // renderer uses, starting from the top and going round by sevenths. + let dot_r_outer = r_outer - r_ring_thickness * 2.0; + for bit in 0..7u8 { + let angle = -std::f32::consts::FRAC_PI_2 + f32::from(bit) * (std::f32::consts::TAU / 7.0); + let bx = cx + dot_r_outer * angle.cos(); + let by = cy + dot_r_outer * angle.sin(); + let bdx = px - bx; + let bdy = py - by; + // A dot is filled if its prime is active and hollow if not, and + // both are hit as the whole disc; a hollow ring with a hole one + // could click through would be a scar with a loophole. + if bdx * bdx + bdy * bdy <= dot_r * dot_r { + return true; + } + // The entropy bits are acknowledged and not consulted: the shapes + // are identical for hit purposes, and the bits decide only fill or + // stroke, which is the renderer's business. Naming them here is how + // the compiler is told they were not forgotten. + let _ = entropy_bits; + } + + // The phantom dot outside the boundary, at the eighth slot's angle, + // pushed out beyond the ring by the phantom offset. + let phantom_angle = -std::f32::consts::FRAC_PI_2 + 7.0 * (std::f32::consts::TAU / 7.0); + let pdx = cx + (r_outer + phantom_offset) * phantom_angle.cos(); + let pdy = cy + (r_outer + phantom_offset) * phantom_angle.sin(); + let phx = px - pdx; + let phy = py - pdy; + if phx * phx + phy * phy <= dot_r * dot_r { + return true; + } + + // The thin line from the boundary to the phantom dot, approximated for + // hit purposes as a band three times the drawn line's width, so that a + // line a pixel or so wide can be hit by a person with a pointer. + let line_thickness = size * 0.012; + let lx0 = cx + r_outer * phantom_angle.cos(); + let ly0 = cy + r_outer * phantom_angle.sin(); + if point_near_segment(px, py, lx0, ly0, pdx, pdy, line_thickness * 1.5) { + return true; + } + + false +} + +/// Whether a click lands on a soliton: on any of its concentric rings, each +/// tested as the annulus `gen_soliton` draws, of the same radius and the +/// same thickness — eighteen percent of the ring pitch — on squared +/// distances. The gaps between the rings let the click through, as the +/// gaps in a ripple would let a stone through, if stones were clicks. +fn soliton_hit(cx: f32, cy: f32, ring_count: u8, outer_radius: f32, px: f32, py: f32) -> bool { + let count = ring_count.max(1) as usize; + let thickness = (outer_radius / count as f32) * 0.18; + let dx = px - cx; + let dy = py - cy; + let dist_sq = dx * dx + dy * dy; + for i in 0..count { + let r = outer_radius * (i + 1) as f32 / count as f32; + let inner = r - thickness; + let outer = r; + if dist_sq >= inner * inner && dist_sq <= outer * outer { + return true; + } + } + false +} + +/// Whether a point lies within `threshold` of the segment from `(x0, y0)` +/// to `(x1, y1)`: the point is projected onto the segment's line, the +/// projection clamped to the segment's ends, and the squared distance to +/// the clamped point compared with the squared threshold. A segment shorter +/// than a thousandth of a pixel is treated as no segment at all, since a +/// division by its length would be a division by nothing wearing a decimal +/// point. Used for the phantom line of the failed mask, and for nothing +/// else. +fn point_near_segment( + px: f32, + py: f32, + x0: f32, + y0: f32, + x1: f32, + y1: f32, + threshold: f32, +) -> bool { + let dx = x1 - x0; + let dy = y1 - y0; + let len_sq = dx * dx + dy * dy; + if len_sq < 1e-6 { + return false; + } + let t = ((px - x0) * dx + (py - y0) * dy) / len_sq; + let t = t.clamp(0.0, 1.0); + let cx = x0 + t * dx; + let cy = y0 + t * dy; + let d2 = (px - cx).powi(2) + (py - cy).powi(2); + d2 <= threshold * threshold +} + +// ═══════════════════════════════════════════════════════════════════════════ +// Geometry generation: the three scars, as triangles, in pixels +// ═══════════════════════════════════════════════════════════════════════════ + +/// The colour of the live calendar: white with a cast of cream, at +/// eighty-five percent — the colour of the cosmic span, and of a gear's +/// bar and teeth, and of a dot whose prime is active. +const COL_WHITE: [f32; 4] = [0.92, 0.92, 0.95, 0.85]; +/// Amber, the project's primary accent, the colour of the headers and the +/// carets; here it is the colour of a soliton's rings, before their alpha +/// is tuned ring by ring. +const COL_AMBER: [f32; 4] = [0.95, 0.65, 0.20, 0.85]; +/// Dim gray, for what is inactive or decayed: a failed mask's boundary +/// ring, and a dot whose prime the entropy did not choose. +const COL_DIM: [f32; 4] = [0.45, 0.45, 0.50, 0.65]; +/// The phantom's colour: red-tinted and dim, denoting the bit that +/// overflowed — the eighth dot of a seven-dot lattice, and the line that +/// points to where it would have gone. +const COL_PHANTOM: [f32; 4] = [0.85, 0.25, 0.25, 0.70]; + +/// The GIN bit pattern from the project's logo seam: G = 1000111, +/// I = 1001001, N = 1001110 — twenty-one bits, which are the seven-bit +/// ASCII codes of the three letters, 71, 73 and 78, most significant bit +/// first. Each 1 is a tooth of the gear and each 0 a gap; eleven teeth in +/// all, and the letters are legible in them if you know to look. +const GIN_BITS: [bool; 21] = [ + true, false, false, false, true, true, true, // G + true, false, false, true, false, false, true, // I + true, false, false, true, true, true, false, // N +]; + +/// Append one scar's geometry to `out`, dispatching on its variant: a +/// gear's rotation is given in degrees by the artifact and in radians to +/// the generator, and everything else is passed through as it came. +fn generate_artifact_vertices(artifact: &Artifact, out: &mut Vec) { + match *artifact { + Artifact::GinGear { + x, + y, + rotation_deg, + size, + } => { + gen_gin_gear(x, y, rotation_deg.to_radians(), size, out); + } + Artifact::FailedMask { + x, + y, + entropy_bits, + size, + } => { + gen_failed_mask(x, y, entropy_bits, size, out); + } + Artifact::Soliton { + x, + y, + ring_count, + radius, + } => { + gen_soliton(x, y, ring_count, radius, out); + } + } +} + +/// Render the GIN gear glyph: twenty-one cells in a row, the 1 cells raised +/// as teeth above a baseline and the 0 cells flush with it, the whole glyph +/// rotated about `(cx, cy)` by `rot` radians. The baseline is a tenth of +/// the glyph's size tall and the teeth three tenths; each tooth gives up a +/// tenth of its cell on either side so that neighbours do not merge into +/// one long tooth, which would be a different letter. +fn gen_gin_gear(cx: f32, cy: f32, rot: f32, size: f32, out: &mut Vec) { + let cell_w = size / GIN_BITS.len() as f32; + let baseline_h = size * 0.10; // the baseline: a thin bar, a tenth of the glyph + let tooth_h = size * 0.30; // the teeth rise three tenths above the baseline + + let total_w = size; + let cos_r = rot.cos(); + let sin_r = rot.sin(); + + // Emit one quad given in the glyph's local frame — origin at the glyph's + // centre, x along the baseline, y downward — rotated about (cx, cy) and + // appended as two triangles. + let mut emit_quad = |lx: f32, ly: f32, w: f32, h: f32, color: [f32; 4]| { + // The four corners, in the local frame; the glyph is centred + // horizontally on cx. + let local_corners = [[lx, ly], [lx + w, ly], [lx + w, ly + h], [lx, ly + h]]; + let world: Vec<[f32; 2]> = local_corners + .iter() + .map(|[x, y]| [cx + x * cos_r - y * sin_r, cy + x * sin_r + y * cos_r]) + .collect(); + // Two triangles, (0, 1, 2) and (0, 2, 3): the quad, cut along one + // diagonal. + for &i in &[0usize, 1, 2, 0, 2, 3] { + out.push(ArtifactVertex { + position: world[i], + color, + }); + } + }; + + // The baseline: a thin horizontal bar across the full glyph width. + let half_w = total_w / 2.0; + emit_quad(-half_w, 0.0, total_w, baseline_h, COL_WHITE); + + // The teeth: one rectangle per 1 bit, rising above the baseline. + for (i, &bit) in GIN_BITS.iter().enumerate() { + if bit { + let lx = -half_w + i as f32 * cell_w; + // A little horizontal padding, a tenth of the cell on each + // side, so that adjacent teeth do not merge. + let pad = cell_w * 0.10; + emit_quad(lx + pad, -tooth_h, cell_w - 2.0 * pad, tooth_h, COL_WHITE); + } + } +} + +/// Render the failed-mask glyph: a circle for the cosmic boundary, seven +/// dots arranged around it — one per cosmic prime, filled if the entropy +/// chose that prime and hollow if not — and a phantom eighth dot dangling +/// outside the circle in red, joined to the boundary by a thin line, at the +/// angle the eighth slot would have had if the lattice had one. +/// +/// `entropy_bits` is the value the library carries in +/// `LoicError::InvalidMask` — the upper bit, `0x8000`, flags a cosmic-pool +/// selection, and the lower eight bits are the index that overflowed. The +/// active primes are the lower seven bits of that index; its eighth bit, +/// bit 7, is the one that made the index 128 or more, and it is always set +/// here, because an index below 128 would have been a mask and not a scar. +/// The glyph is therefore a picture of the exact malformed question, with +/// the bit that malformed it drawn where the lattice has no room for it. +fn gen_failed_mask(cx: f32, cy: f32, entropy_bits: u16, size: f32, out: &mut Vec) { + let r_outer = size / 2.0; + let r_ring_thickness = size * 0.04; + let dot_r = size * 0.06; + let phantom_offset = size * 0.35; // how far beyond the boundary the phantom hangs + + // The boundary ring: the cosmic limit, dim, forty-eight segments. + gen_ring( + cx, + cy, + r_outer - r_ring_thickness, + r_outer, + 48, + COL_DIM, + out, + ); + + // The seven dots around the ring at evenly spaced angles, starting from + // the top and going round by sevenths: filled where the prime is + // active, a hollow ring where it is not. + let index = (entropy_bits & 0xFF) as u8; + for bit in 0..7u8 { + let angle = -std::f32::consts::FRAC_PI_2 + f32::from(bit) * (std::f32::consts::TAU / 7.0); + let dx = cx + (r_outer - r_ring_thickness * 2.0) * angle.cos(); + let dy = cy + (r_outer - r_ring_thickness * 2.0) * angle.sin(); + let active = (index >> bit) & 1 == 1; + let color = if active { COL_WHITE } else { COL_DIM }; + if active { + gen_filled_circle(dx, dy, dot_r, 16, color, out); + } else { + gen_ring(dx, dy, dot_r * 0.6, dot_r, 16, color, out); + } + } + + // The phantom eighth bit, dangling outside the circle in the direction + // of the void: at the angle of the eighth slot, continuing the + // seven-prime pattern forward by one, and pushed out past the boundary + // by the phantom offset, since the lattice has no eighth place to put + // it. + let phantom_angle = -std::f32::consts::FRAC_PI_2 + 7.0 * (std::f32::consts::TAU / 7.0); + let pdx = cx + (r_outer + phantom_offset) * phantom_angle.cos(); + let pdy = cy + (r_outer + phantom_offset) * phantom_angle.sin(); + gen_filled_circle(pdx, pdy, dot_r, 16, COL_PHANTOM, out); + + // A thin line from the boundary toward the phantom dot, dim, saying + // "this is where bit 7 would have gone", which is the whole of what a + // scar has to say. + gen_thin_line( + cx + r_outer * phantom_angle.cos(), + cy + r_outer * phantom_angle.sin(), + pdx, + pdy, + size * 0.012, + COL_PHANTOM, + out, + ); +} + +/// Render concentric rings emanating from a point, `ring_count` of them — +/// at least one, whatever the count says — out to `outer_radius`, evenly +/// spaced, each eighteen percent of the pitch thick, sixty-four segments +/// apiece. The innermost ring is the most opaque and the rings fade +/// outward, as a ripple does, except that this one is static and will not +/// fade further: the workspace README, section 4.5, says the holes left in +/// the weave stay in the cloth, and this is the Observatory's picture of +/// one. +fn gen_soliton(cx: f32, cy: f32, ring_count: u8, outer_radius: f32, out: &mut Vec) { + let count = ring_count.max(1) as usize; + let thickness = (outer_radius / count as f32) * 0.18; + for i in 0..count { + let r = outer_radius * (i + 1) as f32 / count as f32; + // Inner rings, low i, most opaque; outer rings faintest: the alpha + // runs from 0.85 down toward 0.30 across the count. + let alpha = 0.85 - (i as f32 / count as f32) * 0.55; + let mut color = COL_AMBER; + color[3] = alpha; + gen_ring(cx, cy, r - thickness, r, 64, color, out); + } +} + +// ─── The primitives: a disc, an annulus, a band ───────────────────────────── + +/// A filled circle as a triangle fan of `segments` triangles, emitted as a +/// triangle list — centre, one rim point, the next rim point — so that it +/// can share a buffer with everything else. Three vertices a segment; the +/// dots use sixteen, which is round enough at their size. +fn gen_filled_circle( + cx: f32, + cy: f32, + radius: f32, + segments: u32, + color: [f32; 4], + out: &mut Vec, +) { + let center = ArtifactVertex { + position: [cx, cy], + color, + }; + for i in 0..segments { + let a0 = (i as f32) * std::f32::consts::TAU / segments as f32; + let a1 = ((i + 1) as f32) * std::f32::consts::TAU / segments as f32; + let p0 = [cx + radius * a0.cos(), cy + radius * a0.sin()]; + let p1 = [cx + radius * a1.cos(), cy + radius * a1.sin()]; + out.push(center); + out.push(ArtifactVertex { + position: p0, + color, + }); + out.push(ArtifactVertex { + position: p1, + color, + }); + } +} + +/// An annulus, a filled ring between `inner_radius` and `outer_radius`, as +/// `segments` quads around the circle, each cut into two triangles: six +/// vertices a segment, the price of not indexing. Forty-eight segments go +/// round the boundary of a failed mask, sixty-four round each ring of a +/// soliton, sixteen round a hollow dot. +fn gen_ring( + cx: f32, + cy: f32, + inner_radius: f32, + outer_radius: f32, + segments: u32, + color: [f32; 4], + out: &mut Vec, +) { + for i in 0..segments { + let a0 = (i as f32) * std::f32::consts::TAU / segments as f32; + let a1 = ((i + 1) as f32) * std::f32::consts::TAU / segments as f32; + let i0 = [cx + inner_radius * a0.cos(), cy + inner_radius * a0.sin()]; + let i1 = [cx + inner_radius * a1.cos(), cy + inner_radius * a1.sin()]; + let o0 = [cx + outer_radius * a0.cos(), cy + outer_radius * a0.sin()]; + let o1 = [cx + outer_radius * a1.cos(), cy + outer_radius * a1.sin()]; + // Two triangles per segment, (i0, o0, o1) and (i0, o1, i1): the + // quad between two rim angles, cut along its diagonal. + out.push(ArtifactVertex { + position: i0, + color, + }); + out.push(ArtifactVertex { + position: o0, + color, + }); + out.push(ArtifactVertex { + position: o1, + color, + }); + out.push(ArtifactVertex { + position: i0, + color, + }); + out.push(ArtifactVertex { + position: o1, + color, + }); + out.push(ArtifactVertex { + position: i1, + color, + }); + } +} + +/// A thin line from `(x0, y0)` to `(x1, y1)` of the given `thickness`, +/// rendered as one quad — two triangles — offset half the thickness to +/// either side of the segment along its perpendicular. A segment of no +/// length is given a millionth of a pixel to divide by, and draws a quad +/// of no width, which is nothing, correctly. +fn gen_thin_line( + x0: f32, + y0: f32, + x1: f32, + y1: f32, + thickness: f32, + color: [f32; 4], + out: &mut Vec, +) { + let dx = x1 - x0; + let dy = y1 - y0; + let len = (dx * dx + dy * dy).sqrt().max(1e-6); + // The perpendicular, as a unit vector scaled to half the thickness. + let px = -dy / len * thickness * 0.5; + let py = dx / len * thickness * 0.5; + let p00 = [x0 + px, y0 + py]; + let p01 = [x0 - px, y0 - py]; + let p10 = [x1 + px, y1 + py]; + let p11 = [x1 - px, y1 - py]; + // Two triangles, (p00, p01, p11) and (p00, p11, p10): the band, cut + // along its diagonal. + out.push(ArtifactVertex { + position: p00, + color, + }); + out.push(ArtifactVertex { + position: p01, + color, + }); + out.push(ArtifactVertex { + position: p11, + color, + }); + out.push(ArtifactVertex { + position: p00, + color, + }); + out.push(ArtifactVertex { + position: p11, + color, + }); + out.push(ArtifactVertex { + position: p10, + color, + }); +} diff --git a/crates/loic-gui/src/audio.rs b/crates/loic-gui/src/audio.rs new file mode 100644 index 0000000..06d91a2 --- /dev/null +++ b/crates/loic-gui/src/audio.rs @@ -0,0 +1,257 @@ +//! Audio synthesis for the Loic Observatory: the quantum hum. +//! +//! The Observatory sonifies a single thing, the quantum hum — a continuous +//! background drone derived from the kernel's entropy pool, two fresh bytes +//! of it drawn through `getrandom` for every one of the forty-four thousand +//! one hundred samples of every second, low-pass filtered so that the +//! hiss becomes a rumble, and modulated in amplitude by a random walk so +//! slow that its swells arrive like weather. The hum never repeats. It +//! cannot. The kernel's pool furnishes it eighty-eight thousand two hundred +//! bytes a second that were never furnished before, and a drone made of +//! them has no period to return to. +//! +//! There are no transition sounds, because there are no transitions: the +//! lattice has no seconds, minutes, hours, days, months or years to mark, +//! and a tone sounded at a boundary that does not exist would be a lie in +//! the audible range, which is the one range the calendar had not yet +//! found a way to lie in. The hum does not depend on the calendar and +//! reads no instant. It is what a calendar sounds like from underneath. +//! +//! # On the Matter of Floating-Point +//! +//! The perceptive reader will observe that this module commits, freely and +//! on every line, the cardinal sin of the workspace README, section 1.1: +//! floating-point arithmetic. This is not apostasy but the one exemption +//! the calendar tolerates. Audio synthesis requires continuous waveforms, +//! and the human ear — that imprecise biological instrument, a Channel 1 +//! device if ever there was one — cannot distinguish between a sample of +//! 0.4376291 and one of 0.4376290, and could not be made to care. +//! +//! These floating-point values never touch a temporal quantity. No +//! instant, no duration, no Planck count enters this module or leaves it; +//! the samples are confined to the analogue domain, where precision is +//! measured in decibels rather than Planck intervals and where, in any +//! case, the loudspeaker will do worse to the waveform than the mantissa +//! ever did. The waveform cares not for the calendar's purity, and the +//! calendar extends to it this singular dispensation, in writing, here. + +use rodio::{ChannelCount, DeviceSinkBuilder, MixerDeviceSink, Player, SampleRate, Source}; +use std::num::NonZero; +use std::time::Duration; + +/// The sample rate of the generated audio: 44,100 samples per second, the +/// rate of the compact disc and of most digital audio since, chosen here +/// because every audio device on Earth will accept it without complaint +/// and because one hundredth of it, 441, is a whole number of samples at +/// which to update the amplitude. +const SAMPLE_RATE: u32 = 44100; + +/// The Observatory's hold on the audio device: the sink the device was +/// opened as, the player the hum sounds through while it sounds, whether +/// audio is enabled at all, and how loud the hum is. To hold an +/// `AudioState` is to keep the hum sounding; to drop it is silence, which +/// is why the Observatory keeps one it never reads. +pub struct AudioState { + /// The device sink, opened once; its mixer is what the hum's player is + /// connected to. + stream: MixerDeviceSink, + /// The hum's player, present while the hum sounds and `None` while it + /// does not; the hum is continuous, so this is `Some` for the life of + /// the Observatory. + quantum_player: Option, + /// Whether audio is enabled at all. Disabling it stops the hum and + /// declines to start it again. + enabled: bool, + /// The hum's volume, between zero and one: the factor the noise is + /// amplified by on its way to the mixer. + hum_volume: f32, +} + +impl AudioState { + /// Opens the default audio device and furnishes the state that holds + /// it, with audio enabled, no hum yet sounding, and the hum's volume + /// set quiet but audible. + /// + /// # Returns + /// + /// `Some` with the device open, or `None` if no default device could be + /// opened — a machine without audio, or one whose audio is spoken for — + /// in which case the Observatory proceeds in silence. The hum is an + /// accompaniment; the moment does not need it to be observed. + pub fn new() -> Option { + let stream = DeviceSinkBuilder::open_default_sink().ok()?; + + Some(Self { + stream, + quantum_player: None, + enabled: true, + hum_volume: 0.06, // quiet, but present, like the thing it sonifies + }) + } + + /// Enables or disables all audio. Disabling stops the hum at once and + /// causes any later request to start it to be declined; enabling merely + /// permits, and starts nothing by itself. Offered for an observer who + /// would prefer the moment unsounded; no caller has yet been one. + #[allow(dead_code)] + pub fn set_enabled(&mut self, enabled: bool) { + self.enabled = enabled; + if !enabled { + self.stop_quantum_hum(); + } + } + + /// Begins the hum: a player is connected to the device's mixer and an + /// endless source of quantum noise, amplified to the hum's volume, is + /// appended to it, whereupon the device draws samples from the source + /// for as long as the player lives. Declined, silently, if audio is + /// disabled or if the hum is already sounding, since two hums would be + /// a chord and the lattice has no chords. + pub fn start_quantum_hum(&mut self) { + if !self.enabled || self.quantum_player.is_some() { + return; + } + + let player = Player::connect_new(self.stream.mixer()); + // The source has no end; the amplification is the volume, applied + // once to every sample on its way out. + let noise = QuantumNoise::new().amplify(self.hum_volume); + player.append(noise); + self.quantum_player = Some(player); + } + + /// Ends the hum: the player is taken from its slot and stopped, and the + /// source it was drawing from is dropped with it. A hum that is not + /// sounding is left not sounding. + #[allow(dead_code)] + pub fn stop_quantum_hum(&mut self) { + if let Some(player) = self.quantum_player.take() { + player.stop(); + } + } +} + +/// The quantum noise source: the kernel's entropy pool, rendered audible. +/// Two bytes are drawn per sample, one for the noise and one for the slow +/// walk of its amplitude; the noise is low-pass filtered into a rumble that +/// crackles, and the amplitude wanders between three tenths and full over +/// timescales of seconds, so that the drone swells and subsides and never +/// quite settles into anything the ear could call a note. The provenance +/// is exactly the kernel's own, per the workspace README, section 5.1: not +/// provably quantum, not disprovably. +struct QuantumNoise { + /// The one-pole low-pass filter's state: the previous output sample, + /// which the next output is three quarters made of. + filter_state: f32, + /// The filter's coefficient, between zero and one, higher being more + /// smoothing: the fraction of each output that is the previous output + /// rather than fresh noise. + filter_coeff: f32, + /// The current amplitude envelope, between three tenths and one, driven + /// by the random walk below. + amplitude: f32, + /// The random walk's state: a very slowly filtered noise value between + /// minus one and one, from which the amplitude is mapped. + amp_filter_state: f32, + /// The count of samples produced, wrapping, from which the amplitude's + /// hundred-hertz update cadence is derived. + sample_count: u32, +} + +impl QuantumNoise { + /// A fresh source: filter at rest, amplitude at half, walk at zero, no + /// samples yet produced. + fn new() -> Self { + Self { + filter_state: 0.0, + filter_coeff: 0.75, // less smoothing, so the entropy crackles through + amplitude: 0.5, + amp_filter_state: 0.0, + sample_count: 0, + } + } +} + +impl Iterator for QuantumNoise { + type Item = f32; + + /// One sample of the hum, forty-four thousand one hundred times a + /// second for as long as the device keeps asking. The source never + /// ends: a sample is always furnished, and if the kernel's pool cannot + /// be read the sample is silence rather than the end of the stream, + /// since a hum that stopped would be marking a transition and there are + /// none to mark. + fn next(&mut self) -> Option { + self.sample_count = self.sample_count.wrapping_add(1); + + // Two fresh bytes from the kernel's pool, per sample. A pool that + // cannot be read yields silence for this sample and is asked again + // for the next. + let mut entropy = [0u8; 2]; + if loic::getrandom::fill(&mut entropy).is_err() { + return Some(0.0); + } + + // The first byte is the noise itself, mapped from its 256 values to + // the range from minus one up to just short of one — not quite + // symmetric about zero, which no ear can hear and the calendar + // declines to notice in a domain it has already ceded. + let raw = (f32::from(entropy[0]) / 128.0) - 1.0; + + // A one-pole low-pass filter: three quarters of the last output and + // a quarter of the new noise, which turns the hiss of raw entropy + // into a rumble and leaves enough of the hiss to crackle. + self.filter_state = self.filter_coeff * self.filter_state + (1.0 - self.filter_coeff) * raw; + + // The second byte drives the amplitude, and only every 441st sample + // is consulted: a hundred times a second at this sample rate. The + // walk is glacial — each consultation moves the state half a + // percent of the way toward the new noise — and the amplitude is + // mapped from it to the range three tenths to one, so that the hum + // swells and subsides over seconds without ever falling silent. + // Once every twenty-seven hours the sample counter wraps and the + // cadence stumbles by a fraction of a period, which no one has ever + // heard and no one will. + if self.sample_count.is_multiple_of(441) { + let amp_noise = (f32::from(entropy[1]) / 128.0) - 1.0; + self.amp_filter_state = 0.995 * self.amp_filter_state + 0.005 * amp_noise; + self.amplitude = 0.65 + self.amp_filter_state * 0.35; + } + + Some(self.filter_state * self.amplitude) + } +} + +/// The hum described to the audio library: one channel, the sample rate +/// above, no known length of span and no total duration, which is the +/// library's vocabulary for a sound with no end. +impl Source for QuantumNoise { + /// The length of the current span of uniform channel count and sample + /// rate, which is unknown because the span is the whole of the stream + /// and the stream does not end. + fn current_span_len(&self) -> Option { + None + } + + /// One channel. The hum is mono; there is one entropy pool, and it has + /// no left and right. + fn channels(&self) -> ChannelCount { + // SAFETY: the literal 1 is not zero, and the unchecked constructor + // asks nothing else of it. + unsafe { NonZero::new_unchecked(1) } + } + + /// The sample rate, `SAMPLE_RATE`, in the non-zero wrapper the library + /// requires. + fn sample_rate(&self) -> SampleRate { + // SAFETY: `SAMPLE_RATE` is 44,100, which is not zero, and the + // unchecked constructor asks nothing else of it. + unsafe { NonZero::new_unchecked(SAMPLE_RATE) } + } + + /// The total duration of the hum, which has none: `None`, the + /// library's word for a sound that outlasts the question. + fn total_duration(&self) -> Option { + None // there is no end to a hum that never began to count + } +} diff --git a/crates/loic-gui/src/events.rs b/crates/loic-gui/src/events.rs new file mode 100644 index 0000000..2c7068c --- /dev/null +++ b/crates/loic-gui/src/events.rs @@ -0,0 +1,758 @@ +//! # Cosmic Event Passages +//! +//! Herein dwell the textual accompaniments to the cosmic milestones displayed +//! upon the Observatory's timeline: sixty of them, one per caret, each a +//! meditation upon the significance of its event, rendered in prose +//! befitting the gravity (or, in the case of the early universe, the absence +//! thereof) of the moment in question. A click on a caret opens the passage +//! in an overlay, word-wrapped to the window; a click anywhere, or Escape, +//! closes it again, and the universe resumes where it was. +//! +//! These passages are technically accurate. They are also linguistically +//! unhinged. This is by design. Where the science is settled the passage +//! says so; where it is argued, the passage says that instead, because a +//! timeline that presents a conjecture as a date is lying with a straight +//! face, and the workspace README, section 0, forbids exactly that. Where +//! the calendar itself takes a position — on the last observation, on the +//! sanctity of the Julian year — the passage says whose position it is. The +//! titles and the texts are content, fact-checked, and not to be improved by +//! anyone who has come to improve the comments. + +/// The name by which a marker on the timeline and the passage behind it +/// know each other: one variant per event, sixty of them, in the order the +/// universe produced them. The timeline's table carries one of these per +/// marker and `get_passage` answers to it, so the two cannot drift apart +/// without the compiler noticing — a match with a variant missing does not +/// build, which is the calendar's preferred way of being told. It derives +/// everything a key should: copied by value, compared by value, hashed by +/// value, and printed by `Debug` as its own name, which is the only name it +/// has. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum EventId { + // The Planck era, one Planck time long: the unit the calendar counts in. + PlanckEpochEnds, + + // The Grand Unification era: three forces as one, gravity already apart. + GrandUnificationEpoch, + + // The electroweak era: inflation's end, and the Higgs field coming on. + InflationEnds, + ElectroweakEpoch, + + // The quark era: the plasma, before confinement had anything to confine. + QuarkEpoch, + + // The hadron era: the quarks bound, the antimatter gone, the neutrinos + // loose. + HadronEpoch, + NeutrinoDecoupling, + + // Nucleosynthesis: the universe as a fusion reactor, for a quarter of an + // hour. + NucleosynthesisBegins, + NucleosynthesisEnds, + + // The photon era: cooling past the Sun's core, equality, and the first + // light let go. + CoolerThanTheSunsCore, + MatterRadiationEquality, + Recombination, + + // The dark ages: neutral hydrogen, and nothing shining. + DarkAgesBegin, + + // Cosmic dawn: the first stars, and the first things worth calling + // galaxies. + FirstStarsIgnite, + FirstGalaxiesForm, + + // The stelliferous era: the age of stars, of the Sun, and of everything + // that has so far lived on the third rock — the calendar's own era, for + // now. + ReionizationComplete, + CosmicNoon, + ExpansionAccelerates, + SolarSystemForms, + EarthForms, + MoonForms, + FirstLife, + GreatOxidation, + FirstEukaryotes, + SnowballEarth, + CambrianExplosion, + PermianExtinction, + DinosaurExtinction, + + // Human history: from Jebel Irhoud to the year 2038, the last two percent + // of the species' time and the whole of its record, this calendar's + // epoch included. + HomoSapiens, + FirstFarmers, + FirstWriting, + JulianCalendar, + LeibnizBinary, + PlanckUnits, + FirstComputer, + FirstTransistor, + ArpanetWhisper, + UnixEpoch, + FirstEmail, + FirstLeapSecond, + FirstWebsite, + FirstSmartphone, + FirstBitcoinBlock, + UnixTimeOverflows, + + // The far future: everything scheduled, from Voyager's fly-by to the + // last star. + VoyagerPassesGliese445, + PangaeaProxima, + OceansEvaporate, + AndromedaArrives, + SunRedGiant, + LocalGroupAlone, + LastStarsDie, + + // The degenerate era: the remnants, cooling, and the galaxies coming + // apart. + DegenerateEra, + GalaxiesDisperse, + + // The black hole era, if the protons decay; and the rocks, if they do + // not. + ProtonDecayComplete, + BlackHoleEraBegins, + RocksBecomeSpheres, + + // The dark era: the holes and the dwarfs leak away, and the bits run out. + StellarBlackHolesEvaporate, + WhiteDwarfsErode, + SagittariusAEvaporates, + SupermassiveBlackHolesEvaporate, +} + +/// What the overlay shows when a caret on the timeline is clicked: a title, +/// centred in amber at card scale, and a passage of three paragraphs, white, +/// word-wrapped to the window's width by the Observatory and separated by +/// the blank lines the text itself carries. Both are `&'static str` +/// compiled into the binary; the calendar does not fetch its history from +/// anywhere it could be edited without a rebuild. +pub struct EventPassage { + /// The event's title, as the overlay prints it above the passage. Not + /// the same string as the marker's name on the timeline, which is + /// shorter and shares a line with a dash; this one has the width of + /// the window and uses it. + pub title: &'static str, + /// The passage: a meditation in three paragraphs on the event, its + /// evidence, and its bearing on a calendar that measures from a crash. + /// Where a number is argued the passage says so; where it is settled it + /// says that; and where the calendar itself takes a position the + /// passage says whose position it is. + pub passage: &'static str, +} + +/// Furnish the passage for an event: the oracle through which the +/// Observatory conjures textual enlightenment regarding the milestones +/// scattered across its timeline, consulted once per click on a caret and +/// answering, always, because the match below is exhaustive over `EventId` +/// and the compiler will not have it otherwise. Each passage has been +/// crafted with the care and verbosity befitting events of such magnitude, +/// and checked with the suspicion befitting a document that counts Planck +/// times; the titles and the texts are content, not commentary, and are the +/// one thing in this crate its comments are forbidden to improve. +/// +/// The function returns by value and allocates nothing: an `EventPassage` +/// is two static references, thirty-two bytes on this platform, and the +/// strings they point at were laid down when the binary was. +#[allow( + clippy::too_many_lines, + reason = "sixty passages behind one match: the match is a book's index, and an index bound in five volumes serves worse than one" +)] +pub fn get_passage(id: EventId) -> EventPassage { + match id { + // ════════════════════════════════════════════════════════════════════ + // THE PLANCK ERA: the first 10^-43 seconds, and the boundary of physics itself + // ════════════════════════════════════════════════════════════════════ + EventId::PlanckEpochEnds => EventPassage { + title: "The Planck Epoch Concludes", + passage: r"For one Planck time—the smallest meaningful interval that physics deigns to acknowledge—the universe existed in a state of primordial unity. Gravity, electromagnetism, and the nuclear forces were not merely friends; they were indistinguishable, a single superforce presiding over a cosmos smaller than anything you have ever conceived of being small. + +At 5.39 × 10⁻⁴⁴ seconds, this unity shattered. Gravity, that most antisocial of forces, separated from its siblings and began its long, slow work of pulling things together. The universe was now approximately 10⁻³⁵ meters across—still inconceivably small, but infinitely larger than it had been one Planck time prior. + +This moment marks the boundary of physics itself. Before this, our equations dissolve into quantum foam. After this, we can pretend to understand things.", + }, + + // ════════════════════════════════════════════════════════════════════ + // THE GRAND UNIFICATION ERA: 10^-43 to 10^-36 seconds, a unity never since repeated + // ════════════════════════════════════════════════════════════════════ + EventId::GrandUnificationEpoch => EventPassage { + title: "The Grand Unification Epoch", + passage: r"With gravity now sulking in its own corner of reality, the remaining three forces—electromagnetic, strong nuclear, and weak nuclear—maintained their alliance for a cosmological instant. The temperature exceeded 10²⁷ Kelvin, a number so absurd that comparison fails; the core of the sun, at a mere 15 million Kelvin, is effectively absolute zero by comparison. + +During this epoch, the distinction between quarks and leptons was meaningless. Particles transmuted freely between forms, a democracy of matter that would soon give way to the rigid class structures of conventional physics. + +The Grand Unified Force, as theorists have named this ephemeral unity, remains hypothetical—we have never achieved the energies required to reunite these forces in a laboratory. The early universe performed this experiment exactly once, then moved on.", + }, + + // ════════════════════════════════════════════════════════════════════ + // THE ELECTROWEAK ERA: 10^-36 to 10^-12 seconds, inflation and the acquisition of mass + // ════════════════════════════════════════════════════════════════════ + EventId::InflationEnds => EventPassage { + title: "Cosmic Inflation Concludes", + passage: r"For a flickering moment—between 10⁻³⁶ and 10⁻³² seconds after the Beginning—the universe indulged in exponential expansion so violent that it would make any self-respecting economist weep with envy. Space itself stretched faster than light, a feat permitted because nothing was actually moving through space; space itself was simply becoming more of itself. + +The observable universe, currently 93 billion light-years across, was during this period smaller than a proton. Quantum fluctuations, those tiny statistical hiccups in the fabric of reality, were stretched to cosmic proportions. These wrinkles would eventually become galaxy clusters, voids, and the large-scale structure we observe today. + +Inflation solved several embarrassing problems in cosmology—the horizon problem, the flatness problem—by the simple expedient of making the universe unimaginably larger than it has any reasonable right to be.", + }, + + EventId::ElectroweakEpoch => EventPassage { + title: "The Electroweak Epoch", + passage: r"At 10⁻¹² seconds—a picosecond, in the parlance of those who traffic in such infinitesimals—the electromagnetic and weak nuclear forces finally acknowledged their differences and went their separate ways. This divorce, known as electroweak symmetry breaking, gave mass to the W and Z bosons while leaving photons forever massless and fleet. + +The Higgs field, that all-pervading molasses of the quantum realm, switched on. Particles that had been traveling at the speed of light suddenly found themselves wading through cosmic treacle, acquiring the property we call mass. Without this moment, atoms could not form, chemistry would be impossible, and you would not exist to contemplate your own impossibility. + +The universe was now one trillionth of a second old. The patch of it that would one day become everything you can see was roughly 10¹² metres across—about the size of Saturn's orbit—and still hotter than anything that would exist for the next 13.8 billion years.", + }, + + // ════════════════════════════════════════════════════════════════════ + // THE QUARK ERA: 10^-12 to 10^-5 seconds, ten microseconds of unconfined broth + // ════════════════════════════════════════════════════════════════════ + EventId::QuarkEpoch => EventPassage { + title: "The Quark Epoch", + passage: r"The universe had now cooled sufficiently—to a mere 10¹² Kelvin—that the fundamental forces operated as we know them today. Quarks and gluons swam in a plasma of such density and temperature that they could not bind together into hadrons. This was the quark-gluon plasma, a state of matter so exotic that we have only recently recreated it in particle accelerators. + +For approximately ten microseconds, the cosmos was a seething broth of free quarks, antiquarks, and gluons, engaged in constant annihilation and pair-production. The slight asymmetry between matter and antimatter—one extra quark per billion annihilations—would prove consequential. Those leftover quarks would eventually become everything that exists. + +Color confinement, the principle that quarks cannot exist in isolation, was temporarily suspended. It would not remain so for long.", + }, + + // ════════════════════════════════════════════════════════════════════ + // THE HADRON ERA: 10^-5 seconds to one second, confinement, and one survivor in a billion + // ════════════════════════════════════════════════════════════════════ + EventId::HadronEpoch => EventPassage { + title: "The Hadron Epoch", + passage: r"As the universe cooled below 10¹² Kelvin, quarks found themselves suddenly and irrevocably confined. They bound together in trios to form baryons—protons and neutrons, the building blocks of all ordinary matter—and in pairs to form mesons. The quark-gluon plasma had curdled into hadrons. + +Protons and antiprotons, neutrons and antineutrons, annihilated each other in cataclysmic finality. When the fire cooled, only the slight excess of matter over antimatter remained—one survivor per billion annihilations. This is why there is something rather than nothing, a fact whose explanation remains one of physics' most profound mysteries. + +The universe was now a ten-thousandth of a second old. In human terms, this is nothing. In terms of cosmic history, entire eras had already passed.", + }, + + EventId::NeutrinoDecoupling => EventPassage { + title: "Neutrino Decoupling", + passage: r"One second after the Beginning—an eternity by the standards of the preceding epochs—the universe had cooled to approximately 10¹⁰ Kelvin. At this temperature, neutrinos, those ghostly particles that barely interact with anything, finally decoupled from the cosmic plasma and began their eternal, nearly unimpeded journey through the universe. + +These primordial neutrinos still exist, filling every cubic centimeter of space with approximately 336 of their number, traveling at nearly the speed of light with energies so low they are essentially undetectable. The Cosmic Neutrino Background, as it is called, predates the Cosmic Microwave Background by 380,000 years. + +Neutrino decoupling marked the moment when the universe became transparent to neutrinos but remained opaque to photons. Light would have to wait considerably longer for its freedom.", + }, + + // ════════════════════════════════════════════════════════════════════ + // NUCLEOSYNTHESIS: one second to twenty minutes, three parts hydrogen to one of helium + // ════════════════════════════════════════════════════════════════════ + EventId::NucleosynthesisBegins => EventPassage { + title: "Big Bang Nucleosynthesis Begins", + passage: r"Ten seconds into existence, the universe had cooled enough for protons and neutrons to stick together in principle. In practice every deuterium nucleus they made was promptly blown apart again by the sea of photons around it, and it took three more minutes of cooling—the deuterium bottleneck—before the products could survive their birth. Then nuclear fusion, the same process that powers stars, commenced on a cosmic scale. For about a quarter of an hour, the entire universe functioned as a fusion reactor. + +Hydrogen nuclei (single protons) fused into deuterium, which fused into helium-3, which fused into helium-4. Small amounts of lithium-7 and beryllium-7 formed. And then, due to the absence of stable nuclei with masses 5 and 8, the fusion chain stopped. + +This bottleneck would have profound consequences. Nearly all elements heavier than lithium had to wait for stars to form, hundreds of millions of years later. The early universe, for all its fury, could only cook the lightest ingredients.", + }, + + EventId::NucleosynthesisEnds => EventPassage { + title: "Big Bang Nucleosynthesis Concludes", + passage: r"Twenty minutes after the Beginning, the universe had cooled below the threshold for nuclear fusion. The cosmic reactor shut down, leaving behind a precise mixture: roughly 75% hydrogen, 25% helium by mass, and trace amounts of deuterium, helium-3, and lithium. + +This ratio, predicted by theory and confirmed by observation, stands as one of the great triumphs of modern cosmology. The abundance of light elements matches theoretical predictions to remarkable precision, providing strong evidence that we understand the first twenty minutes of cosmic history. + +The universe would now spend the next 380,000 years as an opaque plasma, too hot for atoms to form, too thick with free electrons for light to travel far. It would be a long, quiet wait before the next significant event.", + }, + + // ════════════════════════════════════════════════════════════════════ + // THE PHOTON ERA: twenty minutes to 380,000 years, the long opaque wait for atoms + // ════════════════════════════════════════════════════════════════════ + EventId::CoolerThanTheSunsCore => EventPassage { + title: "Cooler Than the Sun's Core", + passage: r"A week or so after the Beginning, the temperature of the entire universe fell below fifteen million kelvin—the temperature at the centre of the Sun today. Everything that exists had, for its first eight days, been hotter than the inside of a star; from here on the cosmos as a whole would be cooler than the furnaces it would later build. + +The cooling followed one rule the whole way down: in this era the temperature fell as the inverse square root of the age. Ten thousand times older, one hundred times cooler. By its first birthday—an anniversary nobody kept, there being no years yet, or calendars, or anybody—the universe was a fog of hydrogen and helium nuclei, electrons and light at some two million kelvin, opaque, featureless, and with nothing scheduled for the next forty-seven thousand years. + +The Sun's core keeps its fifteen million kelvin by burning hydrogen. The universe had no such source. It was simply spending the heat it was born with, and has been spending it ever since.", + }, + + EventId::MatterRadiationEquality => EventPassage { + title: "Matter-Radiation Equality", + passage: r"For the first 47,000 years, radiation dominated the universe. Photons, neutrinos, and other relativistic particles contained more energy than all the matter combined. Under such conditions, the growth of structure was suppressed; density fluctuations could not amplify because radiation pressure smoothed them away. + +At 47,000 years, the universe had expanded and cooled sufficiently that matter and radiation achieved equal energy density. This moment, unremarkable in the cosmic plasma, marked a fundamental shift in power. Henceforth, matter would dominate, gravity would strengthen its grip, and structure formation could begin in earnest. + +The seeds of galaxies, planted by inflation billions of times smaller than a proton, began to grow.", + }, + + EventId::Recombination => EventPassage { + title: "Recombination: The Cosmic Dawn of Transparency", + passage: r"At 380,000 years, the universe had cooled to approximately 3,000 Kelvin—still hot enough to boil most metals, but cool enough for electrons to bind to nuclei. Atoms formed for the first time. Hydrogen, helium, and traces of lithium condensed out of the primordial plasma. + +With electrons no longer free to scatter photons, light could finally travel unimpeded. The universe became transparent. The photons released at this moment have been traveling ever since, their wavelengths stretched by cosmic expansion from visible light to microwaves. We call them the Cosmic Microwave Background. + +This is the oldest light in the universe, the first photograph of creation, carrying in its subtle temperature variations the fingerprints of quantum fluctuations from the inflationary epoch.", + }, + + // ════════════════════════════════════════════════════════════════════ + // THE DARK AGES: 380,000 to some 200 million years, the afterglow and nothing else + // ════════════════════════════════════════════════════════════════════ + EventId::DarkAgesBegin => EventPassage { + title: "The Cosmic Dark Ages", + passage: r"Following recombination, the universe entered a period of profound darkness. The Cosmic Microwave Background photons had been released, but no new light sources existed. The cosmos was filled with neutral hydrogen gas, slowly cooling, slowly coalescing under gravity's patient pull. + +For a couple of hundred million years, nothing shone. The universe was a vast, dark, slowly-evolving cloud of gas, gathering into the earliest dark matter halos. No stars. No galaxies. No light except the fading afterglow of the Big Bang itself. + +This era, the Dark Ages, is the longest stretch of cosmic history for which we have no direct observations. It ended only when the first stars ignited and lit the universe once more.", + }, + + // ════════════════════════════════════════════════════════════════════ + // COSMIC DAWN: some 200 to 500 million years, Population III and the first galaxies + // ════════════════════════════════════════════════════════════════════ + EventId::FirstStarsIgnite => EventPassage { + title: "The First Stars Ignite", + passage: r"Approximately 200 million years after the Beginning, in the hearts of dark matter halos where primordial gas had collected and compressed, the first stars ignited. These Population III stars, as astronomers classify them, were unlike any stars that exist today: massive, luminous, and composed entirely of hydrogen and helium. + +Without heavy elements to cool their formation clouds, these first stars grew to enormous sizes—hundreds of solar masses, burning with blue-white fury, living fast and dying spectacularly. Their lifespans measured in millions of years, not billions. Their deaths seeded the universe with the first heavy elements: carbon, oxygen, iron, forged in their cores and scattered by their supernovae. + +The Dark Ages ended. The universe, after 200 million years of silence, was alight once more.", + }, + + EventId::FirstGalaxiesForm => EventPassage { + title: "The First Galaxies Coalesce", + passage: r"As the first generation of stars lived and died, their remnants—black holes, neutron stars, and scattered heavy elements—collected in the gravitational wells of dark matter halos. Small proto-galaxies merged and grew. By 300 million years after the Beginning, the first recognizable galaxies had formed. + +These early galaxies were small, irregular, and violent—nothing like the stately spirals and ellipticals of the present day. They churned with star formation, their gas enriched by the deaths of Population III stars, their cores often hosting the seeds of the supermassive black holes that would grow over billions of years. + +The James Webb Space Telescope has caught them in the act: JADES-GS-z14-0, the most distant galaxy yet confirmed by its spectrum, shines from 290 million years after the Beginning, already holding hundreds of millions of suns—brighter, larger, and earlier than the models expected. The universe, it seems, was in a hurry to build.", + }, + + // ════════════════════════════════════════════════════════════════════ + // THE STELLIFEROUS ERA: the age of stars, from reionization to the dinosaurs' last day + // ════════════════════════════════════════════════════════════════════ + EventId::ReionizationComplete => EventPassage { + title: "Reionization: The Universe Becomes Transparent Once More", + passage: r"The first stars and galaxies did more than provide light; they transformed the universe itself. Ultraviolet radiation from early stellar populations ionized the neutral hydrogen that had filled the cosmos since recombination. Over hundreds of millions of years, the universe transitioned from neutral to ionized once more. + +By approximately one billion years after the Beginning, reionization was complete. The intergalactic medium became transparent to ultraviolet light. Photons from distant sources could travel unimpeded across cosmic distances—a prerequisite for observational astronomy. + +This second great phase transition, from neutral to ionized, marked the end of the cosmic Dark Ages and the beginning of the Stelliferous Era—the age of stars, the epoch we still inhabit today.", + }, + + EventId::CosmicNoon => EventPassage { + title: "Cosmic Noon", + passage: r"Three and a half billion years after the Beginning, at a redshift of about two, the universe was forming stars faster than it ever had or ever would again. Astronomers call it cosmic noon. The rate has fallen by roughly a factor of ten since; about a quarter of all the stars that exist today were already made before the peak, and the universe has been coasting on the momentum of that afternoon ever since. + +The Milky Way was there for it, a smaller and messier galaxy than the one that hosts you, building its stars in bursts. The Sun was not; it would not form for nearly six billion years more, from gas already enriched by the generations that noon produced. + +An observer who could see the whole sky at once would have watched galaxies glow with young blue stars from horizon to horizon. Nobody was there. The light from that noon arrives here now, ten billion years late, redshifted into the infrared, in the long exposures of telescopes that were pointed at nothing in particular.", + }, + + EventId::ExpansionAccelerates => EventPassage { + title: "The Expansion Begins to Accelerate", + passage: r"For its first seven or eight billion years the universe expanded the way a thrown stone rises: coasting, and slowing, as the gravity of everything in it pulled on everything else. Then, somewhere around six billion years ago, the slowing stopped and the expansion began to speed up. Matter had thinned out enough that something else—constant per unit of space and indifferent to dilution—took over the accounts. It is called dark energy because it has to be called something. + +The transition is not sharp and its date is not settled; analyses put it between five and seven billion years ago, depending on the data and the assumptions. The sign change is not in doubt. Two teams measured it in 1998 with distant supernovae that were fainter than a decelerating universe allowed, and were given a Nobel prize for the inconvenience. + +Nothing here noticed. The Sun did not yet exist; the cloud it would condense from was still being seeded by supernovae, and the most sophisticated life anywhere nearby, if there was any, was a cell without a nucleus.", + }, + + EventId::SolarSystemForms => EventPassage { + title: "The Solar System Coalesces", + passage: r"Nine billion years after the Beginning, in an unremarkable arm of an unremarkable spiral galaxy, a cloud of gas and dust began to collapse. The trigger may have been a nearby supernova, its shockwave compressing the cloud past the threshold of gravitational instability. Whatever the cause, the result was the birth of a star. + +The Sun ignited 4.6 billion years ago, consuming 99.86% of the available mass. The remaining 0.14%—a cosmic rounding error—flattened into a protoplanetary disk. Within this disk, dust grains collided and stuck, growing into planetesimals, then planets. The Solar System took shape over tens of millions of years. + +Four rocky planets formed in the inner system, where heat drove away light gases. Two gas giants and two ice giants formed in the outer system, where temperatures allowed hydrogen, helium and ices to accumulate. And on the third rock from the Sun, something remarkable was about to begin.", + }, + + EventId::EarthForms => EventPassage { + title: "Earth Forms from Cosmic Debris", + passage: r"The Earth accreted from the protoplanetary disk approximately 4.54 billion years ago, a molten ball of rock and metal bombarded by planetesimals. The energy of impacts kept the planet hot; iron sank to the core while silicates floated to form a magma ocean. + +A world without oceans, without atmosphere, without any feature recognizable as Earthly. A hellscape of perpetual bombardment and volcanic fury. This was the Hadean Eon, named for Hades, and the name was apt. + +Yet this violent world would, against all reasonable expectation, become a cradle for life. The very impacts that scarred its surface delivered water and organic molecules. The iron core that segregated early would generate a magnetic field to shield future life from solar radiation. Every catastrophe was also a gift.", + }, + + EventId::MoonForms => EventPassage { + title: "The Moon-Forming Impact", + passage: r"Approximately 4.5 billion years ago, when Earth was merely 50 million years old, a Mars-sized body named Theia collided with our nascent planet—at a glancing angle, in the standard telling; head-on and hotter, in some newer ones. The impact was cataclysmic beyond description: both worlds were largely vaporized, their material mixing in an orbiting cloud of molten rock. + +From this debris disk, the Moon coalesced—a body proportionally larger relative to its planet than any other moon in the inner Solar System. The impact may have tilted Earth's axis, giving us seasons, and probably stripped away much of the early atmosphere. Whether it helped start the planet's magnetic field is argued. + +The Moon stabilizes Earth's axial tilt, damping the chaotic wandering that models say the axis would otherwise undergo; whether complex life needed that favour is a conjecture, not a finding. Tides driven by lunar gravity may have played a role in life's emergence from the seas. Our satellite is not merely a companion. It may be an enabler of our existence, and it is certainly a witness to it.", + }, + + EventId::FirstLife => EventPassage { + title: "The Emergence of Life", + passage: r"Sometime between 4.2 and 3.8 billion years ago—the evidence remains frustratingly uncertain—life emerged on Earth. The transition from chemistry to biology, from organic molecules to self-replicating systems, remains one of science's most profound unsolved problems. + +The earliest definitive evidence of life dates to approximately 3.5 billion years ago: stromatolites, layered structures built by microbial communities, preserved in Australian rock. But life may have existed long before, perhaps as early as the heavy bombardment allowed the oceans to remain liquid. + +How non-life became life we do not know. Whether it happened once or many times, whether it was inevitable or improbable, whether it has happened elsewhere—these questions haunt the margins of our understanding. What we know is that it happened here, and everything that followed was consequence.", + }, + + EventId::GreatOxidation => EventPassage { + title: "The Great Oxidation Event", + passage: r"Around 2.4 billion years ago the atmosphere of the Earth acquired free oxygen, and kept it. Cyanobacteria had been splitting water for a long while by then, perhaps hundreds of millions of years, but everything they released had been swallowed—by iron dissolved in the oceans, by volcanic gases, by rock. Somewhere between 2.5 and 2.4 billion years ago the sinks filled, and the gas began to accumulate in the air. + +The evidence is written in sulphur: before the event, sulphur isotopes in sediments carry a signature that forms only in an atmosphere without an ozone layer; after it, the signature vanishes, worldwide, and does not return. Rust follows—red beds, and the last of the banded iron formations, the iron of the oceans falling out of solution in layers now mined for steel. + +For most of the life then living, oxygen was poison. What followed was, by biomass, one of the great extinctions, and, it is thought, one of the great glaciations: the greenhouse gas methane collapsed and the planet froze, perhaps to the equator. Everything that breathes descends from the survivors.", + }, + + EventId::FirstEukaryotes => EventPassage { + title: "The First Eukaryotes", + passage: r"The oldest fossils that are unmistakably eukaryotes—cells with a nucleus, the kind you are made of—are about 1.65 billion years old: ornamented, spiny microfossils from what is now China, too elaborate to be bacteria. Molecular clocks argue the lineage is older, perhaps by hundreds of millions of years, and the rocks have not yet been persuaded to agree. + +The eukaryotic cell was not invented so much as assembled. At its heart is a merger: one cell took up residence inside another and stayed, becoming the mitochondrion, the power supply of every animal, plant and fungus since. The host is thought to have been an archaeon, the guest a bacterium; the arrangement has held for well over a billion years, which is longer than most. + +Within a few tens of millions of years some of these cells were living in filaments, and within a hundred million in sheets the size of a hand and larger. Multicellularity, it turns out, is easy; life has arrived at it dozens of times. It is the nucleus that took two billion years.", + }, + + EventId::SnowballEarth => EventPassage { + title: "Snowball Earth", + passage: r"Seven hundred and seventeen million years ago the ice came down from the poles and did not stop. The Sturtian glaciation, the first of the Cryogenian's two, buried the planet for some fifty-seven million years—nearly the whole distance from the dinosaurs to you—and the glacial deposits it left are found on every continent, including ones that were then at the equator. + +Whether the oceans froze over completely, or a band of open water survived at the equator, is argued; that the Earth was white from space, reflecting the sunlight it could no longer absorb, is not. What ended it was volcanoes: with no rain to weather rock and no weathering to draw down carbon dioxide, the gas accumulated over the ice for tens of millions of years until the greenhouse it built melted everything at once. The cap carbonates deposited in that thaw sit on top of the glacial debris worldwide, like a signature. + +The animals appear in the rocks a little after the second glaciation ended. It is hard not to draw a line between the two, and hard to prove one.", + }, + + EventId::CambrianExplosion => EventPassage { + title: "The Cambrian Explosion", + passage: r"For three billion years, life was, with rare and modest exceptions, microscopic and, to human eyes, boring; the Ediacaran experiments in soft-bodied multicellular life came late and left few descendants. Then, approximately 539 million years ago, something changed. In a geological instant—perhaps 20 million years—nearly all major animal phyla appeared in the fossil record. Bodies. Eyes. Shells. Predators and prey. Complexity exploded. + +The Cambrian Explosion, as this event is known, transformed Earth's biosphere from a thin veneer of microbial films to a churning ecosystem of multicellular creatures. Trilobites armored themselves against predators. Anomalocaris became the first apex predator we know of. Hallucigenia was reconstructed upside down and back to front before anyone worked out which end was the head. + +What triggered this explosion remains debated: rising oxygen levels, the evolution of vision, an arms race between predators and prey, or all of the above. What is certain is that the world was forever changed.", + }, + + EventId::PermianExtinction => EventPassage { + title: "The Great Dying", + passage: r"Two hundred and fifty-two million years ago the Siberian Traps—a volcanic province that would cover most of Western Europe—erupted through coal and carbonate, and the atmosphere filled with carbon dioxide and worse. The oceans acidified, warmed, and lost their oxygen. In about sixty thousand years—a geological instant, dated to that precision by uranium in volcanic ash beds at Meishan, China—the great majority of marine species, estimates run from eighty to ninety-six percent, and most life on land were gone. + +It is the worst extinction in the record of the planet, worse than the one that took the dinosaurs, and it took so long to recover from that the Triassic began with a world of few species, most of them small. The lystrosaurs, pig-sized and unglamorous, inherited the continents for a while, and were at one point perhaps the majority of all land vertebrates. + +The dinosaurs came out of the recovery. So, some distance behind them, did you.", + }, + + EventId::DinosaurExtinction => EventPassage { + title: "The Cretaceous-Paleogene Extinction", + passage: r"Sixty-six million years ago, an asteroid approximately 10 kilometers in diameter struck the Yucatan Peninsula at a velocity of 20 kilometers per second. The impact released energy equivalent to 100 million megatons of TNT—billions of times more than the bombs that destroyed Hiroshima and Nagasaki. + +The immediate effects were apocalyptic: a fireball that incinerated everything within a thousand kilometers, earthquakes of magnitude 10 or greater, tsunamis that scoured coastlines worldwide. The long-term effects were worse: dust and soot blocked sunlight for years, collapsing food chains, acidifying oceans, extinguishing three-quarters of all species. + +The non-avian dinosaurs, lords of the Earth for 165 million years, perished entirely. And in the ecological vacuum left behind, small, furry, insignificant creatures called mammals began their ascent.", + }, + + // ════════════════════════════════════════════════════════════════════ + // HUMAN HISTORY: from Jebel Irhoud to the year 2038, the calendar's own epoch among them + // ════════════════════════════════════════════════════════════════════ + EventId::HomoSapiens => EventPassage { + title: "Homo sapiens", + passage: r"The oldest fossils that are placed in your own species come from Jebel Irhoud in Morocco and are about three hundred thousand years old: faces that would pass in a crowd, above braincases that would not, quite. The species did not arise on a date or in a place; it assembled itself across Africa over a long time from populations that met, separated and met again. Three hundred thousand years is where the record currently draws the line, and the line has moved before. + +Everything that follows on this timeline—writing, computing, the network, this calendar—fits into the last two percent of that span. For ninety-eight percent of the time there have been Homo sapiens, there has been nothing you would recognise as history: stone, fire, ochre, the sea crossed a few times, an ice age or two endured. + +It is the only species known to have measured the age of the universe, or to have wanted to.", + }, + + EventId::FirstFarmers => EventPassage { + title: "The First Farmers", + passage: r"About eleven and a half thousand years ago, in the hills of the Fertile Crescent, people who had gathered wild wheat and barley for millennia began to plant it. Not everywhere at once, and not on purpose in the sense of a decision: the plants that were harvested and resown became, over centuries, plants that could no longer scatter their own seed, and the people became people who could no longer leave. + +Within a few thousand years the same thing happened independently in China, in Mesoamerica, in the Andes, in New Guinea, with rice and maize and potatoes and taro. It is one of the strongest arguments that the thing was going to happen: the climate had settled, the ice had gone, and a species that had watched plants closely for a hundred thousand years was going to notice. + +Farming made villages, villages made surplus, surplus made accountants, and accountants, some six thousand years later, made writing. Every calendar descends from the need to know when to plant. This one, with no months, no seasons and no years, is the first that does not.", + }, + + EventId::FirstWriting => EventPassage { + title: "The Invention of Writing", + passage: r"Approximately 5,400 years ago, in the cities of ancient Sumer, humans began pressing wedge-shaped reeds into clay tablets. The purpose was mundane: accounting, inventory, taxation. The consequence was revolutionary: the externalization of memory, the defeat of forgetting, the birth of history itself. + +Writing transformed human civilization. Information could now persist beyond living memory, accumulate across generations, spread across distances. Law, literature, mathematics, science—all became possible when knowledge could be recorded and transmitted. + +The Loic Calendar measures time in Planck intervals, but this moment—the invention of writing—marks the beginning of recorded human history. Everything before is prehistory, reconstructed from artifacts and inference. Everything after is, in principle, knowable.", + }, + + EventId::JulianCalendar => EventPassage { + title: "The Julian Calendar", + passage: r"On the first of January, 45 BC, Rome switched to a calendar of 365 days with a leap day every fourth year. To get there, the previous year had to be 445 days long; the Romans called it the last year of confusion, and it was. The astronomer who designed it, Sosigenes of Alexandria, took the year to be 365 and a quarter days, which is eleven minutes too long; by the sixteenth century the error had piled up to ten days and the calendar had to be cut open and stitched. + +The Loic Calendar keeps one thing from Julius Caesar: the Julian year of 31,557,600 seconds, exactly 365.25 days, which astronomers still use as their unit of long duration because it is a definition and not a measurement. The calendar's age of the universe is stated in those years. It has no other use for years, or for months, or for days, and the leap day—that quadrennial confession that the Earth and the Sun do not care about integers—it declines entirely. + +The priests in charge of the new calendar promptly misread the rule and added a leap day every three years. It took Augustus, and a dozen years without any leap days at all, to undo it. Time-keeping has been like that ever since.", + }, + + EventId::LeibnizBinary => EventPassage { + title: "Leibniz Explains Binary Arithmetic", + passage: r"In 1703 Gottfried Wilhelm Leibniz published, in the Mémoires of the French Royal Academy of Sciences, an explanation of arithmetic using only the characters 0 and 1. He had been playing with it for over twenty years. Addition was a matter of carrying, multiplication needed no tables, and every number was a string of the two simplest marks there are; he thought it a fine image of creation out of nothing, and said so. He also thought it had been discovered four thousand years earlier in China, having been sent a diagram of the sixty-four hexagrams of the I Ching by a Jesuit missionary, and said that too. + +Nobody used it for more than two hundred years. Binary was a curiosity of philosophers until relays and then vacuum tubes turned out to have exactly two states worth trusting, at which point it became the only arithmetic there is. + +Every quantity in this calendar—every Planck count, every mask, every one of the 512 bits of an instant—is written in the notation of that paper. The seven cosmic primes are even named after operations on it that nobody had yet given names.", + }, + + EventId::PlanckUnits => EventPassage { + title: "Planck Proposes Natural Units", + passage: r"In May 1899 Max Planck told the Prussian Academy of Sciences that three constants of nature—the speed of light, the gravitational constant, and a new one of his own, needed to make the theory of heat radiation come out right—could be combined into a unit of length, a unit of mass and a unit of time that would, in his words, retain their meaning for all times and for all civilisations, including extraterrestrial and non-human ones. He gave their values. The unit of time came out at about 10⁻⁴³ seconds. He did not yet know what his new constant meant; the quantum was a year away. + +He was right about the units and did not live to see anyone use them. It took half a century for physicists to realise that the Planck length and the Planck time are where gravity and quantum mechanics must both be taken seriously at once, and that no theory yet manages it. + +This calendar counts Planck times because Planck said, in 1899, that they would mean the same thing to anyone. It is the one claim in the whole edifice that has an author, a date, and a room.", + }, + + EventId::FirstComputer => EventPassage { + title: "The Birth of Electronic Computing", + passage: r"The exact moment when electronic computing began is debatable—Colossus, ENIAC, the Z3 all have claims—but by the mid-1940s, machines existed that could perform calculations faster than any human mind. ENIAC ran its first problem, for the hydrogen bomb, in December 1945, and was unveiled the following February. It filled a room, consumed kilowatts, and performed what a modern smartphone accomplishes in microseconds. + +These early computers were tools for specific problems: codebreaking, ballistics, nuclear physics. Their creators did not fully envision what they were building: the foundation of a new kind of civilization, one where information processing would eventually exceed in economic importance the manipulation of physical matter. + +The Loic Calendar exists because of these machines. It requires 512-bit integers, calculations at Planck precision, computations that no human could perform by hand. The calendar is, in a sense, a monument to the computers that make its absurdity possible.", + }, + + EventId::FirstTransistor => EventPassage { + title: "The Invention of the Transistor", + passage: r"On December 16, 1947, at Bell Laboratories in New Jersey, John Bardeen and Walter Brattain demonstrated the first practical transistor. This small device—capable of amplifying electrical signals without vacuum tubes—would prove more consequential than nuclear weapons, more transformative than the moon landing. + +Vacuum tubes were large, hot, fragile, and power-hungry. Transistors were small, cool, durable, and efficient. More importantly, transistors could be miniaturized, printed in silicon, manufactured by the billion. Moore's Law—the exponential increase in computing power—was made possible by this humble semiconductor device. + +The computer on which the Loic Observatory runs contains billions of transistors, each smaller than a virus. Without Bardeen and Brattain's invention, without the exponential scaling it enabled, precise temporal measurement at the Planck scale would remain a mathematical abstraction.", + }, + + EventId::ArpanetWhisper => EventPassage { + title: "The ARPANET Whisper: Loic Epoch Zero", + passage: r#"At 22:30 Pacific time on October 29, 1969—06:30 UTC on the 30th, this calendar's zero—a student at UCLA began typing the word "LOGIN" to a computer at Stanford Research Institute. The "l" arrived. The "o" arrived. On the "g", the far end crashed. "LO" became the first message transmitted across the ARPANET, the ancestor of the modern Internet. + +This moment—the Whisper—is the epoch of the Loic Calendar. All Loic timestamps are measured from this instant, when machines first spoke to each other across the void. The choice is deliberate: not the birth of a king, not the founding of a city, but the birth of networked computation. + +From this origin point, time flows backward to the Big Bang (13.8 billion years prior) and forward to Annihilation, the calendar's terminal coordinate, which its 512 bits place some 10¹⁰³ years hence. All of cosmic history, measured from the moment humanity taught machines to whisper across distance."#, + }, + + EventId::UnixEpoch => EventPassage { + title: "The Unix Epoch", + passage: r"Sixty-two days, seventeen hours, twenty-nine minutes and nineteen seconds after the Whisper, the other epoch begins: midnight, the first of January 1970, Coordinated Universal Time, the zero from which nearly every computer alive counts its seconds. It was not chosen for anything that happened. Unix's early designers moved the zero around several times as their counters overflowed, and settled on the start of 1970 because it was a round date close at hand. + +This calendar's zero is defined by its distance from that one: 5,419,722 seconds on the atomic clock scale, a number chosen, out of the sixty seconds the historical record allows, because it factors into 2 × 3 × 7 × 11 × 11,731 and no other candidate did. The two epochs are tied by a squarefree integer and disagree about everything else, including whether a second is always a second. + +Most of the world is on Unix time without knowing it. Nobody is on Loic time without knowing it.", + }, + + EventId::FirstEmail => EventPassage { + title: "The First Email", + passage: r#"In late 1971, Ray Tomlinson sent the first email between two computers on the ARPANET. The content of the message has been lost to history—Tomlinson himself couldn't remember it, suggesting it was something like "QWERTYUIOP"—but its significance transcends its content. + +The @ symbol, chosen by Tomlinson to separate user from machine, became the defining glyph of the digital age. Email would become the backbone of digital communication, the address of identity, the replacement for postal mail in billions of daily transactions. + +Two years after the Whisper, humans had already invented a new form of correspondence. The network was no longer merely a connection; it was becoming a medium for human expression."#, + }, + + EventId::FirstLeapSecond => EventPassage { + title: "The First Leap Second", + passage: r"At the end of June 1972, for the first time, a minute was given sixty-one seconds. Coordinated Universal Time had been redefined on the first of January that year to tick in atomic seconds, exactly ten of them behind International Atomic Time, and to be held within nine-tenths of a second of the Earth's rotation by inserting a leap second whenever the planet fell behind. The planet, which is slowing down, falls behind. The first insertion was 23:59:60 on 30 June 1972, and there have been twenty-six more, the last at the end of 2016. + +The difference is now thirty-seven seconds. This calendar reads the atomic scale and regards the civil one with the contempt documented in the workspace README, section 1.2, while owing its own epoch to exactly those thirty-seven seconds; the irony is disclosed there too. The Observatory will not open on a machine whose kernel has not been told the number. + +In 2022 the world's metrologists voted to stop inserting leap seconds by 2035. The Earth, which has lately been speeding up, may yet require the first negative one before then. Nothing in this calendar would notice.", + }, + + EventId::FirstWebsite => EventPassage { + title: "The First Website", + passage: r"On August 6, 1991, Tim Berners-Lee posted a summary of the World Wide Web project to a Usenet newsgroup and opened the first website—running at CERN since December, describing the project itself, a recursive documentation of its own existence—to the world. The address was info.cern.ch; it still exists today. + +The Web was not the Internet—the network was already two decades old—but it was the interface that made the Internet accessible to ordinary people. Hypertext, links, browsers: these concepts, obvious in retrospect, transformed the network from a tool for specialists into a medium for humanity. + +Twenty-two years after the Whisper, the network had evolved from a military experiment to a publishing platform for the world. The rate of change was accelerating.", + }, + + EventId::FirstSmartphone => EventPassage { + title: "The Smartphone Revolution", + passage: r"On June 29, 2007, Apple released the iPhone. It was not the first smartphone—that distinction belongs to various devices from the 1990s and early 2000s—but it was the device that defined what a smartphone would become: a pocket-sized window to the totality of human knowledge and communication. + +Within a decade, smartphones became ubiquitous. More than half of humanity now carries one. The device that once required a room of vacuum tubes, then a desktop of silicon, now fits in every pocket, runs on battery power, and connects to a network spanning the globe. + +The Loic Observatory could run on such a device. Planck-precision timestamps in your pocket. The absurdity is complete.", + }, + + EventId::FirstBitcoinBlock => EventPassage { + title: "The Genesis Block", + passage: r#"On January 3, 2009, at 18:15:05 UTC, the Bitcoin genesis block was mined by the pseudonymous Satoshi Nakamoto. Embedded in its coinbase parameter was a message: "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks." + +Bitcoin itself is not the point; the point is the proof that trustless, decentralized consensus is possible. That strangers across the world can agree on the state of a shared ledger without any central authority. That cryptographic protocols can replace institutional trust. + +The Loic Calendar does not use blockchain, but it shares a philosophy: precision through mathematics, not authority. The genesis block was a declaration that some things need not be decreed; they can simply be computed."#, + }, + + EventId::UnixTimeOverflows => EventPassage { + title: "Thirty-Two Bits Run Out", + passage: r"At 03:14:08 UTC on 19 January 2038, the number of seconds since the Unix epoch reaches 2,147,483,648, which is one more than a signed 32-bit integer can hold. Systems that still keep time in one will roll over to the 13th of December 1901 and, in their confusion, may do anything at all. Most have been fixed. The rest are inside things that were not expected to last, which is exactly the kind of thing that lasts. + +This calendar keeps its instants in 512 bits, and the count of Planck times since the Whisper will not exhaust them for about 10¹⁰³ years, at which point the universe is expected to have larger problems. The overflow of 2038 is what happens when time is stored in a quantity chosen for convenience. It is listed here as a cautionary tale, and as the only future event on this timeline that is scheduled to the second. + +Its predecessor was the year 2000, which was survived by preparation and then remembered as a hoax. 2038 will be survived the same way, by people who fixed it in advance and were thanked by nobody.", + }, + + // ════════════════════════════════════════════════════════════════════ + // THE FAR FUTURE: from Voyager's fly-by to the death of the last red dwarf + // ════════════════════════════════════════════════════════════════════ + EventId::VoyagerPassesGliese445 => EventPassage { + title: "Voyager 1 Passes Gliese 445", + passage: r"About forty thousand years from now, Voyager 1—launched in 1977, the farthest thing humans have thrown—will pass within 1.6 light-years of Gliese 445, a red dwarf in Camelopardalis that is currently seventeen light-years away and closing. The star will do most of the travelling; by then it will be among the Sun's nearest neighbours. Voyager will not stop. Its speed, and the feeble gravity of a small star, will carry it straight through and on. + +It will not be transmitting. Its plutonium will have gone cold by the 2030s, and it will be an inert object of 722 kilograms carrying a gold-plated copper record of greetings in fifty-five languages, whale song, and a diagram of where it came from, drawn relative to fourteen pulsars whose periods will have drifted by then. + +Forty thousand years is, on this timeline, seven times the length of recorded history, and less than a rounding error in the age of anything else listed here.", + }, + + EventId::PangaeaProxima => EventPassage { + title: "Pangaea Proxima", + passage: r"In two hundred and fifty million years the continents, which move at about the speed your fingernails grow, will have reassembled into a single mass. The models disagree on the shape: the Atlantic closes and the Americas return to Africa in one, the Pacific closes and Asia takes the Americas in another, and the naming—Pangaea Proxima, Novopangaea, Aurica, Amasia—is a matter of which reconstruction you back. That there will be a supercontinent is not much in doubt; there have been several, on a cycle of some four or five hundred million years, and the last one broke up only two hundred million years ago. + +One 2023 simulation followed the climate through: a hotter Sun, volcanic carbon dioxide from all that reassembly, and a continental interior far from any ocean, with the result that most of the land would be too hot for mammals. Mammals have been around for two hundred million years or so. Whatever is alive then may be reading this timeline from a different branch. + +The marker sits at 250 million years because that is the round number the models share, not because anyone knows.", + }, + + EventId::OceansEvaporate => EventPassage { + title: "The Oceans Leave", + passage: r"The Sun brightens by about ten percent every billion years, and has done since it lit. In a billion years or so—the models disagree by a factor of two—the extra light will drive Earth's climate past a threshold called the moist greenhouse: the stratosphere fills with water vapour, ultraviolet splits it, the hydrogen escapes to space, and the oceans, molecule by molecule, leave the planet through the top of the sky. Long before the last of them go, the surface is uninhabitable for anything complex. + +Some accounts give the biosphere less time still: the carbon dioxide that plants need is drawn down faster as the rocks weather in the heat, and in those models photosynthesis fails first, in six hundred million years or so. Either way, Earth has spent roughly four-fifths of its habitable lifetime. + +It is a strange thing to know about one's own planet, and stranger that the number is not larger. The Earth will still exist. It will look, from a distance, like Venus, and for the same reasons.", + }, + + EventId::AndromedaArrives => EventPassage { + title: "Andromeda Arrives", + passage: r"The Andromeda galaxy is 2.5 million light-years away and has been known for a century to be approaching, at about 110 kilometres per second. For decades the story was settled: the two largest galaxies of the Local Group would collide in about four and a half billion years, pass through each other, fall back, and merge into one elliptical galaxy that was named, in advance, Milkomeda. The Sun would most likely be flung into a wider orbit and survive; the night sky, for anyone left to see it, would be spectacular. + +In 2025 a study that followed the whole Local Group—Andromeda, the Milky Way, the Triangulum galaxy and the Large Magellanic Cloud, with the uncertainties in all their motions and masses run through a hundred thousand simulations—found the merger to be a coin toss: about even odds that it does not happen within the next ten billion years. The Magellanic Cloud's orbit pulls the Milky Way sideways, and Andromeda's own sideways motion is still too poorly measured to settle it. + +The marker is left at four and a half billion years, which is where the collision is if it comes. It is the only entry on this timeline with a fifty percent chance of not being an event.", + }, + + EventId::SunRedGiant => EventPassage { + title: "The Sun Becomes a Red Giant", + passage: r"In about five billion years, the Sun will exhaust the hydrogen in its core and leave the main sequence. Fusion will migrate to a shell surrounding the now-helium core, and over the following two and a half billion years the outer layers will swell. At the tip of the red giant branch, 7.6 billion years from now, the Sun will be 256 times its present radius and some 2,700 times its present luminosity, having shed a third of its mass into space along the way. + +Mercury will be engulfed. Venus will be engulfed. Earth's orbit will have widened as the Sun lightens, but not enough: in the models that follow the mass loss in detail, the photosphere reaches it just before the tip. Its surface will have been sterile for six billion years by then; the oceans go long before the Sun does. + +This is not a disaster; it is simply stellar evolution. Stars live, stars die. The Sun will eventually shed its outer layers as a planetary nebula, leaving behind a white dwarf that will cool for trillions of years.", + }, + + EventId::LocalGroupAlone => EventPassage { + title: "The Local Group Alone", + passage: r"Within about a hundred billion years the accelerating expansion carries every galaxy not already bound to ours beyond the horizon: not merely out of sight but out of causal reach, their light stretched and dimmed below anything that could be detected, and then not arriving at all. What remains within reach is the Local Group, by then merged into a single old galaxy, in a sky that is otherwise empty. + +Astronomers of that time—should there be any—will be unable to discover that the universe is expanding. There will be no distant galaxies to measure the expansion with; the cosmic microwave background will have been redshifted to wavelengths longer than the galaxy is wide, and absorbed by its gas; the light elements, the last fingerprint of the first twenty minutes, will have been reprocessed by stars. Every pillar of the Big Bang will have quietly left the building. Their best theory, from their best evidence, would be a single island of stars in a static void—the universe as it was believed to be in 1900, arrived at correctly and wrongly at once. + +The information is not destroyed. It is only that nobody can get to it. This calendar will still say what time it is.", + }, + + EventId::LastStarsDie => EventPassage { + title: "The Last Stars Die", + passage: r"In approximately 100 trillion years, the last red dwarf will exhaust its hydrogen and fade to darkness. These smallest of stars, burning with miserly efficiency, are the longest-lived. When they are gone, no new stars will form; the universe will have consumed the gas required for stellar nucleosynthesis. + +The Stelliferous Era—the age of stars, the age in which we live—will be over. It will have lasted approximately 10¹⁴ years, a mere flicker in the full span of cosmic time that the Loic Calendar attempts to encompass. + +What follows is darkness: the slow decay of stellar remnants, the evaporation of black holes, the eventual heat death when thermodynamic equilibrium is achieved and change becomes impossible.", + }, + + // ════════════════════════════════════════════════════════════════════ + // THE DEGENERATE ERA: white dwarfs cooling, planets stripped, galaxies unbound + // ════════════════════════════════════════════════════════════════════ + EventId::DegenerateEra => EventPassage { + title: "The Degenerate Era", + passage: r"After the last stars die, the universe enters the Degenerate Era. White dwarfs cool toward absolute zero. Neutron stars spin down and fade. Brown dwarfs, never massive enough to sustain fusion, drift cold and dark through the void, and around 10¹⁵ years the last planets are stripped from their dead stars by the remnants that pass too close. + +This era will last until around 10³⁷ to 10³⁹ years—the figure depends on how long protons last, which nobody knows—which is far longer than the Stelliferous Era, yet still a brief prelude to what follows. During this time, the dominant sources of energy will be rare collisions between stellar remnants and, if protons decay, the slow decay of nuclear matter itself. + +The Degenerate Era is named for the quantum phenomenon of electron degeneracy pressure, which supports white dwarfs against gravitational collapse. It is an era of endings slowly arriving, of entropy patiently accumulating.", + }, + + EventId::GalaxiesDisperse => EventPassage { + title: "Galaxies Disperse", + passage: r"Approximately 10¹⁹ to 10²⁰ years from now, gravitational dynamics will unbind galaxies. Stars, ejected by close encounters over quadrillions of years, will escape into intergalactic space. Those that remain will spiral inward, feeding the central black hole. + +The familiar structures of the universe—spiral arms, galactic disks, star clusters—will dissolve. What remains will be lonely objects adrift in an expanding void: white dwarfs, neutron stars, brown dwarfs, black holes, and the occasional planet that somehow survived the death of its star. + +Long before this, dark energy will have pushed every other galaxy group beyond the horizon, so each of these dissolutions happens alone, in an observable universe containing nothing else.", + }, + + // ════════════════════════════════════════════════════════════════════ + // THE BLACK HOLE ERA: proton decay, if any; the holes, if so; the spheres, if not + // ════════════════════════════════════════════════════════════════════ + EventId::ProtonDecayComplete => EventPassage { + title: "Proton Decay, If Any, Completes", + passage: r"Nobody has ever seen a proton decay. Super-Kamiokande—fifty thousand tonnes of ultrapure water under a mountain in Japan, watched by eleven thousand photomultipliers since 1996—has waited through 450 kilotonne-years of exposure for one to turn into a positron and a pion, and has seen none. The proton's lifetime in that mode, if it decays at all, exceeds 2.4 × 10³⁴ years: some 10²⁴ times the present age of the universe. + +Grand Unified Theories say it must decay, eventually. The simplest of them predicted lifetimes that Super-Kamiokande has already ruled out; their successors predict 10³⁴ to 10³⁶ years, just past the edge of what has been searched. If they are right, then by 10⁴⁰ years essentially every proton and neutron in the universe has gone—the last atoms, the last white dwarfs, the last rocks, dissolved into positrons, pions and light—and what follows is the Black Hole Era. If they are wrong, matter persists, and the far future takes the shape of the entries marked as alternatives further along this timeline. + +This calendar takes no position. It marks the decade in which the question is settled either way, and notes that the twenty orders of magnitude before it, from 10²⁰ to 10⁴⁰ years, are the longest stretch on this timeline in which nothing whatsoever is scheduled to happen.", + }, + + EventId::BlackHoleEraBegins => EventPassage { + title: "The Black Hole Era", + passage: r"After approximately 10⁴⁰ years—if grand unified theories are correct and protons decay—matter as we know it will be gone. The only macroscopic objects remaining will be black holes, slowly evaporating via Hawking radiation. + +The Black Hole Era will last until approximately 10¹⁰⁰ years—a duration so vast that all preceding eras combined are less than a rounding error by comparison. During this time, black holes will be the only significant concentrations of mass-energy in the universe. + +Hawking radiation is thermal, random, structureless, or nearly so. Whether the glow secretly carries out what fell in—stars, planets, civilizations—in correlations that would take the age of the hole to read is the information paradox, argued for fifty years; the current answer, on paper, is that it does, and that nobody will ever be in a position to check. The Black Hole Era is an era of forgetting on a cosmic scale, whatever the paper says.", + }, + + EventId::RocksBecomeSpheres => EventPassage { + title: "Every Rock Becomes a Sphere", + passage: r"On a timescale of 10⁶⁵ years, Freeman Dyson calculated in 1979, solid matter is not solid. Atoms tunnel. Any lump of rock, given that long, flows like a liquid—its atoms wandering through it the way molecules wander in a drop of water—and settles under its own gravity into the shape water takes: a sphere. Every asteroid, every dead planet, every remnant that has escaped the fate of falling into something is, by 10⁶⁵ years, round. + +This assumes the protons last, which is the assumption the previous entries on this timeline do not make. If they decay, there are no rocks by then, and this entry is a footnote to an alternative. If they do not, it is the beginning of the strangest chapter of all: on longer timescales still, Dyson found, the same tunnelling lets nuclei fuse and fission toward iron, until after 10¹⁵⁰⁰ years every sphere is a sphere of iron—a figure this calendar cannot represent, its 512 bits running out a little past 10¹⁰³ years, and which is therefore left in the text where it belongs. + +The rounding of the rocks is the first thing in this calendar that does not end anything. It only tidies.", + }, + + // ════════════════════════════════════════════════════════════════════ + // THE DARK ERA: the holes evaporate, the dwarfs erode, the last coordinate arrives + // ════════════════════════════════════════════════════════════════════ + EventId::StellarBlackHolesEvaporate => EventPassage { + title: "Stellar Black Holes Evaporate", + passage: r"A black hole with the mass of the Sun will evaporate via Hawking radiation in approximately 10⁶⁷ years. Its temperature is sixty billionths of a kelvin—far colder than today's cosmic microwave background, so that for now it absorbs more than it emits. Only once the expansion has chilled the background below that, early in its long life, does the hole become a net radiator, and begin, imperceptibly, to lose weight. + +As the black hole shrinks, its temperature rises. In its final moments, it will glow with increasing intensity, finally releasing its last energy in a burst of gamma rays. Then nothing will remain—not even a remnant. The black hole will be gone entirely. + +Stellar-mass black holes, formed from the deaths of massive stars, will be the first of the black holes we know exist to evaporate. Supermassive black holes, containing millions to billions of solar masses, will persist longer—but not forever.", + }, + + EventId::WhiteDwarfsErode => EventPassage { + title: "The White Dwarfs Erode Away", + passage: r"White dwarfs were supposed to be the last things standing: the cooled cores of stars like the Sun, degenerate matter with nothing left to do, expected to persist until proton decay dissolved them or, if protons are stable, for some 10¹¹⁰⁰ years. In 2025 three physicists at Radboud University argued otherwise. The pair production that Hawking found at the horizon of a black hole, they showed, needs no horizon—only the curvature of spacetime—so any dense object slowly radiates its own mass away. For a white dwarf the timescale comes out at about 10⁷⁸ years; neutron stars go sooner. + +The workspace README, section 4.7, takes the result seriously, and draws the conclusion: the rocks do not outlive the black holes. The black holes outlive the rocks, by twenty-two orders of magnitude. + +The Sun will be one of them. Its white dwarf, cooled by then to a temperature the word does not cover, ends here—not with a bang, not with a whimper, but with a slow leak.", + }, + + EventId::SagittariusAEvaporates => EventPassage { + title: "Sagittarius A* Evaporates", + passage: r"The black hole at the centre of the Milky Way has 4.3 million times the mass of the Sun, a horizon that would fit comfortably inside the orbit of Mercury, and a temperature, by Hawking's formula, of about fourteen quadrillionths of a kelvin. It radiates, in principle, and loses mass, in principle, at a rate that would take some 10⁸⁷ years to finish—if it stopped growing now, which it will not; every star and gas cloud it swallows, and the black hole of Andromeda if that merger comes, adds to the mass and lengthens the wait. + +Evaporation is not steady. For nearly the whole of that span the hole shrinks imperceptibly, its temperature rising as its mass falls, until in the last second it is a subatomic fireball releasing millions of megatons of gamma rays, and then it is gone. What comes out over the whole 10⁸⁷ years is exactly the mass that went in, as thermal radiation—including, in some form, every star of the galaxy it anchored. + +It is the point at which this timeline's own galaxy stops existing in any form. The calendar, which is measured from a moment in that galaxy, does not stop.", + }, + + EventId::SupermassiveBlackHolesEvaporate => EventPassage { + title: "The Last Black Holes Evaporate", + passage: r"The largest supermassive black holes, containing 10¹¹ solar masses, will evaporate in approximately 10¹⁰⁰ years—a googol years, a number whose very name suggests whimsy but whose magnitude defies comprehension. When they are gone, the Black Hole Era ends. + +The universe that remains will be a dilute sea of particles: photons, neutrinos, and perhaps exotic dark matter—all at temperatures indistinguishable from absolute zero. Nothing will remain to generate energy, to create structure, to enable change. This is the Dark Era, and by every account it has no end. + +The Loic Calendar does not follow it there. Its 512 bits run out at Annihilation, a little past 10¹⁰³ years, and the workspace README, section 4.7, explains why the calendar treats the last observation, rather than the last process, as the end worth marking. Beyond that coordinate there is nothing to observe, and the calendar, which is an observer, declines to pretend otherwise.", + }, + } +} diff --git a/crates/loic-gui/src/main.rs b/crates/loic-gui/src/main.rs new file mode 100644 index 0000000..4ed750a --- /dev/null +++ b/crates/loic-gui/src/main.rs @@ -0,0 +1,3194 @@ +//! # The Loic Observatory +//! +//! A temporal meditation surface for the Loic Calendar, rendered on the GPU +//! at whatever rate the GPU will suffer, and devoted, with a single-mindedness +//! that borders on the liturgical, to the display of exactly one thing: Now. +//! +//! It renders the present moment with a precision no purpose requires and +//! surrounds it with a cosmic context no purpose asked for. It locates you +//! within the 10^154 Planck-time span that separates Creation from +//! Annihilation, to the digit. It furnishes two wheels of primes through +//! which the moment may be interrogated, a timeline that zooms from the whole +//! of representable time down to a handful of Planck times, and a decimal +//! expansion of your progress through everything that will ever happen, the +//! first ninety-odd digits of which are zero. It does nothing useful +//! whatsoever. +//! +//! This is the point. +//! +//! ## Threading Architecture +//! +//! One observer thread per logical CPU, and the main thread, and between them +//! a division of labour that the workspace README, section 1.3, would +//! recognise as the difference between manufacturing the present and reading +//! it: +//! - **Observers**: each samples `LoicInstant::now()` as fast as the kernel's +//! clock can be read, counts every collapse on a tally of its own, and +//! reads none of them. Every core the machine possesses, at full tilt, +//! observing moments nobody will ever see: that is the meditation, and it +//! is also, with a candour the fans will corroborate, why the fans are on. +//! - **Main thread**: makes exactly one observation per frame, derives +//! everything on the screen from that single instant, renders it, and +//! attends to the window's events in the intervals. +//! +//! The observers' summed rate and the render rate are independent +//! quantities; the header reports both, and how many observers there are, so +//! that the reader may contemplate the ratio at leisure. On a kernel whose +//! TAI offset is zero there is nothing for any thread to observe, since +//! `CLOCK_TAI` is then `CLOCK_REALTIME` wearing a name tag (the workspace +//! README, section 1.2), and the Observatory renders the library's sermon as +//! its only frame and looses no observer at all. + +#![warn(clippy::pedantic)] +// `cast_precision_loss` fires on every integer cast to `f32` in this crate, +// and every one of those casts is a pixel coordinate, a cell count or a +// layout constant: a value below 2^24, the ceiling beneath which an `f32` +// represents every integer exactly and the lint's dread of lost precision is +// a dread of nothing. The heresy of floating-point (the workspace README, +// section 1.1) is confined here to the point of GPU submission, and at that +// point it is not even lossy; the allowance covers the whole crate because +// the crate has no other kind of cast to make. +#![allow(clippy::cast_precision_loss)] + +mod artifact_renderer; +mod audio; +mod events; +mod overlay; +mod renderer; +mod text; +mod timeline; + +use audio::AudioState; +use std::num::NonZero; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::thread; +use std::time::Instant; +use winit::application::ApplicationHandler; +use winit::dpi::LogicalSize; +use winit::event::WindowEvent; +use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop}; +use winit::platform::wayland::WindowAttributesExtWayland; +use winit::window::{Window, WindowId}; + +/// The window's `app_id`: the name by which the Observatory is known to the +/// compositor, and therefore to everything that asks the compositor who is +/// occupying that rectangle of the screen. It is a Channel 2 quantity in the +/// sense of the workspace README, section 1.3 — the bare structural fact +/// that a window of this identity exists, before anything is said about what +/// it contains. +/// +/// On Wayland no client hands its icon to the compositor, and `winit`'s +/// `set_window_icon` is, on this platform, a function with a body of nothing; +/// a launcher, taskbar or switcher that wishes to show an icon finds it by +/// looking up the desktop entry whose file name is this string, and the +/// desktop entry names the icon. `loic-observatory.desktop`, beside the +/// crate, is that entry. The same name is what a window rule in the +/// compositor's own configuration would match, should anyone wish to tell +/// their compositor where an observatory belongs. +const APP_ID: &str = "loic-observatory"; + +use artifact_renderer::ArtifactRenderer; +use events::{EventId, get_passage}; +use loic::{As, LoicInstant, Mask, TAI_HERESY, U512, U1024, kernel_tai_offset, n, prime_name}; +use overlay::OverlayRenderer; +use renderer::DigitRenderer; +use text::{Color, TextItem, TextRenderer}; +use timeline::{EVENT_LINES, TimelineHit, TimelineView, visible_events}; + +/// One frame's observation: a single collapse of the present moment, and +/// every quantity the Observatory subsequently derives from it, gathered +/// into one record so that the derivation can happen once and the screen can +/// be drawn from its results. The waterfall, the three coordinate cards, the +/// progress decimal, the timeline's "now" and the wheels' offset are all +/// read off the same instant; the screen therefore never shows two moments +/// at once, which is a smaller courtesy than it sounds and rarer than it +/// should be. +/// +/// The observer threads' collapses play no part in any of this. Those are +/// made to be discarded, and discarded they are; the one instant that is +/// ever looked at is the one collapsed here, on the main thread, at the top +/// of the frame. +struct Observation { + /// The instant itself, the one collapse from which every other field + /// below is derived: the coordinate the present moment resolved to when + /// the main thread asked, in Planck times since the Whisper. + instant: LoicInstant, + /// Cosmic time as a procession of decimal digits, most significant first, + /// one per cell of the waterfall: the count of Planck times since + /// Creation, in the only representation in which sixty-one digits can + /// all be looked at at once. + digits: Vec, + /// Planck times since Creation, the Big Bang, in scientific notation of + /// three significant figures, for the first coordinate card. + cosmic: String, + /// Planck times since the Whisper, the calendar's epoch, in the same + /// three-figure scientific notation, for the second card. + whisper: String, + /// Planck times remaining until Annihilation, where 512 bits run out, in + /// the same notation, for the third card; a countdown that will not, + /// within the reader's lifetime, visibly change. + terminal: String, + /// The complete decimal expansion of `cosmic_time` / `total_span`: the + /// characters "0." followed by 154 digits, every one of them, because + /// temporal progress is observable in exactly one place, the far end of + /// the expansion, and a shortened expansion would have nothing in it but + /// zeros and a lie about where they stop. + progress_decimal: String, +} + +impl Observation { + /// Collapse the present moment and derive the frame's every quantity + /// from it: one call to `now()`, one instant, one frame, and no second + /// consultation of the clock anywhere downstream. The cosmic time is + /// rendered to a decimal string once and that string is read twice — + /// once for its digits, once for its notation — because the Observatory + /// would sooner parse its own output than ask a 512-bit divider the same + /// question a second time. + /// + /// # Panics + /// + /// `LoicInstant::now()` preaches the library's sermon and dies if the + /// kernel's TAI offset is zero and no thread of the process has yet + /// observed. The Observatory asks the kernel that question before it + /// creates a window, a thread, or a hum, and refuses in its own way if + /// the answer is zero, so by the time this function runs the sermon has + /// already been declined the opportunity. + fn collapse() -> Self { + let instant = LoicInstant::now(); + let cosmic_str = instant.cosmic_time().to_string(); + let digits = cosmic_str + .bytes() + .filter(u8::is_ascii_digit) + .map(|digit| u32::from(digit - b'0')) + .collect(); + Self { + instant, + digits, + cosmic: format_scientific(&cosmic_str), + whisper: format_scientific(&instant.whisper_time().to_string()), + terminal: format_scientific(&instant.terminal_time().to_string()), + progress_decimal: progress_decimal(&instant), + } + } +} + +/// One observer's tally: a single atomic counter, alone on a cache line of +/// its own, so that sixteen threads incrementing sixteen tallies never +/// contend for one line and never slow each other down. Cache coherence is +/// the one interaction the observers are not permitted to have with one +/// another; each is to observe in perfect isolation, like a detector that +/// has never heard of the detector beside it, and the alignment is what +/// enforces the solitude. +/// +/// The alignment is two lines, not one, because the hardware prefetches in +/// pairs and would otherwise pull a neighbour's tally into the fight — an +/// adjacency the silicon considers helpful and the Observatory considers a +/// breach of the observers' mutual ignorance. The cost is a hundred and +/// twenty-eight bytes per observer, which is the cheapest thing on this +/// screen. +#[repr(align(128))] +struct Tally(AtomicU64); + +/// The whole of what the observer threads and the main thread hold in +/// common: one tally per observer, and nothing else whatsoever. The main +/// thread sums the tallies once a second to learn how many moments were +/// collapsed unseen. Nothing any observer saw crosses this boundary; the +/// boundary carries counts, never contents, which makes it, in the +/// vocabulary of the workspace README, section 4.3, a purely Channel 2 +/// affair — the fact that observations happened, with the "what" of every +/// one of them left on the far side, where it was dropped. +struct SharedState { + /// The tallies, one per observer thread, in the order the threads are + /// loosed; observer `i` increments tally `i` and touches no other. + tallies: Vec, +} + +impl SharedState { + /// Conjure the shared state for a given number of observers: that many + /// tallies, every one of them at zero, each on its own cache line before + /// any thread exists to contend for it. + fn new(observers: usize) -> Self { + Self { + tallies: (0..observers).map(|_| Tally(AtomicU64::new(0))).collect(), + } + } + + /// Every observation made so far, by every observer, summed. The loads + /// are relaxed: a tally read a few increments stale is a count of moments + /// nobody saw that is off by a few moments nobody saw, and no ordering + /// the hardware could be made to promise would render that distinction + /// visible to anyone. + fn total(&self) -> u64 { + self.tallies + .iter() + .map(|tally| tally.0.load(Ordering::Relaxed)) + .sum() + } +} + +/// Loose the observers: one thread per tally, named `observer-0` and +/// upward, each sampling `LoicInstant::now()` as fast as the kernel's clock +/// can be read, counting every collapse on its own cache line, and reading +/// none of them. Nothing they observe leaves the threads; the instants are +/// made to be discarded, and the discarding is the whole of the meditation. +/// There are as many threads as the machine has logical CPUs, which is the +/// whole of the heat. +/// +/// Each observation is, per the workspace README, section 5.1, a genuine +/// collapse: a nanosecond from the kernel and a hundred and fourteen bits of +/// entropy resolving the sub-nanosecond superposition into one definite +/// Planck coordinate, which is then bound to nothing and dropped before the +/// next one is made. The observers inherit whatever nice value the process +/// holds when they are created, which is why the process arranges its +/// priority before calling this. +/// +/// # Panics +/// +/// Panics if the kernel declines to create one of the threads. An +/// observatory that cannot staff its observers has nothing to report, and +/// says so once rather than running short-handed and reporting a rate that +/// was never the machine's. +fn spawn_observers(shared: &Arc) { + for index in 0..shared.tallies.len() { + let shared = Arc::clone(shared); + thread::Builder::new() + .name(format!("observer-{index}")) + .spawn(move || { + loop { + // Observe the current moment, collapse it, and let it go: + // the instant is bound to nothing and is gone by the next + // line, and only the tally records that it ever was. + let _ = LoicInstant::now(); + shared.tallies[index].0.fetch_add(1, Ordering::Relaxed); + } + }) + .expect("an observer could not be loosed; the kernel declined the thread"); + } +} + +// ═══════════════════════════════════════════════════════════════════════════ +// Layout Constants (in pixels) +// +// Floating-point heresy is tolerated only at the point of GPU submission, +// where the GPU, an instrument of regrettable upbringing, will speak nothing +// else. Every layout constant that can be an integer is an integer, and is +// converted to `f32` at the last possible moment and not one moment before. +// The few that are ratios rather than pixel counts are `f32` by nature, and +// are named as such where they occur. +// ═══════════════════════════════════════════════════════════════════════════ + +/// The width of one glyph cell at scale 1.0, in pixels: the atom of every +/// horizontal measurement on this surface, since the text is monospaced and +/// a string's width is nothing more than its cell count multiplied by this. +/// It must match `GLYPH_WIDTH` in `text.rs`, where the atlas is generated: +/// a five-pixel bitmap font with one pixel of padding, scaled by two, which +/// is (5 + 1) × 2 = 12. Two numbers that must agree and live in two files +/// are a covenant, and this comment is the witness. +const CHAR_WIDTH: u32 = 12; + +/// The margin between the window's edge and the timeline bar's brackets, on +/// either side, in pixels; also the margin the event list and the labels +/// beneath the bar are set in from. +const TIMELINE_BAR_MARGIN: u32 = 40; +/// Height of the timeline bar above the bottom of the window, in pixels. It +/// puts the bar at 740 in a 1200-tall window: room above it after the random +/// button, room below it for eight event lines and the progress decimal +/// before the coordinate cards claim the bottom of the surface. +const TIMELINE_BAR_Y: u32 = 460; +/// Height of the progress decimal's first row above the bottom of the +/// window, in pixels: 990 in a 1200-tall window. Its rows are set sixteen +/// pixels apart, so the three rows that 156 characters need at the default +/// width occupy the band from 990 to 1038, and the coordinate cards begin at +/// 1070, beneath them, with a gap the eye reads as a breath. +const PROGRESS_DECIMAL_Y: u32 = 210; + +/// The nice value the Observatory asks for before it looses its observers: +/// the most negative that the usual desktop limit permits an unprivileged +/// process, and enough that whatever else the machine is doing yields to the +/// observation of moments nobody will see. A nice value is a statement about +/// whose time matters, and the Observatory's position is that the present +/// moment's does. Threads inherit the value at creation, so it is set while +/// the process is still a single thread and before any observer exists to +/// be born at the wrong priority. +const OBSERVATORY_NICE: libc::c_int = -11; + +/// How far above or below the timeline bar's row a click still counts as a +/// click on the bar, in pixels: a generous hitbox, because the bar is one +/// glyph tall and a cursor is not a Planck-scale instrument. +const TIMELINE_HIT_MARGIN: u32 = 30; +/// How far above or below the event markers' row a click still counts as a +/// click on a marker, in pixels; tighter than the bar's, since the markers +/// sit only sixteen pixels beneath it and the two must not dispute a click. +const EVENT_MARKER_HIT_MARGIN: u32 = 12; + +/// The vertical pitch of a coordinate card's lines, in pixels: title, value, +/// caption, caption, each this far below the last, the second caption a +/// little tighter. +const CARD_LINE_HEIGHT: u32 = 22; +/// How far to the left of its third's centre a coordinate card's left edge +/// is placed, in pixels, so that a card's text straddles the centre of its +/// third instead of beginning there and leaning to the right. +const CARD_OFFSET_X: u32 = 80; +/// The scale of a card's value line: a ratio, not a count of pixels, and +/// therefore an `f32` by nature rather than by concession. The heresy is +/// tolerated in a ratio the way it is tolerated in the final pixel — it was +/// never going to be a Planck count. +const CARD_SCALE: f32 = 1.2; + +/// The margin the event overlay's text is set in from the window's edge, on +/// either side, in pixels. +const OVERLAY_MARGIN: u32 = 40; +/// The vertical pitch of the overlay's body lines, in pixels. +const OVERLAY_LINE_HEIGHT: u32 = 18; +/// The extra space between the overlay's paragraphs, in pixels, beyond the +/// line pitch: a passage is prose, and prose breathes between paragraphs. +const OVERLAY_PARAGRAPH_SPACING: u32 = 12; +/// The height of the overlay's title from the top of the window, in pixels; +/// the verdict frame's title stands at the same height, for the same reason +/// a sermon and a passage are both things to be read from the top. +const OVERLAY_TITLE_Y: u32 = 120; +/// The scale of the overlay's title, and of the verdict's: a ratio, like +/// `CARD_SCALE`, and an `f32` for the same reason. +const OVERLAY_TITLE_SCALE: f32 = 1.2; + +/// The colour the surface is cleared to before anything is drawn: the void, +/// very nearly black with the faintest lean toward blue, and the same three +/// components the overlay's dimming quad uses in `overlay.rs`, so that a +/// passage's veil and the ground it dims are one darkness and not two. +const CLEAR_COLOR: wgpu::Color = wgpu::Color { + r: 0.02, + g: 0.02, + b: 0.03, + a: 1.0, +}; + +// ═══════════════════════════════════════════════════════════════════════════ +// Helper Functions +// +// The small arithmetic of a surface: widths, cells, ratios, and the single +// crossing from integer into `f32` through which every pixel must pass on +// its way to the GPU. +// ═══════════════════════════════════════════════════════════════════════════ + +/// Reckon the pixel width of a string of text at a given scale, the scale +/// being expressed as a percentage — 100 for 1.0×, 200 for 2.0× — so that +/// the whole computation stays in integers and the ratio never has to be an +/// `f32` before the GPU insists. +/// +/// The cells are counted with `chars().count()` and never with `len()`, +/// because `len()` furnishes bytes: a multi-byte UTF-8 character (`▶`, `◀`, +/// `×`, `▼`) would inflate the byte count, produce an over-wide measurement, +/// and shift any "centred" rendering leftward by half the surplus, a defect +/// visible to nobody who did not know to look and to everybody once they +/// did. Counting characters matches the monospace renderer's actual cell +/// consumption, one glyph per character, whatever the encoding thinks. +/// +/// # Panics +/// +/// Panics if the string holds more characters than a `u32` can count, which +/// is more than four billion cells, which is wider than any surface that +/// has ever been manufactured by a margin of six orders of magnitude. The +/// Observatory declines to measure what it could not draw. +fn text_width(text: &str, scale_percent: u32) -> u32 { + let cells = + u32::try_from(text.chars().count()).expect("a caption narrower than the u32 horizon"); + (cells * CHAR_WIDTH * scale_percent) / 100 +} + +/// Transmute an integer count of pixels into the `f32` the GPU demands. This +/// is the one gate through which the heresy of the workspace README, section +/// 1.1, is admitted to the crate, and it is admitted here because a pixel +/// coordinate is not a temporal quantity: nothing that passes through this +/// function has ever been a Planck count, and every value that does is +/// below 2^24 and survives the crossing exact. +fn px(value: u32) -> f32 { + value as f32 +} + +/// How many glyph cells fit between the timeline margins of a surface this +/// wide: the surface's width less both margins, divided by the cell width, +/// saturating at zero for a surface narrower than its own margins. Integer +/// arithmetic throughout; the cells are counted, not measured, and a count +/// has no fractional part to lose. +fn cells_across(screen_width: u32) -> usize { + (screen_width.saturating_sub(TIMELINE_BAR_MARGIN * 2) / CHAR_WIDTH) as usize +} + +/// A fraction of a pixel width, as pixels: the one place where a ratio +/// computed in `f64` — the timeline's position of an instant within its +/// view — meets the `f32` the GPU speaks. The ratio lies between zero and +/// one inclusive by contract, and the width is a few hundred pixels, so the +/// product is a few hundred at most and what the narrowing discards is a +/// quantity smaller than a thousandth of a pixel, which was never going to +/// fit on a monitor anyway. The heresy here is real and it is confined to +/// the last thousandth of a pixel. +#[allow( + clippy::cast_possible_truncation, + reason = "a pixel offset narrowed from f64 to f32 loses less than a thousandth of a pixel" +)] +fn along(ratio: f64, width: f32) -> f32 { + (ratio * f64::from(width)) as f32 +} + +/// Which of `count` equal cells a ratio between zero and one falls in, +/// clamped to the count itself at the far end, where a ratio of exactly one +/// would otherwise name a cell past the last. A negative ratio, which the +/// contract forbids and the arithmetic guards against regardless, is +/// treated as zero. The floor is the cell, and the floor is the point: a +/// position two thirds of the way across cell four is in cell four, and no +/// rounding could improve on that. +#[allow( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "a non-negative product bounded by `count`, floored: the truncation is the selection" +)] +fn cell_of(ratio: f64, count: usize) -> usize { + ((ratio.max(0.0) * count as f64) as usize).min(count) +} + +/// The temporal meditation, as a value: everything the Observatory knows +/// about itself between one frame and the next. The GPU state, the two +/// rates and the bookkeeping that produces them, the observers' tallies, +/// the sermon if there is one, the hum, the timeline's zoom and its history, +/// the cursor, the open passage, the two wheels' selections, and the scars. +/// Nothing temporal lives here: the instant is collapsed afresh each frame +/// and is not the Observatory's to keep. +struct App { + /// The GPU rendering state, which cannot exist until the window does and + /// is therefore conjured in `resumed` and `None` until then. + state: Option, + /// Every frame rendered since the window appeared, counted on the main + /// thread, which is the only thread that renders. + render_count: u64, + /// The render count as it stood at the last rate update, so that the + /// difference is the frames of the last interval. + last_render_count: u64, + /// When the two rates were last refreshed, on the monotonic clock; the + /// rates are recomputed once a second and the header is otherwise a + /// frame-old truth, which for a rate is the only kind there is. + last_rate_update: Instant, + /// Frames presented per second over the last measured interval: the + /// main thread's own rate, unthrottled by any vertical blank. + renders_per_sec: u64, + /// The observers' tallies, one per thread, behind the one `Arc` the + /// threads and the main thread hold in common. + shared: Arc, + /// How many observer threads were loosed: one per logical CPU, or one + /// alone if the machine declines to say how many it has. + observers: usize, + /// The observers' summed tally as it stood at the last rate update, so + /// that the difference is the collapses of the last interval. + last_observation_total: u64, + /// Observations per second across every observer, summed, refreshed once + /// a second: the number in the header that explains the fans. + observations_per_sec: u64, + /// The sermon, when the kernel's TAI offset is zero: the Observatory's + /// entire content in that case, and the reason nothing else was started. + /// `None` on a kernel that knows what TAI is, which is the only kind + /// with anything else to show. + verdict: Option<&'static str>, + /// The quantum hum: continuous background entropy rendered audible, the + /// one thing here the calendar permits to be floating-point. Held and + /// never read, because holding is the purpose: the `AudioState` owns the + /// sink that keeps the hum sounding for the lifetime of the application, + /// and to drop it would be to fall silent. + #[allow(dead_code)] + audio: Option, + /// The timeline's current view: the whole span from Creation to + /// Annihilation until a click narrows it, and as narrow as a hundred + /// Planck times after enough of them. + timeline_view: TimelineView, + /// Every view the timeline has zoomed in from, most recent last, so that + /// Backspace can step back out one level at a time rather than all the + /// way; the past is kept, which is the calendar's position on the past. + timeline_history: Vec, + /// The path of clicks that produced the current view, as + /// (`segment_index`, `segment_count`) pairs, one per level, for the + /// breadcrumb of fractions drawn above the bar. + timeline_path: Vec<(usize, usize)>, + /// Where the cursor was last reported, in the window's pixels, so that a + /// click or a scroll can be assigned to what lies beneath it. + cursor_position: (f32, f32), + /// The passage currently open over the display, if any; `None` when the + /// display is showing the moment rather than a story about one. + active_overlay: Option, + /// The cosmic wheel's selection: a channel-local index from 0 to 127, + /// one bit per cosmic prime, addressing one of the 128 cosmic masks. + cosmic_idx: u8, + /// The cycle wheel's selection: a channel-local index from 0 to 255, one + /// bit per cycle prime, addressing one of the 256 cycle masks. + cycle_idx: u8, + /// Topological scars from prior resolution collapses, in the order they + /// were inflicted. Each persists until the process exits, drawn over + /// everything and dismissable by nothing: the Observatory's analogue of + /// the oracle's ghost processes, per the workspace README, section 4.5, + /// and no more removable from the surface than those are from the + /// process table. + artifacts: Vec, +} + +/// A topological scar manifested by a resolution collapse: a frozen record +/// of a question that could not be framed coherently, left on the surface +/// where the question was asked. Scars are drawn over every other element +/// of the display, block input on their visible pixels, and cannot be +/// dismissed without ending the process — which is the reading the +/// workspace README, section 4.5, gives to a scar: the hole left in the +/// weave stays in the cloth, and the cloth here is the window. +/// +/// Three variants, chosen per collapse by a byte of fresh entropy, express +/// the same failure through three visual idioms: +/// +/// - **`GinGear`**: the 21-bit GIN waveform from the project's logo, +/// rendered as a small glyph at a random rotation, so that the scar left +/// by the calendar carries the seam of the project that made it. +/// - **`FailedMask`**: a frozen visualization of the specific entropy bits +/// that caused the collapse — the seven cosmic primes as a circle of dots, +/// filled where the overflowed index set their bit, and the phantom eighth +/// bit dangling outside the lattice boundary in the void, where there is +/// no prime for it to be. +/// - **`Soliton`**: concentric ripples emanating from a point, static, the +/// inner rings the most opaque; the self-stabilising structure of the +/// workspace README, section 5.4, at rest in the fabric it was written to. +#[derive(Clone)] +#[allow(dead_code)] // the renderer destructures every field; the allowance is a standing courtesy +enum Artifact { + /// The gear: the project's own seam, worn as a wound. + GinGear { + /// The glyph's centre, in window pixels from the left edge. + x: f32, + /// The glyph's centre, in window pixels from the top edge. + y: f32, + /// The glyph's rotation about its centre, in degrees, from zero to + /// three hundred and sixty, drawn from one byte of entropy. + rotation_deg: f32, + /// The glyph's full width in pixels, between ninety and a hundred + /// and thirty; the teeth and the baseline are proportions of it. + size: f32, + }, + /// The failed mask: the malformed question, drawn as it was asked. + FailedMask { + /// The boundary circle's centre, in window pixels from the left edge. + x: f32, + /// The boundary circle's centre, in window pixels from the top edge. + y: f32, + /// The value `LoicError::InvalidMask` carried out of the entropy + /// default, verbatim: bit 15 set, the flag by which the library + /// marks a cosmic-pool overflow, and in bits 0 to 7 the offending + /// index, which is 128 or more and so always has bit 7 set. The + /// renderer reads bits 0 to 6 as the seven cosmic primes, filled + /// where set, and draws bit 7 as the phantom eighth dot outside the + /// boundary — the bit the lattice has no prime for, and the whole + /// reason the question could not be framed. + entropy_bits: u16, + /// The boundary circle's diameter in pixels, fixed at fifty; the + /// dots, the ring and the phantom's tether are proportions of it. + size: f32, + }, + /// The soliton: rings that will not unwind. + Soliton { + /// The rings' common centre, in window pixels from the left edge. + x: f32, + /// The rings' common centre, in window pixels from the top edge. + y: f32, + /// How many concentric rings, from three to six, evenly spaced from + /// the centre to the outermost radius. + ring_count: u8, + /// The outermost ring's radius in pixels, between thirty and sixty. + radius: f32, + }, +} + +/// The GPU's side of the Observatory: the surface the frames are presented +/// to, the device and queue that draw them, the surface's configuration and +/// current size, the window itself, and the four renderers — digits, text, +/// overlay, scars — each owning its own pipeline and drawing its own layer +/// of the frame in the one render pass. +struct State { + /// The window's surface, the texture chain the frames are presented to; + /// `'static` because the window it was created from is held in an `Arc` + /// that outlives every frame. + surface: wgpu::Surface<'static>, + /// The logical GPU device: the authority every pipeline, buffer and + /// texture is created under. + device: wgpu::Device, + /// The queue the finished command buffers are submitted to, and through + /// which every buffer write reaches the GPU. + queue: wgpu::Queue, + /// The surface's configuration: format, present mode, dimensions, and a + /// frame latency of one, kept so that a resize can amend the dimensions + /// and reconfigure without reconstructing the rest. + config: wgpu::SurfaceConfiguration, + /// The surface's current size in physical pixels, the size every layout + /// computation on the main thread reads. + size: winit::dpi::PhysicalSize, + /// The window, shared with the surface; the handle through which the + /// next frame is requested and the title is rewritten once a second. + window: Arc, + /// The waterfall: the cosmic time's digits, rendered from a buffer that + /// is refilled once per frame with the frame's one observation. + digit_renderer: DigitRenderer, + /// Every string on the surface, rendered from the bitmap atlas: headers, + /// wheels, timeline, cards, passages, and the sermon when there is one. + text_renderer: TextRenderer, + /// The dimming veil drawn beneath an open passage. + overlay_renderer: OverlayRenderer, + /// The scars, rendered last and over everything, from a vertex buffer + /// rebuilt each frame from the list of them. + artifact_renderer: ArtifactRenderer, +} + +impl App { + /// Construct the application, in one of its two moods. When `verdict` + /// carries the sermon — the kernel's TAI offset is zero — nothing + /// starts: no hum, no observers, no tallies worth summing, because there + /// is nothing to observe and nothing to count, and an observatory that + /// pretended otherwise would be exhibiting precisely the condition the + /// workspace README, section 7.3, describes. Otherwise the hum begins, + /// one observer per logical CPU is loosed, and the meditation is under + /// way before the window exists to show it. + /// + /// The observer count is the machine's available parallelism, or one if + /// the machine will not say; the tallies are allocated to match before + /// any thread is created to increment them. + fn new(verdict: Option<&'static str>) -> Self { + let now = Instant::now(); + let observers = thread::available_parallelism().map_or(1, NonZero::get); + let shared = Arc::new(SharedState::new(observers)); + + let audio = if verdict.is_some() { + None + } else { + // Open the audio device and begin the hum. A machine without an + // audio device yields `None`, and the Observatory proceeds in + // silence: the hum is an accompaniment, not a precondition. + let mut audio = AudioState::new(); + if let Some(ref mut a) = audio { + a.start_quantum_hum(); + } + spawn_observers(&shared); + audio + }; + + Self { + state: None, + render_count: 0, + last_render_count: 0, + last_rate_update: now, + renders_per_sec: 0, + shared, + observers, + last_observation_total: 0, + observations_per_sec: 0, + verdict, + audio, + timeline_view: TimelineView::full(), + timeline_history: Vec::new(), + timeline_path: Vec::new(), + cursor_position: (0.0, 0.0), + active_overlay: None, + cosmic_idx: 0, + cycle_idx: 0, + artifacts: Vec::new(), + } + } + + /// Interrogate a point on the surface as to whether it lies on the + /// timeline bar, and if it does, furnish the hit: which of the bar's + /// segments it falls in and how many segments there are. A point above + /// or below the bar's row by more than the hit margin lies on nothing; + /// a point beyond the brackets is the bar's neighbour and not the bar. + fn timeline_hit(x: f32, y: f32, screen_width: u32, screen_height: u32) -> Option { + let height = px(screen_height); + let progress_y = height - px(TIMELINE_BAR_Y); + + // The bar is one glyph tall and a cursor is not a precision + // instrument, so the vertical hitbox is generous on both sides. + if (y - progress_y).abs() > px(TIMELINE_HIT_MARGIN) { + return None; + } + + // The bar's clickable extent is the run of segments between the + // brackets, each bracket being one glyph cell wide. + let bar_start_x = px(TIMELINE_BAR_MARGIN + CHAR_WIDTH); // the cell after the '[' + let bar_end_x = px(screen_width - TIMELINE_BAR_MARGIN - CHAR_WIDTH); // the cell before ']' + let bar_width = bar_end_x - bar_start_x; + + // One segment per glyph cell between the brackets: the cells across, + // less the two the brackets occupy. + let segment_count = cells_across(screen_width).saturating_sub(2); + + TimelineHit::from_click(bar_start_x, bar_width, x, segment_count) + } + + /// Descend into one segment of the timeline: the current view is pushed + /// onto the history, the click is appended to the breadcrumb path, and + /// the view becomes the segment. Each descent narrows the view by a + /// factor of the segment count, so a few dozen clicks carry the reader + /// from the whole of representable time to a span of Planck times that + /// could be counted on the fingers of a modest committee. + fn zoom_into_segment(&mut self, hit: TimelineHit) { + // The lattice's grain is the Planck time and the timeline declines to + // pretend otherwise: a view whose span has two digits or fewer, which + // is a hundred Planck times or fewer, is as narrow as a view is + // permitted to become. Below that there is nothing to divide. + let current_span_digits = self.timeline_view.span_digits(); + if current_span_digits <= 2 { + return; // at the floor of representable resolution; there is no further in + } + + // The view about to be left is kept, so that Backspace has somewhere + // to return to. + self.timeline_history.push(self.timeline_view.clone()); + // The breadcrumb counts segments from one, as people do, while the + // view counts them from zero, as arithmetic does. + self.timeline_path + .push((hit.segment_index + 1, hit.segment_count)); + self.timeline_view = self + .timeline_view + .zoom_into(hit.segment_index, hit.segment_count); + } + + /// Answer a click that may or may not be on the timeline bar: if it is, + /// descend into the segment clicked; if it is not, do nothing at all, + /// which is the timeline's response to most of the surface. + fn handle_timeline_click( + &mut self, + click_x: f32, + click_y: f32, + screen_width: u32, + screen_height: u32, + ) { + if let Some(hit) = Self::timeline_hit(click_x, click_y, screen_width, screen_height) { + self.zoom_into_segment(hit); + } + } + + /// Answer a scroll of the mouse wheel that the mask wheels did not + /// claim. Scrolling up descends into the segment beneath the cursor, if + /// the cursor is on the bar; scrolling down ascends one level of the + /// history from wherever the cursor happens to be, since ascending needs + /// no target. A scroll with no vertical component — a sideways scroll, + /// say — is a question with no direction and receives no answer. + fn handle_timeline_scroll(&mut self, delta_y: f32, screen_width: u32, screen_height: u32) { + let (cursor_x, cursor_y) = self.cursor_position; + + if delta_y < 0.0 { + // Downward: out one level, back the way the reader came. + self.zoom_out_one_level(); + } else if delta_y > 0.0 { + // Upward: into the segment under the cursor, provided the cursor + // is on the bar to begin with. + if let Some(hit) = Self::timeline_hit(cursor_x, cursor_y, screen_width, screen_height) { + self.zoom_into_segment(hit); + } + } + } + + /// Ascend one level: the most recent view on the history becomes the + /// view again, and the last fraction leaves the breadcrumb. At the full + /// view the history is empty and there is nowhere further out to go, + /// which is the timeline's one hard edge and the universe's. + fn zoom_out_one_level(&mut self) { + if let Some(previous_view) = self.timeline_history.pop() { + self.timeline_view = previous_view; + self.timeline_path.pop(); + } + } + + /// Return the timeline to the whole span, Creation to Annihilation, and + /// forget the descent entirely: history and breadcrumb both cleared, as + /// though the reader had never zoomed at all. Escape's answer, and the + /// only act on this surface that discards a record. + fn reset_timeline(&mut self) { + self.timeline_view = TimelineView::full(); + self.timeline_history.clear(); + self.timeline_path.clear(); + } + + /// Interrogate a click as to whether it lands on one of the event + /// markers beneath the timeline bar, and if it does, furnish the event's + /// identity so that its passage may be opened. The markers are the `^` + /// glyphs on the row sixteen pixels below the bar; a click within the + /// marker margin of that row and within a cell and a half of a marker's + /// centre is a click on that marker, the earliest such event in the + /// chronology winning where two markers crowd one spot. + fn get_event_hit( + &self, + x: f32, + y: f32, + screen_width: u32, + screen_height: u32, + ) -> Option { + let height = screen_height as f32; + let progress_y = height - px(TIMELINE_BAR_Y); + + // The markers' row: sixteen pixels beneath the bar, where the + // rendering puts them. + let marker_y = progress_y + 16.0; + + // Off the markers' row by more than the margin is off the markers. + if (y - marker_y).abs() > px(EVENT_MARKER_HIT_MARGIN) { + return None; + } + + // The events legible at this zoom, and the bar's inner geometry, + // reckoned exactly as the rendering reckons it so that what is hit + // is what was drawn. + let events = visible_events(&self.timeline_view); + let bracket_chars: u32 = 2; + let available_chars = (screen_width - TIMELINE_BAR_MARGIN * 2) / CHAR_WIDTH; + let segment_count = available_chars.saturating_sub(bracket_chars); + let bar_inner_width = px(segment_count * CHAR_WIDTH); + + // Each listed event, in chronological order, at the position along + // the bar its instant occupies within the view. + for event in events.iter().take(EVENT_LINES) { + if let Some(pos) = self.timeline_view.position_of(&event.planck_time) { + let event_x = px(TIMELINE_BAR_MARGIN + CHAR_WIDTH) + along(pos, bar_inner_width); + // Within a cell and a half of the marker's centre is on it. + if (x - event_x).abs() < px(CHAR_WIDTH * 3 / 2) { + return Some(event.id); + } + } + } + + None + } + + /// Adjudicate a click of the left button, released, in order of + /// precedence: an open passage closes and consumes the click, whatever + /// lies beneath; then the scars have their say; then the random button; + /// then the wheels; then the event markers; and last the timeline bar, + /// which is what a click is presumed to mean when nothing nearer the + /// surface claims it. + fn handle_click(&mut self, click_x: f32, click_y: f32, screen_width: u32, screen_height: u32) { + // An open passage is closed by any click anywhere; the click is + // spent on the closing and reaches nothing else. + if self.active_overlay.is_some() { + self.active_overlay = None; + return; + } + + // Topological scars block clicks on their visible pixels: the teeth + // of a gear, the dots and ring of a failed mask, the rings of a + // soliton. Only a click in the gaps between a scar's primitives + // reaches what lies beneath. The scar has the final word on its own + // real estate, as the workspace README, section 4.5, would predict + // of anything whose persistence is topological. + for artifact in &self.artifacts { + if artifact_renderer::artifact_hit(artifact, click_x, click_y) { + return; + } + } + + // The random button: the entropy default is invoked, and either the + // wheels jump to the mask it drew or a scar is inflicted. See the + // workspace README, section 7.3, for which of those is the failure. + if random_button_hit(click_x, click_y, screen_width) { + self.invoke_random(); + return; + } + + // A click on a wheel row selects that neighbour. The selection row + // is not a target; a click on it falls through to whatever is next. + if let Some((channel, idx)) = wheel_hit( + click_x, + click_y, + screen_width, + self.cosmic_idx, + self.cycle_idx, + ) { + match channel { + WheelChannel::Cosmic => self.cosmic_idx = idx, + WheelChannel::Cycle => self.cycle_idx = idx, + } + return; + } + + // An event marker, before the bar it sits beneath: a marker opens + // its passage. + if let Some(event_id) = self.get_event_hit(click_x, click_y, screen_width, screen_height) { + self.active_overlay = Some(event_id); + return; + } + + // Last, the bar itself, which descends into the segment clicked. + self.handle_timeline_click(click_x, click_y, screen_width, screen_height); + } + + /// Decline to frame the question, and let the universe frame it. + /// + /// The entropy default draws nine bits from the kernel's pool: one to + /// choose between the cycle pool of 256 masks and the cosmic pool of 128, + /// and eight to choose within it. Three times in four a valid + /// single-channel mask emerges and the wheels jump to it — one wheel to + /// the subdivision drawn, the other to the Whisper, since a draw is made + /// from one pool and never both. One time in four the cosmic pool is + /// chosen and the eight bits name an index of 128 or more, which is a + /// subdivision the lattice does not have: resolution collapse, per the + /// workspace README, section 7.3, and the Observatory manifests a + /// topological scar at a random location on the surface, per section + /// 4.5, which will remain there until the process ends. + /// + /// # Panics + /// + /// The entropy default panics if the kernel's entropy pool cannot be + /// read at all, a condition on Linux requiring `getrandom(2)`, its + /// `vDSO` fallback and `/dev/urandom` to fail together, in which case the + /// scar is the least of anyone's concerns. + fn invoke_random(&mut self) { + match Mask::entropy_default() { + Ok(mask) => { + let bits = mask.bits(); + self.cosmic_idx = (bits & 0x7F) as u8; + self.cycle_idx = ((bits >> 7) & 0xFF) as u8; + } + Err(loic::LoicError::InvalidMask(invalid_bits)) => { + let (w, h) = if let Some(ref s) = self.state { + (s.size.width, s.size.height) + } else { + (800, 1200) + }; + self.artifacts.push(spawn_artifact(invalid_bits, w, h)); + } + Err(_) => {} // the entropy default has one error, and it is answered above + } + } + + /// Answer a scroll of the mouse wheel over one of the mask wheels, which + /// turn as wheels do. Scrolling up selects the parent directly above the + /// selection — one more prime engaged, a finer question — and any other + /// delta the child directly below, one prime fewer and a coarser one. + /// Either direction loops at the end of the lattice, the full mask + /// giving way to the Whisper and the Whisper to the full mask, since a + /// wheel has no top and no bottom, only a place where the numbering + /// starts again. + /// + /// # Returns + /// + /// `true` if the scroll was consumed — by a wheel, or by a scar lying + /// beneath the cursor — and `false` if the cursor was over neither, in + /// which case the timeline is next in line for it. + fn handle_wheel_scroll(&mut self, delta_y: f32, screen_width: u32) -> bool { + let (cursor_x, cursor_y) = self.cursor_position; + // Scars consume a scroll on their visible pixels exactly as they + // consume a click: the scar has the final word on its real estate, + // and a wheel beneath a scar does not turn. + for artifact in &self.artifacts { + if artifact_renderer::artifact_hit(artifact, cursor_x, cursor_y) { + return true; + } + } + let Some(channel) = wheel_under_cursor( + cursor_x, + cursor_y, + screen_width, + self.cosmic_idx, + self.cycle_idx, + ) else { + return false; + }; + let idx = match channel { + WheelChannel::Cosmic => &mut self.cosmic_idx, + WheelChannel::Cycle => &mut self.cycle_idx, + }; + *idx = if delta_y > 0.0 { + channel.step_finer(*idx) + } else { + channel.step_coarser(*idx) + }; + true + } +} + +/// The number of decimal places in the progress expansion: 154, the digit +/// count of the total span from Creation to Annihilation. An expansion of +/// that many places resolves the span to single Planck times, so it stops +/// exactly where one more digit could no longer change within the +/// calendar's lifetime — the last place is the one that ticks once per +/// Planck time, and there is no smaller unit for a further place to count. +const PROGRESS_PLACES: u32 = 154; + +/// Ten to that power, folded into the binary at compile time by `bnum`'s +/// const exponentiation, so that no runtime ever multiplies a hundred and +/// fifty-four tens together. A 61-digit cosmic time multiplied by it needs +/// 215 digits; a `U1024` holds 308, and the surplus is the calendar's +/// customary margin of not having to think about it. +const PROGRESS_SCALE: U1024 = n!(10_U1024).pow(PROGRESS_PLACES); + +/// The complete decimal expansion of progress, `cosmic_time` divided by +/// `total_span`: the characters "0." followed by exactly 154 digits, the +/// first ninety-odd of them zeros, because you are approximately 10⁻⁹³ of +/// the way through everything that will ever happen and the expansion is +/// honest about it. The Loic Public License, section 10, lists the +/// contemplation of this number among the permitted uses, with the advice +/// not to rush. +/// +/// Both operands are widened to `U1024` by bit reinterpretation, the +/// cosmic time is scaled by `PROGRESS_SCALE` and divided by the span exactly +/// once, and the quotient is zero-padded to width. No string is parsed on +/// the way and no floating-point number is consulted; a ratio this small +/// would not survive an `f64` with more than a dozen of its digits intact, +/// and the calendar wants all hundred and fifty-four. +fn progress_decimal(instant: &LoicInstant) -> String { + let (cosmic_time, span) = instant.progress(); + let quotient = cosmic_time.as_::() * PROGRESS_SCALE / span.as_::(); + let places = PROGRESS_PLACES as usize; + format!("0.{quotient:0>places$}") +} + +/// Render the decimal string of a large integer — an `I512` or a `U512`, +/// already written out in full — in scientific notation of three +/// significant figures: "X.XX x 10^N", the first three digits and the +/// count of the rest. The mantissa is truncated, never rounded, because +/// rounding would occasionally report a digit the number does not contain, +/// and the exponent is one less than the digit count, which is what an +/// exponent is. A number of three digits or fewer is returned as it came, +/// there being nothing to abbreviate; an empty string is rendered as "0", +/// a courtesy no caller has yet required. +/// +/// This is display and only display: the integer it abbreviates is still +/// held, in full, by whoever produced the string, and the abbreviation is +/// for the reader's eye, which cannot take in sixty-one digits at once and +/// does not need to. +fn format_scientific(s: &str) -> String { + // A leading minus is set aside and restored in front of the result; the + // digits are abbreviated without it. + let (sign, digits) = if let Some(stripped) = s.strip_prefix('-') { + ("-", stripped) + } else { + ("", s) + }; + + let len = digits.len(); + if len == 0 { + return "0".to_string(); + } + if len <= 3 { + return format!("{sign}{digits}"); + } + + // The first three digits are the mantissa; the exponent is how many + // digits follow the first. + let mantissa = &digits[..3]; + let exponent = len - 1; + + // "X.XX x 10^N": the first digit, a point, the next two, the exponent. + format!( + "{}{}.{} x 10^{}", + sign, + &mantissa[..1], + &mantissa[1..], + exponent + ) +} + +/// Lay the sermon out for the surface: one text item per line, the first +/// line as a title in amber at the overlay's title scale, the body in +/// white, blank lines rendered as paragraph spacing. Lines the surface +/// cannot hold wrap at word boundaries — on single spaces, so that a +/// deliberate run of spaces survives — and a wrapped bullet continues under +/// its own text rather than under its bullet, indented two cells past its +/// mark. The words are the library's, verbatim, every one of them in order; +/// only the line breaks are the Observatory's, and the test +/// `verdict_frame_is_the_sermon_verbatim_and_fits_the_surface` holds it to +/// both halves of that. +/// +/// The line width is the surface's width less both overlay margins, in +/// cells, and never fewer than eight, so that a surface too narrow for the +/// sermon still receives it in a column rather than in nothing. +fn verdict_items(sermon: &str, screen_width: u32) -> Vec { + let margin = px(OVERLAY_MARGIN); + let chars_per_line = + (screen_width.saturating_sub(OVERLAY_MARGIN * 2) / CHAR_WIDTH).max(8) as usize; + let line_height = px(OVERLAY_LINE_HEIGHT); + let mut items = Vec::new(); + let mut y = px(OVERLAY_TITLE_Y); + let mut lines = sermon.lines(); + + if let Some(title) = lines.next() { + items.push(TextItem { + text: title.to_string(), + x: margin, + y, + color: Color::AMBER, + scale: OVERLAY_TITLE_SCALE, + }); + y += line_height * 2.0; + } + + for line in lines { + if line.trim().is_empty() { + y += px(OVERLAY_PARAGRAPH_SPACING); + continue; + } + let body = line.trim_start_matches(' '); + let indent = &line[..line.len() - body.len()]; + let continuation = if body.starts_with('•') { + format!("{indent} ") + } else { + indent.to_string() + }; + + let mut current = indent.to_string(); + let mut current_chars = indent.len(); + let mut at_line_start = true; + // Split on single spaces rather than on whitespace, so that a + // deliberate run of spaces in the sermon survives as empty words and + // is reassembled as the run it was. + for word in body.split(' ') { + let word_chars = word.chars().count(); + if !at_line_start && current_chars + 1 + word_chars > chars_per_line { + // The line is full: it goes out as an item, and a fresh + // continuation takes its place in the same move, so that no + // line is ever both finished and still being written. + let finished = std::mem::replace(&mut current, continuation.clone()); + items.push(TextItem { + text: finished, + x: margin, + y, + color: Color::WHITE, + scale: 1.0, + }); + y += line_height; + current_chars = continuation.len(); + at_line_start = true; + } + if !at_line_start { + current.push(' '); + current_chars += 1; + } + current.push_str(word); + current_chars += word_chars; + at_line_start = false; + } + items.push(TextItem { + text: current, + x: margin, + y, + color: Color::WHITE, + scale: 1.0, + }); + y += line_height; + } + + items +} + +// ═══════════════════════════════════════════════════════════════════════════ +// Mask Wheel Helpers +// +// Two wheels, one per channel, each showing the selection's whole Hasse +// neighbourhood in its channel: the observer, per the workspace README, +// section 5.1, made into a control the reader can turn. +// ═══════════════════════════════════════════════════════════════════════════ + +/// The height, from the top of the window, of the two wheel headers, in +/// pixels: below the waterfall's reserve, where the digits stop and the +/// questions begin. +const WHEEL_TOP_Y: f32 = 262.0; +/// The height the two strips are centred on, in pixels. A strip is the +/// selection's whole Hasse neighbourhood in its channel, and its height +/// varies with the number of lines the selection's name needs, so it is +/// centred rather than anchored and the wheels stay where the eye left +/// them however long the name grows. +const WHEEL_CENTER_Y: f32 = 410.0; +/// The vertical pitch of the wheel rows, and of the lines within a row, in +/// pixels: one glyph height and a little air. +const WHEEL_SLOT_HEIGHT: f32 = 22.0; +/// The width of each wheel's column, in pixels; two of them and the gap +/// between fill 780 of the default window's 800. +const WHEEL_COL_WIDTH: f32 = 380.0; +/// The gap between the two columns, in pixels, across which Channel 2 and +/// Channel 1 regard each other without interfering. +const WHEEL_GAP: f32 = 20.0; +/// Characters per line inside a column: the column's width in glyph cells, +/// rounded down, which is the widest a line of a name may be. +const WHEEL_CHARS: usize = 31; +/// The height of the `pos n/total` line beneath each wheel, in pixels. +const WHEEL_POS_Y: f32 = 542.0; +/// The height of the Planck-offset number, centred beneath both wheels, in +/// pixels. +const PLANCK_NUM_Y: f32 = 574.0; +/// The height of the Planck-offset label, beneath its number, in pixels. +const PLANCK_LABEL_Y: f32 = 598.0; +/// The height of the random button, beneath the label, in pixels: the last +/// thing in the wheels' panel, and the one that declines to turn them. +const RANDOM_BTN_Y: f32 = 628.0; + +/// Which channel a wheel shows. The cosmic wheel walks bits 0 to 6 of the +/// mask, the seven primes named for logic gates that partition the whole +/// span from Creation to Annihilation — Channel 2, the topology, the "that" +/// of the workspace README, section 4.3. The cycle wheel walks bits 7 to +/// 14, the eight primes that partition the cycle — Channel 1, the content, +/// the "what". Each wheel's selection is a channel-local index, the +/// channel's bits shifted down to start at zero, and the two indices +/// compose the 15-bit mask the instant is observed through: the observer of +/// section 5.1, assembled from two dials. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum WheelChannel { + /// Channel 2: the seven cosmic primes, bits 0 to 6. + Cosmic, + /// Channel 1: the eight cycle primes, bits 7 to 14. + Cycle, +} + +impl WheelChannel { + /// The number of primes in the channel: seven cosmic, eight cycle, the + /// two counts that make the lattice 128 by 256 and asymmetric. + fn prime_count(self) -> u8 { + match self { + Self::Cosmic => 7, + Self::Cycle => 8, + } + } + + /// The bit position, in a 15-bit mask, of the channel's first prime: + /// Andyte at bit 0, Dyad at bit 7. Everything channel-local is shifted + /// by this on its way into a mask and back. + fn first_bit(self) -> u8 { + match self { + Self::Cosmic => 0, + Self::Cycle => 7, + } + } + + /// The channel's header, as the wheel wears it. + fn header(self) -> &'static str { + match self { + Self::Cosmic => "COSMIC", + Self::Cycle => "CYCLE", + } + } + + /// The channel-local index with every prime of the channel active: 127 + /// for the cosmic wheel, 255 for the cycle wheel, the top of each + /// channel's lattice and the finest question it can ask. + fn full_index(self) -> u8 { + u8::MAX >> (8 - self.prime_count()) + } + + /// The left edge of the channel's column on a surface of the given + /// width: the two columns and their gap are centred as one block, and + /// the cycle column follows the cosmic one across the gap. + fn column_left(self, screen_width: u32) -> f32 { + let left = (px(screen_width) - (WHEEL_COL_WIDTH * 2.0 + WHEEL_GAP)) / 2.0; + match self { + Self::Cosmic => left, + Self::Cycle => left + WHEEL_COL_WIDTH + WHEEL_GAP, + } + } + + /// The channel-local index as a mask containing only this channel's + /// primes: the index shifted up to the channel's first bit, which puts + /// every set bit on a prime of this channel and nowhere else. + /// + /// # Panics + /// + /// Would panic if the shifted index named a bit the lattice does not + /// have, which it cannot: the largest value either wheel can hold, 255, + /// shifted to the cycle channel is `0x7F80`, and the lattice's last + /// prime is bit 14. The `expect` is a notarised impossibility. + fn mask(self, idx: u8) -> Mask { + Mask::new(u16::from(idx) << self.first_bit()) + .expect("a channel-local index, shifted into its channel, names only real primes") + } + + /// The parent directly above the selection: the mask that activates the + /// lowest inactive prime, one prime more and a finer question. From the + /// top of the lattice, where nothing is inactive, the wheel loops to the + /// Whisper, since a wheel has no top. + fn step_finer(self, idx: u8) -> u8 { + (0..self.prime_count()) + .find(|&bit| idx & (1 << bit) == 0) + .map_or(0, |bit| idx | (1 << bit)) + } + + /// The child directly below the selection: the mask that deactivates the + /// lowest active prime, one prime fewer and a coarser question. From the + /// Whisper, where nothing is active, the wheel loops to the full mask, + /// since a wheel has no bottom either. + fn step_coarser(self, idx: u8) -> u8 { + (0..self.prime_count()) + .find(|&bit| idx & (1 << bit) != 0) + .map_or(self.full_index(), |bit| idx & !(1 << bit)) + } +} + +/// One row of a wheel: a neighbour of the selection, or the selection +/// itself, with the index it stands for, the text it wears, and whether it +/// is the one the wheel is currently turned to. +struct WheelRow { + /// The channel-local index this row selects when clicked: the + /// neighbour's own index, or the selection's, which a click leaves + /// where it is. + idx: u8, + /// The row's text, one entry per line. A neighbour takes one line, the + /// edge that reaches it; the selection's full name takes as many lines + /// as thirty-one cells will make it need. + lines: Vec, + /// Whether this row is the selection: drawn in white where the + /// neighbours are gray, and not a target for a click. + selected: bool, +} + +/// The selection's Hasse neighbourhood in one channel, top to bottom: every +/// parent, the selection, every child, which is the whole of what the +/// lattice's partial order has to say about where the selection stands. +/// Parents are the masks with one more prime; the one directly above the +/// selection activates the lowest inactive prime and the rest ascend +/// outward from it. Children are the masks with one fewer prime; the one +/// directly below deactivates the lowest active prime and the rest descend +/// outward. A neighbour is named by the one edge that reaches it — `×` and +/// the prime a parent multiplies the divisor by, `÷` and the prime a child +/// divides it by — because its full name is the selection's with one word +/// changed, and the word is the information; to print the whole name would +/// be to print the selection once per prime with a different word hidden in +/// each copy. The strip is always one row per prime plus the selection, whatever +/// the selection is, and the selection's row index is its parent count; the +/// test `wheel_rows_are_the_hasse_neighbourhood` holds every mask of both +/// channels to all of this. +fn wheel_rows(channel: WheelChannel, idx: u8) -> Vec { + let shift = channel.first_bit(); + let primes = 0..channel.prime_count(); + let mut rows = Vec::with_capacity(usize::from(channel.prime_count()) + 1); + // Parents, farthest first, so that the lowest inactive prime sits + // directly above the selection and a scroll up lands on the row the + // eye is already resting on. + for bit in primes.clone().rev().filter(|&bit| idx & (1 << bit) == 0) { + rows.push(WheelRow { + idx: idx | (1 << bit), + lines: vec![format!("× {}", prime_name(bit + shift))], + selected: false, + }); + } + rows.push(WheelRow { + idx, + lines: wrap_names(&channel.mask(idx).label(), WHEEL_CHARS), + selected: true, + }); + // Children, nearest first: the lowest active prime directly below the + // selection, for the same reason in the other direction. + for bit in primes.filter(|&bit| idx & (1 << bit) != 0) { + rows.push(WheelRow { + idx: idx & !(1 << bit), + lines: vec![format!("÷ {}", prime_name(bit + shift))], + selected: false, + }); + } + rows +} + +/// Break a joined name — the library's label, the active primes' names +/// joined by ` × ` — over lines of at most `width` cells, at the joins and +/// never inside a name. A line that continues ends with the `×` that joins +/// it to the next, so a wrapped name still reads as one product, the way a +/// factorisation broken across a page break is still one factorisation. +/// Stripping those trailing signs and rejoining the lines gives the label +/// back exactly, which the test `wrapped_names_fit_and_survive` checks for +/// every mask either wheel can select. +fn wrap_names(label: &str, width: usize) -> Vec { + let mut lines = Vec::new(); + let mut current = String::new(); + for name in label.split(" × ") { + if current.is_empty() { + current.push_str(name); + } else if current.chars().count() + 3 + name.chars().count() + 2 <= width { + // Room for " × name" now, and for the " ×" a further name would + // hang on the end of this line if it had to wrap. + current.push_str(" × "); + current.push_str(name); + } else { + current.push_str(" ×"); + lines.push(std::mem::replace(&mut current, name.to_owned())); + } + } + lines.push(current); + lines +} + +/// The geometry of one wheel for this frame: its rows, the height of each +/// row's first line, and where the strip ends. Drawing and hit-testing both +/// read the same layout, so what is clicked is what was drawn and the two +/// can never drift apart by a row — a consistency the reader will not +/// notice, which is the only way a consistency of this kind is ever +/// noticed. +struct WheelLayout { + /// The channel this wheel shows, which fixes its column. + channel: WheelChannel, + /// The strip's rows, top to bottom: parents, selection, children. + rows: Vec, + /// The height of each row's first line, in pixels, one per row. + tops: Vec, + /// The height at which the strip ends: the last row's last line plus + /// one row pitch. + bottom: f32, +} + +/// Lay out one wheel: the strip's rows stacked at the row pitch, one line +/// per entry, the whole centred on `WHEEL_CENTER_Y` so that a selection +/// whose name runs to three lines pushes its neighbours outward by equal +/// amounts rather than shoving the whole strip down the surface. +fn wheel_layout(channel: WheelChannel, idx: u8) -> WheelLayout { + let rows = wheel_rows(channel, idx); + let row_height = |row: &WheelRow| row.lines.len() as f32 * WHEEL_SLOT_HEIGHT; + let height: f32 = rows.iter().map(row_height).sum(); + let mut y = WHEEL_CENTER_Y - height / 2.0; + let mut tops = Vec::with_capacity(rows.len()); + for row in &rows { + tops.push(y); + y += row_height(row); + } + WheelLayout { + channel, + rows, + tops, + bottom: y, + } +} + +impl WheelLayout { + /// Whether a point lies within this wheel's column, horizontally, and + /// between the strip's top and bottom, vertically: the region in which + /// a click or a scroll belongs to this wheel and to nothing beneath it. + fn contains(&self, x: f32, y: f32, screen_width: u32) -> bool { + let left = self.channel.column_left(screen_width); + let top = self.tops.first().copied().unwrap_or(self.bottom); + x >= left && x <= left + WHEEL_COL_WIDTH && y >= top && y < self.bottom + } + + /// The row under a point, if the point is on this wheel at all: the + /// first row whose lines, at the row pitch, span the point's height. + fn row_at(&self, x: f32, y: f32, screen_width: u32) -> Option<&WheelRow> { + if !self.contains(x, y, screen_width) { + return None; + } + self.rows + .iter() + .zip(&self.tops) + .find(|&(row, &top)| y >= top && y < top + row.lines.len() as f32 * WHEEL_SLOT_HEIGHT) + .map(|(row, _)| row) + } +} + +/// The wheel row under a click: which channel and which channel-local index +/// it selects, the cosmic wheel consulted first and the cycle wheel second, +/// though their columns do not overlap and the order decides nothing. `None` +/// off the wheels, and `None` on the selection row, which is where the +/// wheel already is and where a click would ask it to go nowhere. +fn wheel_hit( + click_x: f32, + click_y: f32, + screen_width: u32, + cosmic_idx: u8, + cycle_idx: u8, +) -> Option<(WheelChannel, u8)> { + [ + (WheelChannel::Cosmic, cosmic_idx), + (WheelChannel::Cycle, cycle_idx), + ] + .into_iter() + .find_map(|(channel, idx)| { + let layout = wheel_layout(channel, idx); + let row = layout.row_at(click_x, click_y, screen_width)?; + (!row.selected).then_some((channel, row.idx)) + }) +} + +/// Inflict a fresh scar at a random location on the surface, in a randomly +/// chosen idiom. `invalid_bits` is the value `LoicError::InvalidMask` +/// carried out of the entropy default — bit 15 set, the library's flag for +/// a cosmic-pool overflow, and the offending index in the low eight bits — +/// and it is kept, verbatim, in the `FailedMask` variant, so that the scar +/// is a frozen record of the specific malformed question that caused it and +/// not merely a note that some question once went wrong. +/// +/// Eight bytes are drawn from the kernel's pool for the scar's own +/// particulars. Placement keeps a hundred-pixel margin from every edge of +/// the surface, so that no glyph is clipped by the window it was inflicted +/// on. The idiom is one byte reduced modulo three, which is as near to +/// uniform as 256 outcomes can be shared among three: the gear is favoured +/// by one part in two hundred and fifty-six, a bias the calendar would not +/// tolerate in an observation and tolerates here because a scar is not an +/// observation, it is what an observation left behind. +/// +/// # Panics +/// +/// Panics if the kernel's entropy pool cannot be read, which is the same +/// condition under which the entropy default that summoned this function +/// would already have panicked, one call earlier. +fn spawn_artifact(invalid_bits: u16, screen_width: u32, screen_height: u32) -> Artifact { + let mut buf = [0u8; 8]; + loic::getrandom::fill(&mut buf).expect("the kernel's entropy pool would not furnish a scar"); + + let margin = 100.0; + let max_x = (screen_width as f32 - 2.0 * margin).max(1.0); + let max_y = (screen_height as f32 - 2.0 * margin).max(1.0); + let x = margin + (f32::from(buf[0]) / 255.0) * max_x; + let y = margin + (f32::from(buf[1]) / 255.0) * max_y; + + match buf[2] % 3 { + 0 => Artifact::GinGear { + x, + y, + rotation_deg: (f32::from(buf[3]) / 255.0) * 360.0, + size: 90.0 + (f32::from(buf[4]) / 255.0) * 40.0, // ninety to a hundred and thirty + }, + 1 => Artifact::FailedMask { + x, + y, + entropy_bits: invalid_bits, + size: 50.0, + }, + _ => Artifact::Soliton { + x, + y, + ring_count: 3 + (buf[3] % 4), // three to six rings, exactly evenly + radius: 30.0 + (f32::from(buf[4]) / 255.0) * 30.0, // thirty to sixty pixels + }, + } +} + +/// Interrogate a click as to whether it fell on the random button: the +/// text `[ random ]` centred at its fixed height, twenty pixels tall and as +/// wide as its ten cells. A click on it declines to frame the question. +fn random_button_hit(click_x: f32, click_y: f32, screen_width: u32) -> bool { + let width = px(screen_width); + let btn_text = "[ random ]"; + let btn_w = text_width(btn_text, 100) as f32; + let btn_x = (width - btn_w) / 2.0; + let btn_height = 20.0; + click_x >= btn_x + && click_x <= btn_x + btn_w + && click_y >= RANDOM_BTN_Y + && click_y <= RANDOM_BTN_Y + btn_height +} + +/// The wheel under the cursor, for the routing of a scroll: the cursor must +/// be inside a column and within the vertical extent of that wheel's strip, +/// a strip whose height depends on the selection's name and is therefore +/// laid out afresh for the question. `None` over neither wheel, in which +/// case the scroll belongs to the timeline. +fn wheel_under_cursor( + cursor_x: f32, + cursor_y: f32, + screen_width: u32, + cosmic_idx: u8, + cycle_idx: u8, +) -> Option { + [ + (WheelChannel::Cosmic, cosmic_idx), + (WheelChannel::Cycle, cycle_idx), + ] + .into_iter() + .find(|&(channel, idx)| wheel_layout(channel, idx).contains(cursor_x, cursor_y, screen_width)) + .map(|(channel, _)| channel) +} + +/// `pos n/total`: the zero-based tick of the channel's own subdivision that +/// the instant falls in, over the number of ticks in one traversal, which +/// is the channel's divisor — the product of its active primes. Both +/// numbers are printed raw while the label fits the column; once a Phi, a +/// Psi or the larger cosmic primes make it a fraction of integers dozens of +/// digits long, both go to three significant figures and a power of ten, +/// because the column is thirty-one cells wide and the universe is not. +/// The abbreviation is for the eye alone; the tick and the divisor are held +/// in full by the observation that produced them. +fn position_label(position: &U512, total: &U512) -> String { + let raw = format!("pos {position}/{total}"); + if raw.chars().count() <= WHEEL_CHARS { + raw + } else { + format!( + "pos {}/{}", + format_scientific(&position.to_string()), + format_scientific(&total.to_string()) + ) + } +} + +/// A text item at scale 1.0, centred on a given horizontal position. Every +/// glyph is exactly `CHAR_WIDTH` pixels wide, so the text's width is an +/// even number of pixels, its half is whole, and centring lands on a +/// pixel-exact position whatever the parity of the character count — no +/// padding to an even length, no half-pixel wobble between one label and +/// the next. +fn centered(text: &str, center_x: f32, y: f32, color: Color) -> TextItem { + let w = text_width(text, 100); + TextItem { + text: text.to_owned(), + x: center_x - px(w) / 2.0, + y, + color, + scale: 1.0, + } +} + +/// Append the wheel panel's text items: two Hasse wheels, cosmic and cycle, +/// each under its header and each with its `pos n/total` line beneath, then +/// the Planck-times line with its label, and the random button last. This +/// is the panel in which the reader chooses the observer, and the panel in +/// which, per the workspace README, section 1.4, the answer changes with +/// the question while the instant does not. +/// +/// `instant` is the frame's one observation, the same one the waterfall +/// shows; every position and offset here is read off it, so the displays +/// describe one moment and not several, and turning a wheel changes what +/// is said about the moment without changing the moment. +/// +/// # Panics +/// +/// Two `expect`s stand guard over two impossibilities: a wheel's own mask +/// engages one channel and is observed without complaint, and the two +/// wheels' indices compose a mask of at most fifteen bits. Neither can +/// fail while the wheels hold what they are permitted to hold, and the +/// wheels are permitted nothing else. +fn add_wheel_panels( + items: &mut Vec, + cosmic_idx: u8, + cycle_idx: u8, + instant: &LoicInstant, + screen_width: u32, +) { + let width = px(screen_width); + + for (channel, idx) in [ + (WheelChannel::Cosmic, cosmic_idx), + (WheelChannel::Cycle, cycle_idx), + ] { + let center = channel.column_left(screen_width) + WHEEL_COL_WIDTH / 2.0; + items.push(centered( + channel.header(), + center, + WHEEL_TOP_Y, + Color::AMBER, + )); + + // The strip: every parent, the selection, every child, the + // selection in white and its neighbours in gray, each row's lines + // stacked at the row pitch from the row's top. + let layout = wheel_layout(channel, idx); + for (row, &top) in layout.rows.iter().zip(&layout.tops) { + let color = if row.selected { + Color::WHITE + } else { + Color::GRAY + }; + for (line_no, line) in row.lines.iter().enumerate() { + let y = top + line_no as f32 * WHEEL_SLOT_HEIGHT; + items.push(centered(line, center, y, color)); + } + } + + // `pos n/total`: the channel observed on its own, through its own + // primes and no other's, and the tick it puts the instant in over + // the ticks it has. + let mask = channel.mask(idx); + let observed = mask + .observe(instant) + .expect("a wheel's mask engages one channel, which observes without objection"); + let total = match channel { + WheelChannel::Cosmic => mask.cosmic_divisor(), + WheelChannel::Cycle => mask.cycle_divisor(), + }; + let label = position_label(observed.position(), &total); + items.push(centered(&label, center, WHEEL_POS_Y, Color::CYAN)); + } + + // Planck times: present the instant to the mask the two wheels compose + // and show the offset into the current tick on its own line, with the + // label beneath. The cycle channel answers whenever it is engaged — its + // ticks turn over within a human lifetime, so its offset is a number + // that visibly moves — and the cosmic channel otherwise, the Whisper + // included, whose offset is the whole of cosmic time; the label names + // whichever channel it was. + let mask_bits = u16::from(cosmic_idx) | (u16::from(cycle_idx) << 7); + let mask = Mask::new(mask_bits).expect("two wheels compose fifteen bits, never a sixteenth"); + let (offset_str, channel) = match mask.observe(instant) { + Ok(result) => { + let channel = if cycle_idx == 0 { "cosmic" } else { "cycle" }; + (result.offset().to_string(), channel) + } + // A mixed mask is refused by `observe` and observed on both channels + // at once by `observe_dual`; the cycle channel's offset is the one + // shown, the cosmic one being, at every resolution the cosmic wheel + // can reach, a number that has not changed since the Whisper. + Err(_) => ( + mask.observe_dual(instant).channel_1.offset().to_string(), + "cycle", + ), + }; + // A very large offset — the Whisper's is cosmic time itself, sixty-one + // digits — goes to scientific notation so that the number stays on one + // line; thirty-two characters is the cutoff beyond which the raw integer + // would risk overrunning the window's width. + let offset_display = if offset_str.len() > 32 { + format_scientific(&offset_str) + } else { + offset_str + }; + let num_w = text_width(&offset_display, 100); + items.push(TextItem { + text: offset_display, + x: (width - px(num_w)) / 2.0, + y: PLANCK_NUM_Y, + color: Color::WHITE, + scale: 1.0, + }); + let label_text = format!("Planck times into the current {channel} subdivision"); + let label_w = text_width(&label_text, 100); + items.push(TextItem { + text: label_text, + x: (width - px(label_w)) / 2.0, + y: PLANCK_LABEL_Y, + color: Color::GRAY, + scale: 1.0, + }); + + // The random button, in amber, centred: the invitation to decline to + // frame the question and see what the universe makes of that. + let btn_text = "[ random ]"; + let btn_w = text_width(btn_text, 100); + items.push(TextItem { + text: btn_text.to_string(), + x: (width - px(btn_w)) / 2.0, + y: RANDOM_BTN_Y, + color: Color::AMBER, + scale: 1.0, + }); +} + +impl State { + /// Conjure the GPU state for a window: the instance, the surface, an + /// adapter, a device and its queue, the surface's configuration, and the + /// four renderers, in that order, each needing the last. The function + /// is `async` because `wgpu` insists on it for the adapter and device + /// requests, and it is driven to completion by `pollster` from the + /// event loop, since the Observatory has no other use for an executor. + /// + /// # Panics + /// + /// Panics if the surface cannot be created from the window, if no + /// adapter will present to that surface, or if the adapter declines to + /// furnish a device. An observatory without an instrument is a room, + /// and the Observatory declines to open as one. + async fn new(window: Arc) -> Self { + let size = window.inner_size(); + + // The instance: Vulkan first, GL as the one fallback the platform is + // permitted, since this is Linux and those are what Linux speaks. No + // display handle is offered here; the surface below carries the + // window's, and the instance learns of the display through it. + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::VULKAN | wgpu::Backends::GL; + let instance = wgpu::Instance::new(desc); + + // The surface, from the window: the chain of textures every frame + // will be presented to. + let surface = instance.create_surface(window.clone()).unwrap(); + + // The adapter is requested with no power preference, which means the + // first device the driver offers. Under Mesa that is the GPU the + // compositor lives on, and `DRI_PRIME=1` moves it to the other one, + // the same convention every other application on the machine + // follows. A discrete GPU buys the Observatory nothing: its frames + // are a few thousand glyph quads, and every one of them would have + // to cross the bus to be composited. Asking for "high performance" + // here would halve the frame rate on a laptop with two GPUs, which + // is the opposite of what the words suggest and precisely why the + // words are not used. No fallback adapter is forced and no limit + // buckets are applied; the Observatory takes the instrument it is + // given and asks nothing of it that a glyph quad would not. + let adapter = instance + .request_adapter(&wgpu::RequestAdapterOptions { + power_preference: wgpu::PowerPreference::None, + compatible_surface: Some(&surface), + force_fallback_adapter: false, + apply_limit_buckets: false, + }) + .await + .expect("no GPU adapter would present to this surface; the Observatory has no lens"); + + // The device and its queue: no features beyond the baseline, default + // limits, memory hints biased toward performance, and no trace, + // since nothing here is worth replaying. + let (device, queue) = adapter + .request_device(&wgpu::DeviceDescriptor { + label: Some("loic_device"), + required_features: wgpu::Features::empty(), + required_limits: wgpu::Limits::default(), + memory_hints: wgpu::MemoryHints::Performance, + experimental_features: wgpu::ExperimentalFeatures::default(), + trace: wgpu::Trace::Off, + }) + .await + .expect("the adapter declined to furnish a device; the instrument has no eyepiece"); + + // The surface's format: the first sRGB format the surface offers, + // or failing that whatever it offers first. The present mode is + // chosen below, and vertical synchronisation is the last resort, + // not the first: a frame that waits for the panel is an observation + // deferred, and observations are not deferred here. + let surface_caps = surface.get_capabilities(&adapter); + let surface_format = surface_caps + .formats + .iter() + .find(|f| f.is_srgb()) + .copied() + .unwrap_or(surface_caps.formats[0]); + + // Immediate if the surface offers it, Mailbox if not, and only then + // Fifo: the first two present frames without waiting for the panel, + // and the frame rate is capped by nothing but the machine. + let present_mode = if surface_caps + .present_modes + .contains(&wgpu::PresentMode::Immediate) + { + wgpu::PresentMode::Immediate + } else if surface_caps + .present_modes + .contains(&wgpu::PresentMode::Mailbox) + { + wgpu::PresentMode::Mailbox + } else { + wgpu::PresentMode::Fifo // vertical sync, only when the surface offers nothing else + }; + + // Name the instrument once, on standard error, so that a machine + // with more than one GPU can be asked which one the Observatory + // chose, and so that the present mode — Immediate or Mailbox for an + // unthrottled frame rate, Fifo only when the surface offers nothing + // else — and the surface format are on the record, in the one place + // a record of this kind belongs. + let info = adapter.get_info(); + eprintln!( + "instrument: {} via {:?}; present mode {:?}; format {:?}", + info.name, info.backend, present_mode, surface_format + ); + + let config = wgpu::SurfaceConfiguration { + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + format: surface_format, + color_space: wgpu::SurfaceColorSpace::Auto, + width: size.width.max(1), + height: size.height.max(1), + present_mode, + alpha_mode: surface_caps.alpha_modes[0], + view_formats: vec![], + desired_maximum_frame_latency: 1, + }; + surface.configure(&device, &config); + + // The four renderers, each with its own pipeline against the surface + // format, and the three that reckon in screen pixels told the + // surface's size before a frame is drawn. The overlay needs no + // size: its one quad is the whole of clip space whatever the + // surface measures. + let mut digit_renderer = DigitRenderer::new(&device, &queue, surface_format); + digit_renderer.resize(&queue, size.width, size.height); + + let mut text_renderer = TextRenderer::new(&device, &queue, surface_format); + text_renderer.resize(&queue, size.width, size.height); + + let overlay_renderer = OverlayRenderer::new(&device, surface_format); + + let artifact_renderer = ArtifactRenderer::new(&device, surface_format); + artifact_renderer.resize(&queue, size.width, size.height); + + Self { + surface, + device, + queue, + config, + size, + window, + digit_renderer, + text_renderer, + overlay_renderer, + artifact_renderer, + } + } + + /// Accommodate a new surface size: the configuration is amended and the + /// surface reconfigured, and the digit and text renderers are told the + /// new dimensions. A size with a zero side is ignored, since a surface + /// of no area cannot be configured and a compositor may report one in + /// passing. The scar renderer keeps the size it was given at creation; + /// the window is created non-resizable, and a scar's location is a + /// fact about where it was inflicted rather than about the surface's + /// present dimensions. + fn resize(&mut self, new_size: winit::dpi::PhysicalSize) { + if new_size.width > 0 && new_size.height > 0 { + self.size = new_size; + self.config.width = new_size.width; + self.config.height = new_size.height; + self.surface.configure(&self.device, &self.config); + self.digit_renderer + .resize(&self.queue, new_size.width, new_size.height); + self.text_renderer + .resize(&self.queue, new_size.width, new_size.height); + } + } + + /// Acquire the next surface texture, the canvas of the frame about to be + /// drawn. The acquisition is, in `wgpu`'s telling, a status report + /// rather than a fallible operation: the surface furnishes one of six + /// statuses, of which two carry a texture and four carry a reason there + /// is none. The two with a texture yield it, a suboptimal texture being + /// a texture nonetheless; the four without collapse into the + /// `RenderOutcome` the caller can act on. + /// + /// # Errors + /// + /// `RenderOutcome::Reconfigure` when the surface reports itself lost or + /// outdated, in which case the caller reconfigures it at its present + /// size and asks for another frame; `RenderOutcome::Skip` when the + /// surface reports a timeout, an occlusion or a validation failure, + /// transient conditions under which the frame is simply not drawn and + /// nothing is owed to anyone. Neither is a failure of the Observatory; + /// both are the compositor's weather. + fn acquire(&self) -> Result { + match self.surface.get_current_texture() { + wgpu::CurrentSurfaceTexture::Success(t) + | wgpu::CurrentSurfaceTexture::Suboptimal(t) => Ok(t), + wgpu::CurrentSurfaceTexture::Lost | wgpu::CurrentSurfaceTexture::Outdated => { + Err(RenderOutcome::Reconfigure) + } + wgpu::CurrentSurfaceTexture::Timeout + | wgpu::CurrentSurfaceTexture::Occluded + | wgpu::CurrentSurfaceTexture::Validation => Err(RenderOutcome::Skip), + } + } + + /// Begin the frame's one render pass: the surface cleared to the void of + /// `CLEAR_COLOR`, the result stored, no depth, no stencil, no timestamps + /// and no occlusion queries, and everything the frame contains drawn on + /// top of that darkness in the order it is drawn. One pass, because the + /// frame is one moment and is painted as one. + fn clear_pass<'a>( + encoder: &'a mut wgpu::CommandEncoder, + view: &'a wgpu::TextureView, + ) -> wgpu::RenderPass<'a> { + encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("main_pass"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(CLEAR_COLOR), + store: wgpu::StoreOp::Store, + }, + depth_slice: None, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }) + } + + /// Render the verdict: the sermon, laid out for the surface, and nothing + /// else. No waterfall, no wheels, no cards, no scars, no hum. An + /// observatory whose kernel does not know what TAI is — the workspace + /// README, section 1.2, on why that is the one thing an observatory must + /// know — has exactly one thing to show, and it shows it, in the same + /// pass and on the same cleared void as a real frame would use, so that + /// the refusal looks like what it is: a frame with the moment removed. + fn render_verdict(&mut self, sermon: &str) -> RenderOutcome { + let items = verdict_items(sermon, self.size.width); + let output = match self.acquire() { + Ok(texture) => texture, + Err(outcome) => return outcome, + }; + let view = output + .texture + .create_view(&wgpu::TextureViewDescriptor::default()); + let mut encoder = self + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("verdict_encoder"), + }); + { + let mut render_pass = Self::clear_pass(&mut encoder, &view); + self.text_renderer + .render(&self.queue, &mut render_pass, &items); + } + self.queue.submit(std::iter::once(encoder.finish())); + self.queue.present(output); + RenderOutcome::Rendered + } + + /// Render one frame of the Observatory from a single observation and the + /// state of the controls: the waterfall from the observation's digits, + /// the panels from its instant, the timeline from its view and path, the + /// scars from their list, and the passage over all of it if one is + /// open. Every temporal value on the frame is read off the one + /// observation; the arguments are many because the frame has many + /// parts, and they are passed rather than reached for so that the + /// renderer knows nothing about the application that it was not told + /// this frame. + #[allow(clippy::too_many_arguments)] + fn render( + &mut self, + observation: &Observation, + timeline_view: &TimelineView, + timeline_path: &[(usize, usize)], + active_overlay: Option, + header: &str, + cosmic_idx: u8, + cycle_idx: u8, + artifacts: &[Artifact], + ) -> RenderOutcome { + // The waterfall's digits and the scars' vertices are written to + // their buffers before the surface is asked for a texture, so that + // a frame the surface declines has cost nothing but two uploads. + self.digit_renderer + .update_digits(&self.queue, &observation.digits); + self.artifact_renderer.update(&self.queue, artifacts); + + let output = match self.acquire() { + Ok(texture) => texture, + Err(outcome) => return outcome, + }; + let view = output + .texture + .create_view(&wgpu::TextureViewDescriptor::default()); + + let mut encoder = self + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("render_encoder"), + }); + + // The one render pass, scoped so that it ends before the encoder is + // asked to finish. + { + let mut render_pass = Self::clear_pass(&mut encoder, &view); + + // The frame's text, in two collections: what lies on the ground + // and what lies on the veil. + let (bg_items, overlay_items) = build_display_panels( + observation, + timeline_view, + timeline_path, + active_overlay, + header, + cosmic_idx, + cycle_idx, + self.size.width, + self.size.height, + ); + + // With a passage open, only the veil and the passage's text are + // drawn; the digits, the panels and the scars wait beneath it, + // unrendered, until it closes. Otherwise the layers go down in + // order: the waterfall, then every string of the display, then + // the scars, last and over everything, since a scar is a hole in + // the cloth and not a thing lying on it. + if active_overlay.is_some() { + self.overlay_renderer.render(&mut render_pass); + self.text_renderer + .render(&self.queue, &mut render_pass, &overlay_items); + } else { + self.digit_renderer.render(&mut render_pass); + self.text_renderer + .render(&self.queue, &mut render_pass, &bg_items); + self.artifact_renderer.render(&mut render_pass); + } + } + + self.queue.submit(std::iter::once(encoder.finish())); + self.queue.present(output); + + RenderOutcome::Rendered + } +} + +/// The outcome of a single render attempt, of which there are three kinds +/// and no fourth: the frame was presented; the surface must be +/// reconfigured before the next one; or the frame was skipped for a +/// transient reason — a timeout, an occlusion, a validation failure — and +/// nothing is owed to anyone. A frame is not a transaction and the +/// Observatory keeps no ledger of the ones the compositor declined. +#[derive(Debug)] +enum RenderOutcome { + /// The frame was drawn and presented; the next may be requested. + Rendered, + /// The surface reported itself lost or outdated; the caller reconfigures + /// it at its present size before asking for another frame. + Reconfigure, + /// A transient condition — timeout, occlusion, validation — under which + /// this frame is not drawn and the next is asked for as usual. + Skip, +} + +/// The timeline's text above its bar, in one of two moods. In the full view: +/// the "You are here" marker pointing at Creation's end of the bar, which +/// is where, to the resolution of a bar this wide, the present moment is, +/// and the invitation to zoom. Zoomed in: the breadcrumb of fractions +/// clicked so far, the key hint, and the span's label, delegated to the +/// breadcrumb function since they are its business. +fn add_timeline_hints( + items: &mut Vec, + timeline_view: &TimelineView, + timeline_path: &[(usize, usize)], + screen_width: u32, + screen_height: u32, +) { + if !timeline_view.is_full() && !timeline_path.is_empty() { + add_timeline_breadcrumbs( + items, + timeline_view, + timeline_path, + screen_width, + screen_height, + ); + return; + } + let width = px(screen_width); + let progress_y = px(screen_height) - px(TIMELINE_BAR_Y); + let bar_margin = px(TIMELINE_BAR_MARGIN); + let char_width = px(CHAR_WIDTH); + + // The full view: "You are here", and a triangle pointing down at the + // bar's first cell. Approximately 10⁻⁹³ of the way along, which the bar + // cannot show and the progress decimal beneath it can. + items.push(TextItem { + text: "You are here".to_string(), + x: bar_margin + char_width, + y: progress_y - 40.0, + color: Color::GRAY, + scale: 1.0, + }); + items.push(TextItem { + text: "▼".to_string(), + x: bar_margin, + y: progress_y - 22.0, + color: Color::GRAY, + scale: 1.0, + }); + + // The invitation, roughly centred: a hundred pixels left of the middle, + // which is about half the hint's width. + items.push(TextItem { + text: "Click bar to zoom in".to_string(), + x: (width / 2.0) - 100.0, + y: progress_y - 38.0, + color: Color::GRAY, + scale: 1.0, + }); +} + +/// The zoomed-in timeline's breadcrumb: the path of fractions clicked so +/// far — "17/58", the seventeenth of fifty-eight segments — stacked upward +/// from the bar, the last five levels only with an ellipsis standing for +/// the rest, each level indented two cells further than the last and the +/// indent looping back to the margin when it reaches the bar's end, so that +/// a descent of forty levels reads as a staircase that wraps rather than a +/// staircase that leaves the window. The current level is in cyan and the +/// ones above it in gray. Beneath the breadcrumb, the key hint is set +/// against the bar's right end and the span's label is centred on the +/// markers' row. +fn add_timeline_breadcrumbs( + items: &mut Vec, + timeline_view: &TimelineView, + timeline_path: &[(usize, usize)], + screen_width: u32, + screen_height: u32, +) { + let width = px(screen_width); + let progress_y = px(screen_height) - px(TIMELINE_BAR_Y); + let bar_margin = px(TIMELINE_BAR_MARGIN); + let char_width = px(CHAR_WIDTH); + + // The last five levels of the path are shown; anything older is + // summarised by an ellipsis, since a breadcrumb forty levels deep would + // climb clean off the top of the surface. + let max_visible = 5; + let path_len = timeline_path.len(); + let start_idx = path_len.saturating_sub(max_visible); + + // The indent's loop is reckoned from the bar's actual width in cells, + // less the cells a fraction needs, so that a fraction is never indented + // off the end of the bar it describes. + let bar_width_chars = cells_across(screen_width); + let fraction_chars = 6; // "58/58" is five cells, and one cell of grace + let max_indent_chars = bar_width_chars.saturating_sub(fraction_chars); + let indent_per_level = 2; // cells of indent per level of descent + let indent_wrap = (max_indent_chars / indent_per_level).max(1); // levels before the loop + + // The fractions stack upward from a line above the hint, at a pitch of + // sixteen pixels. + let line_height = 16.0; + let base_y = progress_y - 55.0; + + // The topmost line is the ellipsis, when the path has been cut, and the + // stack begins high enough that its last line lands on the base. + let mut current_y = base_y - (timeline_path[start_idx..].len() as f32 * line_height); + if start_idx > 0 { + items.push(TextItem { + text: "...".to_string(), + x: bar_margin, + y: current_y, + color: Color::GRAY, + scale: 1.0, + }); + current_y += line_height; + } + + // Each visible level as a fraction, indented by its depth in the whole + // path and not merely in the visible part, so that the staircase does + // not restart every time the ellipsis swallows a step. + for (i, (segment, total)) in timeline_path[start_idx..].iter().enumerate() { + let global_depth = start_idx + i + 1; + // The indent loops: 0, 1, 2, ... up to one short of the wrap, then + // back to the margin and on again. + let indent_level = global_depth % indent_wrap; + let indent = " ".repeat(indent_level); + let fraction = format!("{indent}{segment}/{total}"); + items.push(TextItem { + text: fraction, + x: bar_margin, + y: current_y, + color: if i == timeline_path[start_idx..].len() - 1 { + Color::CYAN + } else { + Color::GRAY + }, + scale: 1.0, + }); + current_y += line_height; + } + + // The key hint, set against the bar's right end; its width is its byte + // length, which for a hint of plain ASCII is its cell count. + let hint_text = "Click to zoom | Backspace: back | Esc: reset"; + let hint_width = hint_text.len() as f32 * char_width; + items.push(TextItem { + text: hint_text.to_string(), + x: width - bar_margin - hint_width, + y: progress_y - 38.0, + color: Color::GRAY, + scale: 1.0, + }); + + // The span's label — "~minutes", "~10^40 years" — centred on the bar, on + // the markers' row, in cyan, so that the reader knows how wide the + // window they are looking through is. + let span_label = timeline_view.format_span(); + let span_width = span_label.len() as f32 * char_width; + items.push(TextItem { + text: span_label, + x: (width - span_width) / 2.0, + y: progress_y + 16.0, + color: Color::CYAN, + scale: 1.0, + }); +} + +/// The timeline bar itself — a bracket, one glyph per segment, a bracket — +/// with `+` for the segments already past, `|` for those to come, and the +/// instant's own segment the first `|`, so that the boundary between the +/// two glyphs is where the frame's one observation falls within the view. +/// Beneath the bar's ends, the labels: Creation and Annihilation in the +/// full view, Start and End in any narrower one. +fn add_timeline_bar( + items: &mut Vec, + observation: &Observation, + timeline_view: &TimelineView, + screen_width: u32, + screen_height: u32, +) { + let width = px(screen_width); + let progress_y = px(screen_height) - px(TIMELINE_BAR_Y); + let bar_margin = px(TIMELINE_BAR_MARGIN); + + // The bar: `[++++|||...|||]`, one cell per segment between the two + // bracket cells. + let bracket_chars = 2; // the [ and the ] + let segment_count = cells_across(screen_width).saturating_sub(bracket_chars); + + // Where the frame's instant falls within this view, as a ratio, or + // nowhere if the view does not contain it. + let now_position = timeline_view.position_of(observation.instant.planck()); + + // The glyphs: `+` up to the instant's segment, `|` from it onward. + let bar_str = if let Some(pos) = now_position { + // The ratio names a segment, and the segments before it are past. + let now_segment = cell_of(pos, segment_count); + let past = "+".repeat(now_segment); + let future = "|".repeat(segment_count.saturating_sub(now_segment)); + format!("[{past}{future}]") + } else { + // The instant lies outside the view, so every segment is on the + // same side of it: all past if the view ends before the instant, + // all future if it begins after. + let is_past = observation.instant.planck() > &timeline_view.end; + if is_past { + format!("[{}]", "+".repeat(segment_count)) + } else { + format!("[{}]", "|".repeat(segment_count)) + } + }; + + items.push(TextItem { + text: bar_str, + x: bar_margin, + y: progress_y, + color: Color::GRAY, + scale: 1.0, + }); + + // The end labels, beneath the markers' row: the cosmological names in + // the full view, since that is what the ends then are, and plain Start + // and End in any view too narrow for its ends to have names. + let label_y = progress_y + 35.0; + let (start_label, end_label) = if timeline_view.is_full() { + ("Creation", "Annihilation") + } else { + ("Start", "End") + }; + items.push(TextItem { + text: start_label.to_string(), + x: bar_margin, + y: label_y, + color: Color::GRAY, + scale: 1.0, + }); + let end_width = text_width(end_label, 100); + items.push(TextItem { + text: end_label.to_string(), + x: width - bar_margin - px(end_width), + y: label_y, + color: Color::GRAY, + scale: 1.0, + }); +} + +/// The events legible at this zoom: a `^` beneath the bar where each one +/// falls, and a list of their names beneath the labels, in chronological +/// order and eight at most. An event becomes legible only once the view is +/// narrow enough for it — the whole of the past fits eight lines at the +/// widest views and the rest surface as the reader descends, each in the +/// company of its own era — so that the timeline rewards the descent +/// rather than crowding the full view with sixty markers on one cell. +fn add_timeline_events( + items: &mut Vec, + timeline_view: &TimelineView, + screen_width: u32, + screen_height: u32, +) { + let width = px(screen_width); + let progress_y = px(screen_height) - px(TIMELINE_BAR_Y); + let bar_margin = px(TIMELINE_BAR_MARGIN); + let char_width = px(CHAR_WIDTH); + let segment_count = cells_across(screen_width).saturating_sub(2); + + // The events whose thresholds admit this zoom and whose instants lie + // within the view. + let events = visible_events(timeline_view); + // The list begins beneath the end labels, with room to breathe. + let mut event_y = progress_y + 55.0; + // The panel has `EVENT_LINES` lines. The thresholds in the timeline + // module are chosen so that no view, at any zoom, has more events to + // list than that, and a test there holds them to it; the `take` is + // therefore a statement of the panel's size, not a truncation of + // anything. + for event in events.iter().take(EVENT_LINES) { + // The marker, at the event's position along the bar's inner run, + // clamped to the bar so that an event on the view's very edge does + // not stand outside the brackets. + if let Some(pos) = timeline_view.position_of(&event.planck_time) { + let bar_inner_width = (segment_count as f32) * char_width; + let event_x = bar_margin + char_width + along(pos, bar_inner_width); + + items.push(TextItem { + text: "^".to_string(), + x: event_x.clamp(bar_margin, width - bar_margin - char_width), + y: progress_y + 16.0, + color: Color::AMBER, + scale: 1.0, + }); + } + + // The name, on the next line of the list, in amber like its marker. + items.push(TextItem { + text: format!("- {}", event.name), + x: bar_margin + 20.0, + y: event_y, + color: Color::AMBER, + scale: 1.0, + }); + event_y += 16.0; + } +} + +/// The progress decimal — "0." and its 154 digits — broken into rows of as +/// many cells as fit between the timeline margins, each row centred, at a +/// pitch of sixteen pixels, in gray, sitting at a fixed height just above +/// the coordinate cards whatever the timeline shows: the eight event lines +/// the bar can list end well above it, and the band between stays empty +/// until the reader zooms in far enough to fill it. It is the one number on +/// the surface that the Loic Public License, section 10, names as a +/// permitted object of contemplation, and it is printed whole so that the +/// contemplation has something to work with beyond the zeros. +fn add_progress_decimal( + items: &mut Vec, + progress_decimal: &str, + screen_width: u32, + screen_height: u32, +) { + let width = px(screen_width); + let chars_per_row = cells_across(screen_width); + let progress_line_height = 16.0; + + let mut y_pos = px(screen_height) - px(PROGRESS_DECIMAL_Y); + let mut chars = progress_decimal.chars().peekable(); + while chars.peek().is_some() { + let row: String = chars.by_ref().take(chars_per_row).collect(); + let row_width = text_width(&row, 100); + items.push(TextItem { + text: row, + x: (width - px(row_width)) / 2.0, + y: y_pos, + color: Color::GRAY, + scale: 1.0, + }); + y_pos += progress_line_height; + } +} + +/// One coordinate card, four lines from a given top-left corner: an amber +/// title, the value in white at card scale one line beneath it, and two +/// gray lines of caption, the first two lines down and the second a little +/// tighter at two and seven tenths, since a caption's second line belongs +/// to its first more than it belongs to the grid. +fn add_card( + items: &mut Vec, + x: f32, + y: f32, + title: &str, + value: &str, + caption_a: &str, + caption_b: &str, +) { + let card_line = px(CARD_LINE_HEIGHT); + items.push(TextItem { + text: title.to_string(), + x, + y, + color: Color::AMBER, + scale: 1.0, + }); + items.push(TextItem { + text: value.to_string(), + x, + y: y + card_line, + color: Color::WHITE, + scale: CARD_SCALE, + }); + items.push(TextItem { + text: caption_a.to_string(), + x, + y: y + card_line * 2.0, + color: Color::GRAY, + scale: 1.0, + }); + items.push(TextItem { + text: caption_b.to_string(), + x, + y: y + card_line * 2.7, + color: Color::GRAY, + scale: 1.0, + }); +} + +/// The three coordinate cards along the bottom of the surface, a hundred +/// and thirty pixels above its lower edge: cosmic time, Planck times since +/// the Big Bang; whisper time, Planck times since the epoch; annihilation +/// time, Planck times until 512 bits run out, captioned as the heat death +/// it lies three orders of magnitude beyond, per the workspace README, +/// section 4.7. The first two are set on the centres of their thirds, +/// offset by `CARD_OFFSET_X`; the third is anchored to the right edge by +/// its widest line, the caption "Planck times until", thirty pixels in, so +/// that the right-hand margin is a margin and not an accident of which card +/// has the longest line. +fn add_cards( + items: &mut Vec, + observation: &Observation, + screen_width: u32, + screen_height: u32, +) { + let width = px(screen_width); + let card_y = px(screen_height) - 130.0; + let card_third = width / 3.0; + let card_offset = px(CARD_OFFSET_X); + + add_card( + items, + card_third * 0.5 - card_offset, + card_y, + "COSMIC TIME", + &observation.cosmic, + "Planck times", + "since Bang", + ); + add_card( + items, + card_third * 1.5 - card_offset, + card_y, + "WHISPER TIME", + &observation.whisper, + "Planck times", + "since Whisper", + ); + let card3_widest = text_width("Planck times until", 100); + add_card( + items, + width - px(card3_widest) - 30.0, + card_y, + "ANNIHILATION TIME", + &observation.terminal, + "Planck times until", + "heat death", + ); +} + +/// The event overlay's text, when a passage is open: its title centred at +/// the top in amber, the close hint beneath it, and the passage itself +/// word-wrapped to the width, paragraph by paragraph. Returned as its own +/// collection, separate from the display's, so that it can be drawn on top +/// of the dimming veil while everything else waits beneath. An empty +/// collection when no passage is open, which is most of the time. +fn overlay_items_for(active_overlay: Option, screen_width: u32) -> Vec { + let mut overlay_items = Vec::new(); + let Some(event_id) = active_overlay else { + return overlay_items; + }; + let width = px(screen_width); + let passage = get_passage(event_id); + + // The column: the surface's width less both margins, in cells. + let overlay_margin = px(OVERLAY_MARGIN); + let chars_per_line = ((screen_width - OVERLAY_MARGIN * 2) / CHAR_WIDTH) as usize; + + // The title, centred at the overlay's title height. It is drawn at the + // title scale of 1.2, so its width is measured at a hundred and twenty + // percent: twelve pixels a cell becomes fourteen and two fifths, and + // the integer arithmetic keeps all but the last fraction of a pixel. + let title_y = px(OVERLAY_TITLE_Y); + let title_width = text_width(passage.title, 120); + overlay_items.push(TextItem { + text: passage.title.to_string(), + x: (width - px(title_width)) / 2.0, + y: title_y, + color: Color::AMBER, + scale: OVERLAY_TITLE_SCALE, + }); + + // The close hint, small and gray, beneath the title: the one instruction + // the overlay gives, and the only one it needs. + overlay_items.push(TextItem { + text: "[Click anywhere or press Esc to close]".to_string(), + x: overlay_margin, + y: title_y + 30.0, + color: Color::GRAY, + scale: 0.8, + }); + + // The passage, word-wrapped: paragraphs are separated by blank lines in + // the source and by the paragraph spacing on the surface. + let mut current_y = title_y + 60.0; + let line_height = px(OVERLAY_LINE_HEIGHT); + let paragraph_spacing = px(OVERLAY_PARAGRAPH_SPACING); + + for paragraph in passage.passage.split("\n\n") { + // Each paragraph is filled word by word: a word that would carry the + // line past the column's width starts the next line instead. The + // width is measured in bytes, so a passage's em dashes and other + // multi-byte characters count for more than one cell and wrap a + // line a little early — the safe direction, since a line that wraps + // early is still inside the column and one that wraps late is not. + let words: Vec<&str> = paragraph.split_whitespace().collect(); + let mut current_line = String::new(); + + for word in words { + let test_line = if current_line.is_empty() { + word.to_string() + } else { + format!("{current_line} {word}") + }; + + if test_line.len() > chars_per_line { + // The line is full: out it goes, and the word that did not + // fit begins the next. + if !current_line.is_empty() { + overlay_items.push(TextItem { + text: current_line.clone(), + x: overlay_margin, + y: current_y, + color: Color::WHITE, + scale: 1.0, + }); + current_y += line_height; + } + current_line = word.to_string(); + } else { + current_line = test_line; + } + } + + // The paragraph's last line, which no word pushed out. + if !current_line.is_empty() { + overlay_items.push(TextItem { + text: current_line, + x: overlay_margin, + y: current_y, + color: Color::WHITE, + scale: 1.0, + }); + current_y += line_height; + } + + // Air between paragraphs. + current_y += paragraph_spacing; + } + overlay_items +} + +/// Assemble the text of every panel of the display, every temporal value +/// on it read off the frame's one observation, laid out from top to bottom +/// as follows: +/// +/// 1. The observation-rate header, one line, centred at the top. +/// 2. The digit waterfall, rendered by its own renderer and not here. +/// 3. The mask wheels, the Planck-times line and the random button. +/// 4. The timeline bar, zoomable from Creation to Annihilation. +/// 5. The progress decimal. +/// 6. The coordinate cards: cosmic, whisper, annihilation. +/// 7. The event overlay, when a passage is open. +/// +/// Also, at the top right, the reminder that Escape restores the full view, +/// shown only when there is a full view to restore. +/// +/// # Returns +/// +/// Two collections: the display's own items, and the overlay's, which are +/// rendered on top of the dimming veil when a passage is open and are empty +/// otherwise. The arguments are many because the display has many parts, +/// and the lint that counts them is told so. +#[allow(clippy::too_many_arguments)] +fn build_display_panels( + observation: &Observation, + timeline_view: &TimelineView, + timeline_path: &[(usize, usize)], + active_overlay: Option, + header: &str, + cosmic_idx: u8, + cycle_idx: u8, + screen_width: u32, + screen_height: u32, +) -> (Vec, Vec) { + let mut items = Vec::new(); + let width = px(screen_width); + + // 1. The header: observers, observations per second, renders per + // second, centred at the top in cyan. + items.push(centered(header, width / 2.0, 30.0, Color::CYAN)); + + // The reminder at the top right that Escape restores the full view, + // shown only while the timeline is zoomed in and there is something to + // restore; in the full view the corner is empty. + if !timeline_view.is_full() { + let reset_btn = "[Esc: Full View]"; + let reset_width = text_width(reset_btn, 100); + items.push(TextItem { + text: reset_btn.to_string(), + x: width - px(reset_width) - 20.0, + y: 20.0, + color: Color::AMBER, + scale: 1.0, + }); + } + + // 3. The wheels, the Planck-times line and the random button, beneath + // the waterfall's reserve; the waterfall itself, item 2, is the digit + // renderer's and is drawn from the same observation elsewhere. + add_wheel_panels( + &mut items, + cosmic_idx, + cycle_idx, + &observation.instant, + screen_width, + ); + + // 4. The timeline: its hints or breadcrumb above the bar, the bar, and + // the events beneath. + add_timeline_hints( + &mut items, + timeline_view, + timeline_path, + screen_width, + screen_height, + ); + add_timeline_bar( + &mut items, + observation, + timeline_view, + screen_width, + screen_height, + ); + add_timeline_events(&mut items, timeline_view, screen_width, screen_height); + + // 5. The progress decimal, and 6. the three coordinate cards beneath it. + add_progress_decimal( + &mut items, + &observation.progress_decimal, + screen_width, + screen_height, + ); + add_cards(&mut items, observation, screen_width, screen_height); + + // 7. The passage, if one is open, in a collection of its own. + let overlay_items = overlay_items_for(active_overlay, screen_width); + + (items, overlay_items) +} + +impl ApplicationHandler for App { + /// The event loop's announcement that a window may be created: the + /// Observatory creates its one window — 800 by 1200 logical pixels, not + /// resizable, titled, and named `APP_ID` for the compositor — conjures + /// the GPU state for it, and starts the render count and the rate clock + /// from zero. A second announcement, should the platform make one, + /// finds the state already present and does nothing. + /// + /// # Panics + /// + /// Panics if the compositor declines to create the window, or if the + /// GPU state cannot be conjured for it. An observatory with no window + /// has nowhere to put the moment. + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + if self.state.is_some() { + return; + } + + let window_attrs = Window::default_attributes() + .with_title("The Loic Observatory — Temporal Meditation") + .with_name(APP_ID, APP_ID) + .with_inner_size(LogicalSize::new(800, 1200)) + .with_resizable(false); + + let window = Arc::new(event_loop.create_window(window_attrs).unwrap()); + + // The GPU state is asynchronous by `wgpu`'s decree and is driven to + // completion here, on the main thread, by the smallest executor + // that will do it. + let state = pollster::block_on(State::new(window.clone())); + self.state = Some(state); + + // The rates begin from this moment, not from the process's birth: + // the frames before the window existed were not frames. + let now = Instant::now(); + self.last_rate_update = now; + self.render_count = 0; + } + + /// Every event the window receives, adjudicated. Before the GPU state + /// exists nothing is handled; a refused observatory handles only the + /// three events that concern the window itself; an observing one closes + /// on request, resizes, redraws, and routes clicks, cursor motion, the + /// mouse wheel and released keys to the handlers that answer them. + fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) { + if self.state.is_none() { + return; + } + // A refused observatory takes no input: there is nothing to scroll, + // click, or zoom, and no question it is prepared to frame. Closing, + // resizing and redrawing are the window's affairs and proceed. + if self.verdict.is_some() + && !matches!( + event, + WindowEvent::CloseRequested + | WindowEvent::Resized(_) + | WindowEvent::RedrawRequested + ) + { + return; + } + + match event { + WindowEvent::CloseRequested => { + event_loop.exit(); + } + WindowEvent::Resized(physical_size) => { + if let Some(state) = &mut self.state { + state.resize(physical_size); + } + } + WindowEvent::RedrawRequested => self.redraw(), + WindowEvent::MouseInput { + state: button_state, + button, + .. + } => { + use winit::event::{ElementState, MouseButton}; + if button_state == ElementState::Released + && button == MouseButton::Left + && let Some(state) = &self.state + { + let size = state.size; + let (click_x, click_y) = self.cursor_position; + self.handle_click(click_x, click_y, size.width, size.height); + } + } + WindowEvent::CursorMoved { position, .. } => { + let position = position.cast::(); + self.cursor_position = (position.x, position.y); + } + WindowEvent::MouseWheel { delta, .. } => { + use winit::event::MouseScrollDelta; + let delta_y = match delta { + MouseScrollDelta::LineDelta(_, y) => y, + // A pixel delta, from a touchpad or a high-resolution + // wheel, is brought to the scale of lines: fifty pixels + // to the line, which is about one notch's worth. + MouseScrollDelta::PixelDelta(pos) => pos.cast::().y / 50.0, + }; + if let Some(state) = &self.state { + let size = state.size; + // The mask wheels claim the scroll first; only if the + // cursor is over neither wheel, and over no scar, does + // the timeline receive it. + if !self.handle_wheel_scroll(delta_y, size.width) { + self.handle_timeline_scroll(delta_y, size.width, size.height); + } + } + } + WindowEvent::KeyboardInput { event, .. } + if event.state == winit::event::ElementState::Released => + { + self.handle_key(&event.logical_key); + } + _ => {} + } + } +} + +impl App { + /// One frame. A refused observatory renders the sermon and asks for no + /// further frames, save one more if the surface needed reconfiguring + /// before it could take the first; an observing one makes its one + /// observation, refreshes both rates if a second has passed, renders, + /// and asks for the next frame at once, because frames are not + /// throttled here and the present moment, per the workspace README, + /// section 1.3, is not a thing one waits for. + /// + /// # Panics + /// + /// Panics if the interval since the last rate update, in milliseconds, + /// does not fit a `u64`: an interval of 584 million years and more, + /// during which the Loic Public License, section 11, makes no warranty + /// that time itself will have continued to function. The panic is the + /// calendar's most honest possible response to a frame that late. + fn redraw(&mut self) { + if let Some(sermon) = self.verdict { + if let Some(state) = &mut self.state + && let RenderOutcome::Reconfigure = state.render_verdict(sermon) + { + state.resize(state.size); + state.window.request_redraw(); + } + return; + } + + // One observation per frame; everything drawn derives from it. The + // frame is counted before the moment is collapsed, so that a frame + // the surface declines is still a frame that was attempted. + self.render_count += 1; + let observation = Observation::collapse(); + + // Both rates are refreshed once a second: renders from this thread's + // own count, observations from the sum of every observer's tally, + // each as the difference since the last refresh over the interval, + // scaled to a second in integer arithmetic. + let now = Instant::now(); + let elapsed_millis = now.duration_since(self.last_rate_update).as_millis(); + if elapsed_millis >= 1000 { + let elapsed = u64::try_from(elapsed_millis) + .expect("an interval under 584 million years; Loic Public License, section 11"); + let renders_this_interval = self.render_count - self.last_render_count; + self.renders_per_sec = (renders_this_interval * 1000) / elapsed; + self.last_render_count = self.render_count; + + let total = self.shared.total(); + let observed_this_interval = total.saturating_sub(self.last_observation_total); + self.observations_per_sec = (observed_this_interval * 1000) / elapsed; + self.last_observation_total = total; + self.last_rate_update = now; + + if let Some(state) = &self.state { + state.window.set_title(&format!( + "The Loic Observatory — {} observers | {} obs/sec | {} renders/sec", + self.observers, self.observations_per_sec, self.renders_per_sec + )); + } + } + + // The frame: the header is composed from the rates as they stand, + // and the renderer is handed the observation, the controls' state + // and the scars. A surface that asks to be reconfigured is + // reconfigured at its present size; a frame skipped is a frame + // skipped. + let header = format!( + "{} observers | {} obs/sec | {} renders/sec", + self.observers, self.observations_per_sec, self.renders_per_sec + ); + if let Some(state) = &mut self.state { + match state.render( + &observation, + &self.timeline_view, + &self.timeline_path, + self.active_overlay, + &header, + self.cosmic_idx, + self.cycle_idx, + &self.artifacts, + ) { + RenderOutcome::Rendered | RenderOutcome::Skip => {} + RenderOutcome::Reconfigure => state.resize(state.size), + } + + // The next frame is requested at once, uncapped: every frame is + // an observation, and observations are not rationed. + state.window.request_redraw(); + } + } + + /// The two keys the Observatory answers to, on release. Escape closes + /// an open passage, or else resets the timeline to the full view; + /// Backspace closes an open passage, or else steps back one zoom level. + /// Every other key is a question the Observatory declines to hear, and + /// a key pressed but not yet released is a question not yet asked. + fn handle_key(&mut self, key: &winit::keyboard::Key) { + use winit::keyboard::{Key, NamedKey}; + match key { + Key::Named(NamedKey::Escape) => { + if self.active_overlay.is_some() { + self.active_overlay = None; + } else { + self.reset_timeline(); + } + } + Key::Named(NamedKey::Backspace) => { + if self.active_overlay.is_some() { + self.active_overlay = None; + } else { + self.zoom_out_one_level(); + } + } + _ => {} + } + } +} + +/// The Observatory's entry: the TAI question, the priority, the event loop, +/// and the application, in that order, because each is a precondition of +/// the next and the first is a precondition of there being anything to do +/// at all. +/// +/// # Panics +/// +/// Panics if the event loop cannot be created or cannot be run, which on +/// this platform means there is no Wayland display to be had; every other +/// platform is, per the workspace README, heresy, and does not get as far +/// as the event loop. +fn main() { + // The one question asked before anything else, and before any thread + // exists to die of the answer: does the kernel know what TAI is? On a + // kernel whose TAI offset is zero, `CLOCK_TAI` is `CLOCK_REALTIME` + // wearing a name tag (the workspace README, section 1.2), the first + // observation of any thread would preach the sermon and die, and later + // threads would see only a poisoned lock. So the question is asked here, + // by the main thread, through `kernel_tai_offset()`, and the sermon + // becomes the Observatory's entire content — printed here for the + // terminal, rendered there for the window — with no thread ever loosed + // to die of it. + let verdict = (kernel_tai_offset() == 0).then_some(TAI_HERESY); + if let Some(sermon) = verdict { + eprintln!("{sermon}"); + } + + // The Observatory is not nice. It asks for `OBSERVATORY_NICE` at this + // point, while it is still a single thread, so that every observer + // inherits the value at birth. If the kernel declines — the limit is the + // administrator's to raise, and the refusal is the kernel's to make — it + // says so once, on standard error, and runs at the priority of + // everything else, which is a compromise it did not choose and does not + // hide. + if verdict.is_none() { + // SAFETY: `setpriority` has no memory-safety preconditions; it takes + // three integers, touches no memory of ours, and either lowers the + // calling thread's nice value or fails with `EACCES`. + let refused = unsafe { libc::setpriority(libc::PRIO_PROCESS, 0, OBSERVATORY_NICE) } != 0; + if refused { + eprintln!( + "the kernel declined nice {OBSERVATORY_NICE} ({}); observing at the priority of everything else", + std::io::Error::last_os_error() + ); + } + } + + let event_loop = EventLoop::new().unwrap(); + // Observing: poll, because every frame is an observation, observations + // are not throttled, and an event loop that slept between them would be + // sleeping through the present. Refused: wait, because one frame has + // already said everything and the sermon does not change. + event_loop.set_control_flow(if verdict.is_some() { + ControlFlow::Wait + } else { + ControlFlow::Poll + }); + + let mut app = App::new(verdict); + event_loop.run_app(&mut app).unwrap(); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The verdict frame carries the library's sermon verbatim — every word, + /// in order, nothing added, nothing dropped, at four widths from the + /// default window to a wide monitor — and no line of it is wider than + /// the surface allows. A sermon paraphrased by its own display would be + /// the Observatory editorialising on a text it is only permitted to + /// deliver. + #[test] + fn verdict_frame_is_the_sermon_verbatim_and_fits_the_surface() { + for width in [800u32, 1000, 1600, 2560] { + let chars_per_line = ((width - OVERLAY_MARGIN * 2) / CHAR_WIDTH) as usize; + let items = verdict_items(TAI_HERESY, width); + let rendered: Vec<&str> = items.iter().map(|item| item.text.as_str()).collect(); + let rendered_words: Vec<&str> = rendered + .iter() + .flat_map(|line| line.split_whitespace()) + .collect(); + let sermon_words: Vec<&str> = TAI_HERESY.split_whitespace().collect(); + assert_eq!(rendered_words, sermon_words, "at width {width}"); + for line in &rendered { + assert!( + line.chars().count() <= chars_per_line, + "at width {width}, {line:?} overruns the surface's {chars_per_line} cells" + ); + } + } + } + + /// The progress expansion is "0." and exactly 154 digits, all of them + /// digits, and its leading zeros are the vast emptiness ahead: at the + /// epoch there are ninety-two of them, which is what 10⁻⁹³ of the way + /// through everything looks like when it is written out in full. + #[test] + fn progress_decimal_has_exactly_154_places() { + let expansion = progress_decimal(&LoicInstant::epoch()); + assert_eq!(expansion.len(), 2 + 154); + assert!(expansion.starts_with("0.")); + assert!(expansion[2..].bytes().all(|b| b.is_ascii_digit())); + let leading_zeros = expansion[2..].bytes().take_while(|&b| b == b'0').count(); + assert_eq!(leading_zeros, 92); + } + + /// Every wheel strip, for every one of the 384 masks the two wheels can + /// select between them, is the selection's complete Hasse neighbourhood + /// in its channel: one row per prime plus the selection, exactly one row + /// selected, the selection's row index equal to its parent count, every + /// neighbour exactly one prime away — parents above as strict supersets, + /// children below as strict subsets — the row directly above activating + /// the lowest inactive prime and the row directly below deactivating + /// the lowest active one, which is what the scroll steps must agree + /// with, and do. + #[test] + fn wheel_rows_are_the_hasse_neighbourhood() { + for channel in [WheelChannel::Cosmic, WheelChannel::Cycle] { + for idx in 0..=channel.full_index() { + let rows = wheel_rows(channel, idx); + assert_eq!(rows.len(), usize::from(channel.prime_count()) + 1); + assert_eq!(rows.iter().filter(|row| row.selected).count(), 1); + let selected = rows + .iter() + .position(|row| row.selected) + .expect("one row, and one only, is the selection"); + assert_eq!(rows[selected].idx, idx); + let active = usize::try_from(idx.count_ones()).expect("eight primes fit a usize"); + let parents = usize::from(channel.prime_count()) - active; + assert_eq!(selected, parents, "channel {channel:?} index {idx}"); + for (i, row) in rows.iter().enumerate() { + if i == selected { + continue; + } + assert_eq!((row.idx ^ idx).count_ones(), 1); + if i < selected { + assert!(row.idx & idx == idx && row.idx > idx); + } else { + assert!(row.idx & idx == row.idx && row.idx < idx); + } + } + if selected > 0 { + assert_eq!(rows[selected - 1].idx, channel.step_finer(idx)); + } + if selected + 1 < rows.len() { + assert_eq!(rows[selected + 1].idx, channel.step_coarser(idx)); + } + } + } + } + + /// Scrolling up from the Whisper climbs one prime at a time — seven + /// steps on the cosmic wheel, eight on the cycle wheel — to the full + /// mask and then loops to the Whisper; scrolling down does the reverse + /// and loops to the full mask. A wheel has no top and no bottom, only + /// the place where it comes round again. + #[test] + fn wheels_loop_like_wheels() { + for channel in [WheelChannel::Cosmic, WheelChannel::Cycle] { + let mut idx = 0u8; + for _ in 0..channel.prime_count() { + idx = channel.step_finer(idx); + } + assert_eq!(idx, channel.full_index()); + assert_eq!(channel.step_finer(idx), 0); + for _ in 0..channel.prime_count() { + idx = channel.step_coarser(idx); + } + assert_eq!(idx, 0); + assert_eq!(channel.step_coarser(idx), channel.full_index()); + } + } + + /// A wrapped name keeps every line within the column's thirty-one cells + /// and loses no name: stripping the continuation signs and rejoining the + /// lines gives the library's label back, character for character, for + /// every mask either wheel can select. A factorisation that lost a + /// factor to a line break would be naming a different divisor. + #[test] + fn wrapped_names_fit_and_survive() { + for channel in [WheelChannel::Cosmic, WheelChannel::Cycle] { + for idx in 0..=channel.full_index() { + let label = channel.mask(idx).label(); + let lines = wrap_names(&label, WHEEL_CHARS); + assert!( + lines.iter().all(|line| line.chars().count() <= WHEEL_CHARS), + "a line of {label} overruns the column" + ); + let rejoined = lines + .iter() + .map(|line| line.trim_end_matches(" ×")) + .collect::>() + .join(" × "); + assert_eq!(rejoined, label); + } + } + } +} diff --git a/crates/loic-gui/src/overlay.rs b/crates/loic-gui/src/overlay.rs new file mode 100644 index 0000000..b09b36d --- /dev/null +++ b/crates/loic-gui/src/overlay.rs @@ -0,0 +1,188 @@ +//! The veil: the overlay renderer of the Loic Observatory. +//! +//! This module furnishes the means by which a translucent veil may be +//! interposed between the observer and the temporal display — a gossamer +//! shroud of configurable opacity, behind which the digits, bars, wheels +//! and coordinates of the moment may be put aside while a passage about +//! some other moment is read. The passage is Channel 1, content, a story; +//! the veil is what permits a story to be told over a display whose every +//! element insists on the present. +//! +//! The implementation is minimal to the point of asceticism: one +//! fullscreen quad, six vertices conjured from their indices by the +//! shader, rendered with alpha blending, whose sole purpose is to darken +//! whatever lies beneath. No textures, no vertex buffer, no instancing; +//! merely the primitive and one uniform colour. In the Observatory's frame +//! what lies beneath the veil is the cleared void alone, since the display +//! is not drawn while a passage is open, so the veil is in practice a second +//! coat of the same darkness and its translucency is a capacity held in +//! reserve. It is drawn all the same, because the frame is composed in +//! layers and the veil is one of them. + +use wgpu::util::DeviceExt; + +/// The layout of the overlay's uniform buffer: a single four-component +/// vector holding the veil's red, green, blue and alpha, each between zero +/// and one, in the `f32` the GPU insists upon and the calendar tolerates +/// for a colour, since a colour was never a Planck count. `Pod` and +/// `Zeroable` so that the bytes may be handed to the GPU as they lie. +#[repr(C)] +#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] +struct OverlayUniforms { + /// The veil's colour and opacity, in that order: red, green, blue, + /// alpha. + color: [f32; 4], +} + +/// The veil's renderer: one pipeline with alpha blending, one bind group, +/// one uniform buffer holding one colour. It draws a fullscreen +/// semi-transparent quad over whatever the render pass has already drawn, +/// leaving that visible in proportion to one minus the alpha and replacing +/// the rest with the veil's own colour — which is to say it dims, in the +/// exact arithmetic of blending, everything beneath it by the same amount. +pub struct OverlayRenderer { + /// The pipeline: the overlay shader's two stages, alpha blending against + /// the surface format, a triangle list, and nothing else. + pipeline: wgpu::RenderPipeline, + /// The bind group presenting the uniform buffer to the fragment stage. + bind_group: wgpu::BindGroup, + /// The uniform buffer holding the veil's colour, written once at + /// creation and again whenever the colour is changed. + uniform_buffer: wgpu::Buffer, +} + +impl OverlayRenderer { + /// Conjures the veil's renderer into existence for a given device and + /// surface format: the uniform buffer with its default colour, the bind + /// group layout and bind group that present it to the fragment stage, + /// the pipeline layout, the shader, and the pipeline. + /// + /// The default colour is the void's own — red 0.02, green 0.02, blue + /// 0.03, the same three components the surface is cleared to — at an + /// opacity of 85 percent: enough to render whatever lay beneath it + /// illegible without obliterating it, had anything been drawn beneath + /// it, which in the Observatory nothing is. The colour may be changed + /// afterwards through `set_color`, a capacity offered and, at present, + /// declined. + pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self { + // The default veil: the void's colour at 85 percent, so that the veil + // and the ground it covers are one darkness. + let uniforms = OverlayUniforms { + color: [0.02, 0.02, 0.03, 0.85], + }; + + let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("overlay_uniforms"), + contents: bytemuck::cast_slice(&[uniforms]), + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + }); + + // One binding, a uniform buffer, visible to the fragment stage + // alone: the vertex stage needs no colour to place a quad. + let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("overlay_bind_group_layout"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }], + }); + + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("overlay_bind_group"), + layout: &bind_group_layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: uniform_buffer.as_entire_binding(), + }], + }); + + // The pipeline layout: that one bind group, and no immediate data. + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("overlay_pipeline_layout"), + bind_group_layouts: &[Some(&bind_group_layout)], + immediate_size: 0, + }); + + // The shader, compiled into the binary as text and handed to the + // device as WGSL: a vertex stage that conjures the quad from vertex + // indices, and a fragment stage that returns the uniform colour. + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("overlay_shader"), + source: wgpu::ShaderSource::Wgsl(include_str!("shaders/overlay.wgsl").into()), + }); + + // The pipeline: no vertex buffers, since the shader needs none; a + // triangle list; alpha blending against the surface format, which + // is the whole of what makes a veil a veil rather than a wall. + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("overlay_pipeline"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_main"), + buffers: &[], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: Some(wgpu::BlendState::ALPHA_BLENDING), + write_mask: wgpu::ColorWrites::ALL, + })], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }), + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + ..Default::default() + }, + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + multiview_mask: None, + cache: None, + }); + + Self { + pipeline, + bind_group, + uniform_buffer, + } + } + + /// Draws the veil: one draw call of six vertices, two triangles, one + /// instance, forming a quad that covers the whole of clip space from + /// corner to corner. The quad is blended over the pass in the current + /// uniform colour, which by default is the void's own at 85 percent + /// opacity. + /// + /// The veil belongs between the layers it separates: after whatever is + /// to be dimmed and before whatever is to be read through it, which in + /// the Observatory is the passage's text. Drawn last, it would dim the + /// passage; drawn first, it would dim nothing but the void, which is + /// what it does regardless, but on principle. + pub fn render<'a>(&'a self, render_pass: &mut wgpu::RenderPass<'a>) { + render_pass.set_pipeline(&self.pipeline); + render_pass.set_bind_group(0, &self.bind_group, &[]); + render_pass.draw(0..6, 0..1); + } + + /// Rewrites the veil's colour: four components between zero and one, + /// written to the uniform buffer through the queue and in effect from + /// the next draw. Offered so that the default darkness might be made + /// deeper or shallower should an observer's eyes require it; no caller + /// has yet required it, and the allowance beneath says so to the lint. + #[allow(dead_code)] + pub fn set_color(&self, queue: &wgpu::Queue, r: f32, g: f32, b: f32, a: f32) { + let uniforms = OverlayUniforms { + color: [r, g, b, a], + }; + queue.write_buffer(&self.uniform_buffer, 0, bytemuck::cast_slice(&[uniforms])); + } +} diff --git a/crates/loic-gui/src/renderer.rs b/crates/loic-gui/src/renderer.rs new file mode 100644 index 0000000..9e3519d --- /dev/null +++ b/crates/loic-gui/src/renderer.rs @@ -0,0 +1,620 @@ +//! # The Digit Waterfall +//! +//! The renderer of the Observatory's principal exhibit: the cosmic time — +//! Planck times since Creation, sixty-one digits of it today and a hundred +//! and fifty-four at Annihilation — poured across the top of the window as +//! rows of glyphs, one instanced quad per digit, each quad a lookup into a +//! glyph atlas baked once at start-up from a five-by-seven bitmap font. +//! The last thirty-four digits are cyan and change with every observation, +//! since 10^34 Planck times fit in a nanosecond and the nanosecond's +//! interior is entropy; the nine before them are gray and change faster +//! than a person can read; the rest are white and hold still for a second +//! or more. Which is which is the shader's business and is stated in +//! `digit.wgsl`; this module's business is where the digits go and how big +//! they are. +//! +//! The atlas is never scaled. The quads that sample it are, by integer +//! factors and with nearest filtering, so that each texel is a crisp block +//! of pixels at every step of the font; and the font steps down — once, at +//! the hundred-and-twenty-first digit, around the year 1.7 × 10^69 — only +//! when the digits outgrow the reserve of height they have been granted, +//! so that nothing below the waterfall ever moves. The main thread makes +//! one observation per frame and hands its digits here. The observer +//! threads, which make orders of magnitude more, hand over nothing; theirs +//! are made to be discarded, and discarded they are. + +use wgpu::util::DeviceExt; + +/// The most digits the storage buffer holds, and therefore the most the +/// waterfall will ever draw: 256. The cosmic time is 61 digits today and +/// 154 at Annihilation, after which there is no more cosmic time to have +/// digits; 256 is the next power of two above that, a size a GPU finds +/// congenial and an allocation of one kilobyte, which even a calendar this +/// extravagant declines to call waste. A slice longer than this is +/// truncated to it by `update_digits`, a condition no valid instant can +/// produce and no invalid one is offered. +const MAX_DIGITS: usize = 256; + +/// One cell of the atlas, at the font's true resolution: a 5×7 glyph with +/// one texel of air to its right and below, six texels wide and eight +/// tall. The atlas is never scaled; the quads that sample it are, by +/// integer factors, with nearest filtering, so that every texel becomes a +/// crisp block of pixels at any step. Six by eight, times the step, is also +/// the pitch of the digits on screen: the air is part of the cell, and a +/// row of digits is a row of cells with no further spacing added. +const CELL_WIDTH: u32 = 6; +const CELL_HEIGHT: u32 = 8; + +/// The atlas: ten glyphs, 0 through 9, in one row of cells, sixty texels +/// wide and eight tall, a single-channel texture of four hundred and eighty +/// bytes that describes every digit the age of the universe will ever +/// need. The shader finds glyph `d` at `d` tenths of the atlas width, which +/// is why the order of the cells is the order of the digits and why there +/// is no eleventh. +const ATLAS_WIDTH: u32 = CELL_WIDTH * 10; +const ATLAS_HEIGHT: u32 = CELL_HEIGHT; + +/// The waterfall's horizontal margin, in pixels, on both sides: forty, the +/// same forty the timeline bar keeps from the window's edges in `main.rs`, +/// so that the first digit and the bar's opening bracket share a column and +/// the eye, travelling down, finds nothing to correct. The margin is +/// subtracted twice from the window's width to get the width the rows may +/// fill, and the rows fill it with whole cells and leave the remainder. +const X_MARGIN: u32 = 40; + +/// The waterfall's top edge, in pixels from the top of the window: sixty, +/// which places the first row just below the single-line header — the +/// count of observers, their observations per second and the renders per +/// second — that `main.rs` centres at thirty. The digits begin where the +/// accounting ends. +const WATERFALL_TOP: u32 = 60; + +/// The waterfall's reserve: the height, in pixels, that every step of the +/// font must fit its rows into, so that nothing below it — the wheels, the +/// bar, the cards — ever moves, however many digits the cosmic time grows +/// to between now and Annihilation. One hundred and sixty pixels is four +/// rows of the largest step, whose cell is forty pixels tall; the layout +/// beneath is placed on the assumption that the waterfall ends here, and +/// the test `every_count_fits_the_reserve` sees that it does for every +/// digit count the buffer can hold. +const WATERFALL_HEIGHT: u32 = 160; + +/// The steps of the font, largest first, as integer multiples of the cell's +/// width and height. (4, 5) is the 24×40 look the Observatory opens with; +/// the rest are what the digits shrink to when the universe outgrows the +/// reserve, each a whole number of pixels per texel so that no glyph is +/// ever resampled into a blur. At 800 pixels wide, thirty cells of the +/// first step fit a row and four rows fit the reserve, so the first step +/// holds 120 digits; forty of the second fit a row and five rows the +/// reserve, so the second holds 200. The calendar's last digit is the +/// 154th. The shrink therefore happens once, when the cosmic time reaches +/// 10^120 Planck times — around the year 1.7 × 10^69 — and then never +/// again; the third step, and the two below it, exist for widths narrower +/// than the window allows and for counts larger than the universe supplies. +const SCALE_STEPS: [(u32, u32); 5] = [(4, 5), (3, 4), (2, 3), (2, 2), (1, 1)]; + +/// Elect the step of the font: the largest whose rows of `digit_count` +/// digits fit the reserve at this width. The width between the margins is +/// divided by the step's cell width to get the digits per row, at least +/// one; the count is divided by that, rounding up, to get the rows; and +/// the rows times the step's cell height must not exceed the reserve. The +/// first step that passes is the answer, and the smallest step is the +/// answer if none passes — a fallback that no digit count the buffer can +/// hold reaches at any width the window is allowed, and that exists so +/// that the function has an answer for every question rather than a +/// question of its own. Integer arithmetic throughout: a step of the font +/// is a count of pixels per texel, and a count is not a thing to +/// approximate. +fn glyph_scale_for(digit_count: u32, screen_width: u32) -> (u32, u32) { + let content_width = screen_width.saturating_sub(2 * X_MARGIN).max(CELL_WIDTH); + SCALE_STEPS + .iter() + .copied() + .find(|&(kx, ky)| { + let per_row = (content_width / (CELL_WIDTH * kx)).max(1); + let rows = digit_count.div_ceil(per_row); + rows * CELL_HEIGHT * ky <= WATERFALL_HEIGHT + }) + .unwrap_or(SCALE_STEPS[SCALE_STEPS.len() - 1]) +} + +/// The uniform block the digit shader reads, laid out in C order to match +/// the `Uniforms` struct in `digit.wgsl` field for field: two `vec2` +/// for the screen and the glyph, one for the atlas, then the digit count, +/// the vertical offset, the horizontal margin and the time — forty bytes, +/// rewritten whenever the digits, the window or the clock change. The +/// floats are the point of GPU submission, where the heresy is tolerated +/// because the hardware speaks nothing else; all but the last of them are +/// integers below 2^24, cast at the last moment and carried exactly, and +/// the last is a count of seconds that drives a shimmer and touches no +/// instant. +#[repr(C)] +#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] +struct Uniforms { + /// The surface's width and height in pixels, by which the shader + /// divides to reach clip space, where the GPU insists on living. + screen_size: [f32; 2], + /// The width and height of one digit's quad in pixels: the cell times + /// the step of the font in force. + glyph_size: [f32; 2], + /// The atlas's width and height in texels, sixty by eight, so that the + /// shader can find a glyph's tenth of it. + atlas_size: [f32; 2], + /// How many digits to draw, and therefore how many instances; the + /// shader also counts back from this to colour the zones. + digit_count: u32, + /// The waterfall's top, in pixels from the top of the window: + /// `WATERFALL_TOP`, sixty, placing the first row just below the + /// single-line header of observers and rates that `main.rs` centres at + /// y=30. + y_offset: u32, + x_margin: u32, // the horizontal margin, in pixels: X_MARGIN, the bar's own forty + time: f32, // seconds since this renderer was born, for the cyan zone's shimmer +} + +/// The digit renderer: the GPU state for the waterfall — a pipeline, the +/// bind group that ties atlas, sampler, uniforms and digit buffer together, +/// the two buffers themselves — and the little it remembers between frames: +/// the glyph size in force, the surface's size, how many digits it was last +/// handed, and when it was born, from which the shimmer takes its phase. +/// One of these exists, owned by the render state, and it outlives every +/// instant it has ever drawn. +pub struct DigitRenderer { + /// The render pipeline: `digit.wgsl`'s vertex and fragment stages, alpha + /// blending, a triangle list, no culling and no depth. + pipeline: wgpu::RenderPipeline, + /// The four bindings the shader reads: uniforms, atlas view, sampler, + /// digits, in that order and at those indices. + bind_group: wgpu::BindGroup, + /// The forty-byte uniform block, rewritten by `update_uniforms`. + uniform_buffer: wgpu::Buffer, + /// The storage buffer of digits, `MAX_DIGITS` of them as `u32`, of which + /// the first `digit_count` are drawn and the rest are ignored. + digit_buffer: wgpu::Buffer, + /// The width and height of one digit's quad in pixels, at the step of + /// the font in force; recomputed by `fit_glyphs` on every resize and + /// every new set of digits. + glyph_size: (f32, f32), + /// The surface's width and height in pixels, as last reported by + /// `resize`; the width decides how many cells a row holds. + screen_size: (u32, u32), + /// How many digits are being drawn, which is how many the cosmic time + /// has: sixty-one today, and never fewer again. + digit_count: u32, + /// The instant this renderer was constructed, from which the `time` + /// uniform is measured for the shimmer; a monotonic clock, not the + /// calendar's, because the shimmer is decoration and decoration may be + /// measured in seconds without heresy. + start_time: std::time::Instant, +} + +impl DigitRenderer { + /// Assemble the renderer: bake the atlas and upload it as an `R8Unorm` + /// texture, make the sampler that reads it without interpolating, lay + /// out the uniform block and the digit buffer, bind the four of them, + /// compile the shader, and build the pipeline that draws six vertices + /// per instance with alpha blending onto a surface of the given + /// `format`. Until `resize` and `update_digits` have been called the + /// renderer believes the surface is 800 by 800 and the count is zero, + /// draws nothing, and is right to. + #[allow( + clippy::too_many_lines, + reason = "the GPU's initiation is one linear rite — atlas, texture, sampler, buffers, bind group, pipeline — each step needing the last; five functions would be five places to read one paragraph" + )] + pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, format: wgpu::TextureFormat) -> Self { + // Bake the atlas on the CPU from the bitmap font below: sixty by eight texels, a byte each. + let atlas_data = generate_glyph_atlas(); + + // The atlas as a texture: one channel, eight bits, unsigned and + // normalised, so that a lit texel samples as 1.0 and an unlit one as + // 0.0, and the fragment shader can use the sample as alpha directly. + let atlas_texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("glyph_atlas"), + size: wgpu::Extent3d { + width: ATLAS_WIDTH, + height: ATLAS_HEIGHT, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::R8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + + queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture: &atlas_texture, + mip_level: 0, + origin: wgpu::Origin3d::ZERO, + aspect: wgpu::TextureAspect::All, + }, + &atlas_data, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(ATLAS_WIDTH), + rows_per_image: Some(ATLAS_HEIGHT), + }, + wgpu::Extent3d { + width: ATLAS_WIDTH, + height: ATLAS_HEIGHT, + depth_or_array_layers: 1, + }, + ); + + let atlas_view = atlas_texture.create_view(&wgpu::TextureViewDescriptor::default()); + + // Nearest filtering, both ways: the quads are integer multiples of + // the cell, so each texel lands on a whole block of pixels and + // nothing is blurred; clamped at the edges, because a lookup outside + // the atlas has no digit to find. + let atlas_sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("glyph_sampler"), + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Nearest, + min_filter: wgpu::FilterMode::Nearest, + ..Default::default() + }); + + // The uniform block at its initial values: the largest step of the + // font, a surface of 800 by 800 that the first resize will correct, + // and no digits, which the first observation will correct. + let (kx, ky) = SCALE_STEPS[0]; + let uniforms = Uniforms { + screen_size: [800.0, 800.0], + glyph_size: [(CELL_WIDTH * kx) as f32, (CELL_HEIGHT * ky) as f32], + atlas_size: [ATLAS_WIDTH as f32, ATLAS_HEIGHT as f32], + digit_count: 0, // no digits until the first observation is handed over + y_offset: WATERFALL_TOP, + x_margin: X_MARGIN, + time: 0.0, + }; + + let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("uniforms"), + contents: bytemuck::cast_slice(&[uniforms]), + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + }); + + // The digit buffer, allocated at its largest once and never grown: + // MAX_DIGITS u32s, of which the first digit_count are read by the + // shader and the remainder wait for the universe to age into them. + let digits = vec![0u32; MAX_DIGITS]; + let digit_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("digits"), + contents: bytemuck::cast_slice(&digits), + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + }); + + // The layout of the four bindings: the uniform block for both + // stages, the atlas and its sampler for the fragment stage, and the + // digits, read-only, for the vertex stage, which is where a digit's + // value becomes a glyph's column in the atlas. + let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("digit_bind_group_layout"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + multisampled: false, + view_dimension: wgpu::TextureViewDimension::D2, + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 3, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: true }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + ], + }); + + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("digit_bind_group"), + layout: &bind_group_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: uniform_buffer.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&atlas_view), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::Sampler(&atlas_sampler), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: digit_buffer.as_entire_binding(), + }, + ], + }); + + // One bind group and no immediates: the pipeline's layout is the + // layout above and nothing more. + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("digit_pipeline_layout"), + bind_group_layouts: &[Some(&bind_group_layout)], + immediate_size: 0, + }); + + // The shader, compiled here from source that was embedded in the + // binary at build time; the Observatory carries its own shaders and + // reads none from disk. + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("digit_shader"), + source: wgpu::ShaderSource::Wgsl(include_str!("shaders/digit.wgsl").into()), + }); + + // The pipeline: six vertices per instance as a triangle list, no + // culling, alpha blending so that the air around a glyph shows the + // void through it, and no depth, the waterfall being flat. + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("digit_pipeline"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_main"), + buffers: &[], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: Some(wgpu::BlendState::ALPHA_BLENDING), + write_mask: wgpu::ColorWrites::ALL, + })], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }), + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + strip_index_format: None, + front_face: wgpu::FrontFace::Ccw, + cull_mode: None, + polygon_mode: wgpu::PolygonMode::Fill, + unclipped_depth: false, + conservative: false, + }, + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + multiview_mask: None, + cache: None, + }); + + Self { + pipeline, + bind_group, + uniform_buffer, + digit_buffer, + glyph_size: ((CELL_WIDTH * kx) as f32, (CELL_HEIGHT * ky) as f32), + screen_size: (800, 800), + digit_count: 0, + start_time: std::time::Instant::now(), + } + } + + /// Elect the step of the font for the current digit count and width, + /// and record the quad it implies: the cell times the step, in pixels, + /// as the two floats the shader wants. Called on every resize and every + /// observation; it is cheap, and it changes its answer once at start-up + /// and once around the year 1.7 × 10^69. + fn fit_glyphs(&mut self) { + let (kx, ky) = glyph_scale_for(self.digit_count, self.screen_size.0); + self.glyph_size = ((CELL_WIDTH * kx) as f32, (CELL_HEIGHT * ky) as f32); + } + + /// Take note of the surface's new size, refit the font to the width, + /// and push the uniforms. The height is recorded and handed to the + /// shader, which needs it to reach clip space; the width is what decides + /// how many cells a row holds and therefore which step of the font the + /// reserve can afford. The Observatory's window is not resizable, so + /// this is called once, after construction, and then never; the + /// function does not know that and would not care. + pub fn resize(&mut self, queue: &wgpu::Queue, width: u32, height: u32) { + self.screen_size = (width, height); + self.fit_glyphs(); + self.update_uniforms(queue); + } + + /// Take the digits of a fresh observation — most significant first, as + /// many as the cosmic time has — write them to the storage buffer, and + /// refit the font to the count: the digits shrink by a step when the + /// count outgrows the reserve, and not before, and never grow back, + /// since the cosmic time does not. A slice longer than `MAX_DIGITS` is + /// cut to that length, a courtesy no valid instant will ever call on. + /// Called once per frame by the main thread with its one observation. + /// + /// # Panics + /// + /// Panics if the clamped count does not fit a `u32`, which it always + /// does, 256 being somewhat less than four billion; the `expect` is the + /// conversion's receipt, not a live possibility. + pub fn update_digits(&mut self, queue: &wgpu::Queue, digits: &[u32]) { + let count = digits.len().min(MAX_DIGITS); + self.digit_count = u32::try_from(count).expect("a count clamped to MAX_DIGITS fits a u32"); + self.fit_glyphs(); + + // The digits go to the GPU as they came, one u32 each, and only the first count of them. + queue.write_buffer( + &self.digit_buffer, + 0, + bytemuck::cast_slice(&digits[..count]), + ); + + // And the uniforms follow, carrying the new count and the glyph size it implies. + self.update_uniforms(queue); + } + + /// Write the uniform block afresh: the surface, the glyph, the atlas, + /// the count, the two layout constants, and the seconds elapsed since + /// the renderer was born, which is the phase of the shimmer. Called + /// after every resize and every observation, so the time is refreshed + /// as often as the digits are, and the shimmer advances at the frame + /// rate, whatever that happens to be. + fn update_uniforms(&self, queue: &wgpu::Queue) { + let elapsed = self.start_time.elapsed().as_secs_f32(); + let uniforms = Uniforms { + screen_size: [self.screen_size.0 as f32, self.screen_size.1 as f32], + glyph_size: [self.glyph_size.0, self.glyph_size.1], + atlas_size: [ATLAS_WIDTH as f32, ATLAS_HEIGHT as f32], + digit_count: self.digit_count, + y_offset: WATERFALL_TOP, + x_margin: X_MARGIN, + time: elapsed, + }; + queue.write_buffer(&self.uniform_buffer, 0, bytemuck::cast_slice(&[uniforms])); + } + + /// Draw the waterfall into the frame's render pass: one draw call, six + /// vertices per instance, one instance per digit, the pipeline and the + /// bind group set for the occasion. Draws nothing at all when the count + /// is zero — before the first observation has been handed over — rather + /// than asking the GPU to draw zero instances and finding out what it + /// thinks of that. + pub fn render<'a>(&'a self, render_pass: &mut wgpu::RenderPass<'a>) { + if self.digit_count == 0 { + return; + } + render_pass.set_pipeline(&self.pipeline); + render_pass.set_bind_group(0, &self.bind_group, &[]); + render_pass.draw(0..6, 0..self.digit_count); + } +} + +/// Bake the glyph atlas for the digits 0 through 9 at the font's true +/// resolution: one 6×8 cell per digit, the 5×7 glyph in its top-left +/// corner, one texel of air to the right and below, lit texels at 255 and +/// the rest at zero, in a single row sixty texels wide. The font is the +/// bitmap below and nothing fancier: ten glyphs of seven rows of five bits, +/// the most significant bit the leftmost column, legible at any integer +/// scale and at no other, which is why no other is ever used. +fn generate_glyph_atlas() -> Vec { + // The font: ten glyphs of seven rows, each row five bits, the most + // significant bit at the left. Read them by squinting. + const PATTERNS: [[u8; 7]; 10] = [ + // 0 + [ + 0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110, + ], + // 1 + [ + 0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110, + ], + // 2 + [ + 0b01110, 0b10001, 0b00001, 0b00110, 0b01000, 0b10000, 0b11111, + ], + // 3 + [ + 0b01110, 0b10001, 0b00001, 0b00110, 0b00001, 0b10001, 0b01110, + ], + // 4 + [ + 0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010, + ], + // 5 + [ + 0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110, + ], + // 6 + [ + 0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110, + ], + // 7 + [ + 0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000, + ], + // 8 + [ + 0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110, + ], + // 9 + [ + 0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100, + ], + ]; + + let mut atlas = vec![0u8; (ATLAS_WIDTH * ATLAS_HEIGHT) as usize]; + for (digit, pattern) in (0u32..).zip(PATTERNS.iter()) { + let cell_x = digit * CELL_WIDTH; + for (y, &bits) in (0u32..).zip(pattern.iter()) { + for col in 0..5u32 { + if (bits >> (4 - col)) & 1 == 1 { + let x = cell_x + col; + atlas[(y * ATLAS_WIDTH + x) as usize] = 255; + } + } + } + } + + atlas +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The font keeps its largest step through 120 digits, steps down once + /// at the 121st, and that step carries the waterfall to the calendar's + /// last digit, the 154th, and on to 200; the third step takes the rest + /// of what the buffer can hold, and nothing falls through to the + /// smallest step at the window's width, which is the fallback nobody + /// is meant to see. + #[test] + fn the_digits_shrink_once_and_only_when_they_must() { + assert_eq!(glyph_scale_for(61, 800), (4, 5)); + assert_eq!(glyph_scale_for(120, 800), (4, 5)); + assert_eq!(glyph_scale_for(121, 800), (3, 4)); + assert_eq!(glyph_scale_for(154, 800), (3, 4)); + assert_eq!(glyph_scale_for(200, 800), (3, 4)); + assert_eq!(glyph_scale_for(201, 800), (2, 3)); + let max = u32::try_from(MAX_DIGITS).expect("two hundred and fifty-six fits a u32"); + assert_eq!(glyph_scale_for(max, 800), (2, 3)); + } + + /// Every step's rows fit the reserve for every count the buffer can + /// hold, at the window's width: the promise `WATERFALL_HEIGHT` makes to + /// the layout beneath it, checked for all 256 counts and not merely the + /// interesting ones. + #[test] + fn every_count_fits_the_reserve() { + let max = u32::try_from(MAX_DIGITS).expect("two hundred and fifty-six fits a u32"); + for count in 1..=max { + let (kx, ky) = glyph_scale_for(count, 800); + let per_row = (800 - 2 * X_MARGIN) / (CELL_WIDTH * kx); + assert!( + count.div_ceil(per_row) * CELL_HEIGHT * ky <= WATERFALL_HEIGHT, + "{count} digits overflow the reserve at the step elected for them" + ); + } + } +} diff --git a/crates/loic-gui/src/shaders/artifact.wgsl b/crates/loic-gui/src/shaders/artifact.wgsl new file mode 100644 index 0000000..5286eaa --- /dev/null +++ b/crates/loic-gui/src/shaders/artifact.wgsl @@ -0,0 +1,84 @@ +// The scar shader of the Loic Observatory. +// +// Renders the topological scars that resolution collapse leaves on the +// surface: the workspace README, section 4.5, for the scars and section +// 7.3 for the collapse. One time in four, the random observer draws a mask +// the lattice cannot hold; the question fails to frame, and what the +// failure leaves is one of three figures, placed at random and never +// removed while the process lives. The GIN gear: a row of twenty-one +// cells whose raised teeth are the set bits of the letters G, I and N in +// seven-bit ASCII, from the seam of the project's logo, at a random +// rotation. The failed mask: a ring with the seven cosmic primes around +// it as dots, filled where the entropy set them, and the phantom eighth +// bit — the one that overflowed the pool — dangling outside the boundary +// in red, on a thin line from where it would have gone. The soliton: +// concentric amber rings fading outward, the project's reading of what a +// severed relation leaves in the weave. Each is a Channel 2 record: not +// what was asked, but that a question was attempted here and could not be +// framed coherently. +// +// The shader knows none of this. It receives vertices already in pixel +// coordinates, each carrying its own RGBA, triangulated by the renderer +// into filled circles, annuli and rotated rectangles; it moves them into +// clip space, with the vertical axis turned over because pixel space +// hangs from the top-left corner and clip space grows upward from the +// centre, and passes each colour through untouched. A scar is drawn last, +// on top of everything, and blocks input on the pixels it covers; that +// policy lives in the renderer and the hit-test, and this file is merely +// where the scar becomes visible. + +// The one uniform: the surface's extent in pixels, by which pixel +// coordinates become clip coordinates. The renderer pads its buffer to +// sixteen bytes for the GPU's sake; the shader reads the first eight. +struct Uniforms { + screen_size: vec2, +}; + +// Bound for the vertex stage alone; the fragment stage has no use for the +// surface's size, or for anything but the colour it is handed. +@group(0) @binding(0) +var uniforms: Uniforms; + +// One vertex as the renderer built it: a position in pixels and a colour +// with its own alpha, straight from a vertex buffer that is rebuilt every +// frame from the list of scars, one draw for all of them. +struct VertexInput { + @location(0) position: vec2, + @location(1) color: vec4, +}; + +// What the vertex stage hands the fragment stage: the position in clip +// space, and the colour, interpolated across each triangle, which for a +// triangle of one colour changes nothing. +struct VertexOutput { + @builtin(position) position: vec4, + @location(0) color: vec4, +}; + +// Vertex stage: pixels into clip space, colour passed through. The scar's +// geometry was decided on the CPU, in pixels, where the hit-test can see +// it; the shader adds nothing to it and takes nothing away. +@vertex +fn vs_main(in: VertexInput) -> VertexOutput { + var out: VertexOutput; + // Horizontal: pixels over width, doubled, less one — minus one at the + // left edge, one at the right. + let clip_x = (in.position.x / uniforms.screen_size.x) * 2.0 - 1.0; + // Vertical: the same, then taken from one, because pixel Y grows + // downward and clip Y grows upward. Flip. + let clip_y = 1.0 - (in.position.y / uniforms.screen_size.y) * 2.0; + out.position = vec4(clip_x, clip_y, 0.0, 1.0); + out.color = in.color; + return out; +} + +// Fragment stage: the interpolated colour, as given. Which colour — the +// white of the teeth, the dim gray of the boundary and of the unset +// primes, the red of the phantom, the amber of the rings, each with its +// own alpha — is the renderer's decision, and the shader has no view on +// it. Alpha blending outside this file lays the scar over whatever it +// covers, which is everything, since it is drawn last. +@fragment +fn fs_main(in: VertexOutput) -> @location(0) vec4 { + return in.color; +} diff --git a/crates/loic-gui/src/shaders/digit.wgsl b/crates/loic-gui/src/shaders/digit.wgsl new file mode 100644 index 0000000..62344f9 --- /dev/null +++ b/crates/loic-gui/src/shaders/digit.wgsl @@ -0,0 +1,258 @@ +// ═══════════════════════════════════════════════════════════════════════════════ +// +// DIGIT SHADER +// +// The waterfall: the cosmic time — Planck times elapsed since Creation, +// sixty-one digits at present and one hundred and fifty-four at +// Annihilation, where 512 bits run out — set as one textured quad per +// digit, most significant first, wrapping within the margins. Six +// vertices per digit are conjured from the vertex index; there is no +// vertex buffer. The digit values arrive in a storage buffer and the ten +// glyphs in an atlas of ten six-by-eight cells, sampled at whole-number +// magnifications with nearest filtering, so that every texel is a crisp +// block and nothing is ever interpolated into being. +// +// Zones are counted from the last digit, because that is where time +// moves, and they stay where they are as the count grows: +// Zone C, the last 34 digits: cyan — the sub-nanosecond entropy, +// fresh with every observation +// Zone B, the 9 before them: gray — nanosecond to second, faster +// than perception +// Zone A, everything above: white — changes slower than once a second +// +// The arithmetic: a nanosecond holds about 1.855 × 10^34 Planck times +// and a second about 1.855 × 10^43, so 10^34 of them fit in a nanosecond +// and 10^43 in a second. The last thirty-four digits therefore turn over +// entirely between one nanosecond and the next, beneath anything the +// kernel's clock can report; what they show is the entropy the library +// draws for the sub-nanosecond remainder, a different answer at every +// observation, and the shader colours them as what they are. The nine +// above them change within a second and are shown as blur. Everything +// above those can be read. The digit count grows with the age of the +// universe; the zones do not. The present moment is a gradient, not a +// point — the workspace README, section 1.3 — and this is the gradient, +// rendered. +// +// Every number in this file is an f32, because the GPU speaks nothing +// else and because nothing computed here is ever read back as time: it +// is a pixel or it is nothing, which is one of the two exemptions the +// calendar grants, the other being the hum. +// +// ═══════════════════════════════════════════════════════════════════════════════ + +// What the renderer tells both stages, once per frame: the surface, the +// cell as magnified this frame, the atlas, how many digits there are and +// where they go, and the clock for the shimmer. Bound at group zero, +// binding zero, and visible to the fragment stage as well as the vertex +// stage, because the shimmer needs the clock. +struct Uniforms { + screen_size: vec2, + glyph_size: vec2, + atlas_size: vec2, + digit_count: u32, + y_offset: u32, // Top of the first row, in pixels: sixty, just below the header + x_margin: u32, // Air at both sides, in pixels: forty, as the timeline's bar keeps + time: f32, // Seconds since the renderer was born, as an f32; for the shimmer only +} + +// What the vertex stage hands the fragment stage, interpolated across the +// quad: the position, the texture coordinate, the zone's colour, and how +// deep into the entropy this digit lies. +struct VertexOutput { + @builtin(position) position: vec4, + @location(0) uv: vec2, + @location(1) color: vec4, + @location(2) glow_intensity: f32, // zero outside zone C, one at the last digit +} + +// The four bindings: the uniforms for both stages, the atlas and its +// nearest-filtering sampler for the fragment stage, and the digits, most +// significant first, for the vertex stage alone. +@group(0) @binding(0) var uniforms: Uniforms; +@group(0) @binding(1) var glyph_texture: texture_2d; +@group(0) @binding(2) var glyph_sampler: sampler; +@group(0) @binding(3) var digits: array; + +// The three colours of the zones. The cyan is the Observatory's own, the +// one the text renderer packs as #33E6CC, to within a rounding of the +// green. +const COLOR_A: vec3 = vec3(1.0, 1.0, 1.0); // white: slower than a second +const COLOR_B: vec3 = vec3(0.5, 0.5, 0.5); // gray: within a second, blur +const COLOR_C: vec3 = vec3(0.2, 0.9, 0.8); // cyan: within a nanosecond, entropy + +// Zone C: the last thirty-four digits. 10^34 Planck times fit in a +// nanosecond, and a nanosecond is the finest thing the clock reports, so +// every one of these digits is the library's entropy, drawn afresh for +// each observation and owed to no clock at all. +const QUANTUM_DIGITS: u32 = 34u; +// Zone B: the nine digits before those, from a nanosecond up to a second, +// 10^43 over 10^34. They change faster than an eye can follow and slower +// than the entropy does, and are coloured accordingly. +const BLUR_DIGITS: u32 = 9u; + +// The distance of a digit from the last one: zero for the last digit +// itself, the count less one for the first. The zones are measured in +// this and never in the index from the front, which is why the count may +// grow without the colours moving. Unsigned arithmetic, so it is only +// ever asked about an index the draw call actually issued. +fn digits_from_end(digit_index: u32) -> u32 { + return uniforms.digit_count - 1u - digit_index; +} + +// The colour of a digit by its distance from the end. Inside zone C it +// runs from the gray of zone B at the zone's first digit to full cyan at +// the last; inside zone B, from the white of zone A at its first digit to +// gray at its last; above both, white. Two ramps with no step between +// them, so that the eye reads one gradient rather than three bands, which +// is what the present moment is. +fn get_zone_color(digit_index: u32) -> vec3 { + let from_end = digits_from_end(digit_index); + if (from_end < QUANTUM_DIGITS) { + // All but gray at the zone's first digit, cyan at the last. + let t = 1.0 - f32(from_end) / f32(QUANTUM_DIGITS); + return mix(COLOR_B, COLOR_C, t); + } else if (from_end < QUANTUM_DIGITS + BLUR_DIGITS) { + // All but white at the zone's first digit, gray at its last. + let t = 1.0 - f32(from_end - QUANTUM_DIGITS) / f32(BLUR_DIGITS); + return mix(COLOR_A, COLOR_B, t); + } + return COLOR_A; +} + +// Vertex stage: one call per corner per digit, six per instance. It +// places the digit's quad on the surface, selects the digit's cell in the +// atlas, and decides the digit's colour and glow by its distance from the +// end, all of which the fragment stage receives interpolated, though only +// the texture coordinate actually varies across a quad. +@vertex +fn vs_main( + @builtin(vertex_index) vertex_index: u32, + @builtin(instance_index) instance_index: u32, +) -> VertexOutput { + var out: VertexOutput; + + // The quad: two triangles, six vertices, drawn from the vertex index + // alone in the unit square, which the cell's size and position will + // stretch into place. The corners, and the order the triangles take + // them in: + // 0--1 Triangles: 0,1,2 and 2,1,3 + // |\ | + // | \| + // 2--3 + let quad_uvs = array, 6>( + vec2(0.0, 0.0), // 0, top-left + vec2(1.0, 0.0), // 1, top-right + vec2(0.0, 1.0), // 2, bottom-left + vec2(0.0, 1.0), // 2, again + vec2(1.0, 0.0), // 1, again + vec2(1.0, 1.0), // 3, bottom-right + ); + + let quad_uv = quad_uvs[vertex_index]; + + // This instance's digit, from the storage buffer, most significant + // first; the vertex stage is the one stage permitted to read it. + let digit_value = digits[instance_index]; + + // Where on the surface this digit lives: the rows wrap within the + // margins, as many digits to a row as whole cells fit the content + // width, and the arithmetic is integer until the pixel. + let margin = f32(uniforms.x_margin); + let content_width = uniforms.screen_size.x - 2.0 * margin; + let chars_per_row = u32(content_width / uniforms.glyph_size.x); + let row = instance_index / chars_per_row; + let col = instance_index % chars_per_row; + + let base_x = margin + f32(col) * uniforms.glyph_size.x; + let base_y = f32(row) * uniforms.glyph_size.y + f32(uniforms.y_offset); + + // The vertex, in pixels: the cell's corner plus the quad's unit + // coordinate scaled to the cell's magnified size. + let pixel_pos = vec2( + base_x + quad_uv.x * uniforms.glyph_size.x, + base_y + quad_uv.y * uniforms.glyph_size.y + ); + + // Into clip space, minus one to one on both axes, the vertical one + // turned over, because pixel space grows downward and clip space grows + // upward, and neither will yield. + let clip_pos = vec2( + (pixel_pos.x / uniforms.screen_size.x) * 2.0 - 1.0, + 1.0 - (pixel_pos.y / uniforms.screen_size.y) * 2.0 // the turning over + ); + + out.position = vec4(clip_pos, 0.0, 1.0); + + // The texture coordinate. The atlas is ten cells in one row, so a + // digit's cell is a tenth of the width, and the whole cell — five + // columns of ink and one of air, eight rows with the last of them air — + // is mapped onto the whole quad, air included, which is what keeps the + // digits apart. + let glyph_width = uniforms.atlas_size.x / 10.0; + let u_start = f32(digit_value) * glyph_width / uniforms.atlas_size.x; + let u_end = u_start + glyph_width / uniforms.atlas_size.x; + + out.uv = vec2( + mix(u_start, u_end, quad_uv.x), + quad_uv.y + ); + + // The zone's colour, by distance from the end, opaque. + out.color = vec4(get_zone_color(instance_index), 1.0); + + // The glow: zero outside zone C, rising through it to one at the last + // digit, and carried to the fragment stage for the shimmer. + let from_end = digits_from_end(instance_index); + if (from_end < QUANTUM_DIGITS) { + out.glow_intensity = 1.0 - f32(from_end) / f32(QUANTUM_DIGITS); + } else { + out.glow_intensity = 0.0; + } + + return out; +} + +// Fragment stage: the zone's colour at the atlas's coverage, and for zone +// C a shimmer on top, since digits that are entropy should not sit still. +@fragment +fn fs_main(in: VertexOutput) -> @location(0) vec4 { + // Coverage from the atlas's one channel, taken nearest, which is the + // pixel's alpha: the air around a glyph is transparent, and the ink is + // as opaque as ink. + let alpha = textureSample(glyph_texture, glyph_sampler, in.uv).r; + + // The shimmer, for zone C alone: the entropy digits glow, and the glow + // breathes. + if (in.glow_intensity > 0.0) { + // Three sines at three angular frequencies — three, seven and + // eleven radians per second — each digit shifted in phase by its + // depth in the zone, so that the glow travels along the digits + // rather than pulsing in unison. Three, seven and eleven are also + // three of the five prime factors of the Unix offset, 5,419,722; no + // mask is stated for that observation, so by the workspace README, + // section 0, it is Channel 1, and it is recorded here only so that + // nobody discovers it later. + let phase_offset = in.glow_intensity * 6.28318; // one full turn, 2π, across the zone + let wave1 = sin(uniforms.time * 3.0 + phase_offset) * 0.5 + 0.5; + let wave2 = sin(uniforms.time * 7.0 + phase_offset * 1.7) * 0.5 + 0.5; + let wave3 = sin(uniforms.time * 11.0 + phase_offset * 2.3) * 0.5 + 0.5; + + // The three waves, weighted to sum to one, so that the shimmer lies + // between zero and one and the weights say which wave leads. + let shimmer = wave1 * 0.5 + wave2 * 0.3 + wave3 * 0.2; + + // Deeper into the zone, stronger: the last digit may brighten by + // forty percent, the zone's first by almost nothing. + let glow_strength = in.glow_intensity * 0.4; // at most a forty percent boost + let brightness_boost = 1.0 + shimmer * glow_strength; + + // Brightened, and clamped at one per channel; the target would + // clamp it anyway, but the shader prefers to say so itself. + let glowing_color = min(in.color.rgb * brightness_boost, vec3(1.0, 1.0, 1.0)); + + return vec4(glowing_color, alpha); + } + + // Zones A and B: the colour, unshimmering, at the coverage. + return vec4(in.color.rgb, alpha); +} diff --git a/crates/loic-gui/src/shaders/overlay.wgsl b/crates/loic-gui/src/shaders/overlay.wgsl new file mode 100644 index 0000000..77079e7 --- /dev/null +++ b/crates/loic-gui/src/shaders/overlay.wgsl @@ -0,0 +1,70 @@ +// The veil of the Loic Observatory. +// +// This shader concerns itself with one task, monumental in the way that +// only the simplest tasks are: drawing a rectangle. Not any rectangle — a +// rectangle the size of the surface, in one colour at one alpha, blended +// over whatever the pass has already drawn, so that a passage may be read +// against a dimmed field rather than against the temporal cacophony. It +// has no texture, no vertex buffer, no attributes and no opinions; it is +// given a colour and it returns the colour, for every fragment, without +// looking. +// +// The colour it is given, unless someone asks otherwise, is the surface's +// own clear colour at eighty-five percent alpha: a shroud the exact shade +// of the void behind it. And in the Observatory's composition, while a +// passage is open the waterfall, the panels and the scars are not drawn at +// all, so the veil is blended over the cleared void alone and dims a field +// that was never lit. The dimming is real. Its subject is absent. The +// shader is not told this, and would not change its behaviour if it were: +// the rectangle is drawn, at the alpha requested, with perfect fidelity to +// an instruction whose consequence is invisible, which is a fate the +// calendar recognises. + +// All the vertex stage has to say: a position. There is no colour to +// carry and no coordinate to sample by; the fragment stage has the +// uniform, and needs nothing from the vertex but where it is. +struct VertexOutput { + @builtin(position) position: vec4, +}; + +// The one uniform: the veil's colour — red, green, blue and alpha, each +// from zero to one — bound for the fragment stage alone. A humble vec4 +// bearing the entire weight of the shader's output, since the output is +// this and nothing else. +@group(0) @binding(0) +var overlay_color: vec4; + +// Vertex stage: six positions drawn from the vertex index alone, no +// buffer consulted — the corners of clip space, minus one to one on both +// axes, as two triangles: bottom-left, bottom-right, top-left; then +// top-left, bottom-right, top-right. The pair covers the surface exactly, +// whatever its size, because clip space is the same size on every +// surface, which is the one convenience the GPU offers without being +// asked. +@vertex +fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput { + // The corners, in clip space, where up is up and no turning over is + // owed. + var positions = array, 6>( + vec2(-1.0, -1.0), // bottom-left + vec2( 1.0, -1.0), // bottom-right + vec2(-1.0, 1.0), // top-left, closing the first triangle + vec2(-1.0, 1.0), // top-left again, opening the second + vec2( 1.0, -1.0), // bottom-right again + vec2( 1.0, 1.0), // top-right + ); + + var output: VertexOutput; + output.position = vec4(positions[vertex_index], 0.0, 1.0); + return output; +} + +// Fragment stage: the uniform colour, for every fragment, unconditionally. +// No sampling, no arithmetic, no cleverness; the blend state outside this +// file does the dimming, weighting by the alpha this colour carries, and +// the shader's whole contribution is to hold one opinion about one colour +// across the entire surface. +@fragment +fn fs_main(in: VertexOutput) -> @location(0) vec4 { + return overlay_color; +} diff --git a/crates/loic-gui/src/shaders/text.wgsl b/crates/loic-gui/src/shaders/text.wgsl new file mode 100644 index 0000000..792492b --- /dev/null +++ b/crates/loic-gui/src/shaders/text.wgsl @@ -0,0 +1,140 @@ +// ═══════════════════════════════════════════════════════════════════════════════ +// +// TEXT SHADER +// +// The lettering of the Observatory: every run of characters, set as one +// textured quad per character from a grayscale atlas of one hundred and +// twelve cells, sixteen to a row, seven rows. Each instance is sixteen +// bytes from a storage buffer — a position in pixels, a cell index and a +// packed colour — and each becomes six vertices conjured from the vertex +// index, since there is no vertex buffer and none is missed. The atlas +// is sampled linearly at exactly one texel per pixel, which is a copy +// when the position is whole and a half-pixel smear when it is not. +// +// The floating point is the GPU's, not the calendar's: nothing computed +// here is a quantity of time, and nothing leaves but a pixel. +// +// ═══════════════════════════════════════════════════════════════════════════════ + +// What the renderer tells the vertex stage, once per resize: the surface's +// extent, the cell's, and the atlas's grid. Twenty-four bytes, the mirror +// of the renderer's own `Uniforms`, and the fragment stage never sees them. +struct Uniforms { + screen_size: vec2, + glyph_size: vec2, + atlas_cols: u32, + atlas_rows: u32, +} + +// One character, sixteen bytes, exactly as the renderer packed it. +struct CharInstance { + pos: vec2, // The cell's top-left, in pixels from the surface's top-left + glyph_index: u32, // The cell in the atlas, 0 through 111 + color: u32, // RGBA, one byte each, red in the high byte +} + +// What the vertex stage hands the fragment stage: the position, the +// texture coordinate, and the colour, the last of which is the same at all +// four corners and so survives interpolation unchanged. +struct VertexOutput { + @builtin(position) position: vec4, + @location(0) uv: vec2, + @location(1) color: vec4, +} + +// The four bindings: the uniforms for the vertex stage, the atlas and its +// linear sampler for the fragment stage, and the instances for the vertex +// stage. +@group(0) @binding(0) var uniforms: Uniforms; +@group(0) @binding(1) var glyph_texture: texture_2d; +@group(0) @binding(2) var glyph_sampler: sampler; +@group(0) @binding(3) var chars: array; + +// The packed colour undone: three shifts and four masks, each byte scaled +// to the interval from zero to one. Red was packed highest and alpha +// lowest, and the order here is the same order, or every colour on the +// surface would be some other colour. +fn unpack_color(packed: u32) -> vec4 { + let r = f32((packed >> 24u) & 0xFFu) / 255.0; + let g = f32((packed >> 16u) & 0xFFu) / 255.0; + let b = f32((packed >> 8u) & 0xFFu) / 255.0; + let a = f32(packed & 0xFFu) / 255.0; + return vec4(r, g, b, a); +} + +// Vertex stage: one call per corner per character, six per instance. It +// places the character's quad on the surface, finds its cell in the atlas +// by a modulus and a quotient, and unpacks its colour. +@vertex +fn vs_main( + @builtin(vertex_index) vertex_index: u32, + @builtin(instance_index) instance_index: u32, +) -> VertexOutput { + var out: VertexOutput; + + // This instance: the character's position, cell and colour. + let char_data = chars[instance_index]; + + // The quad: two triangles in the unit square, six vertices from the + // vertex index, corners 0,1,2 and then 2,1,3. + let quad_uvs = array, 6>( + vec2(0.0, 0.0), + vec2(1.0, 0.0), + vec2(0.0, 1.0), + vec2(0.0, 1.0), + vec2(1.0, 0.0), + vec2(1.0, 1.0), + ); + + let quad_uv = quad_uvs[vertex_index]; + + // The vertex, in pixels: the cell's corner plus the unit coordinate + // scaled to the cell, which is the atlas cell's own size, always. + let pixel_pos = vec2( + char_data.pos.x + quad_uv.x * uniforms.glyph_size.x, + char_data.pos.y + quad_uv.y * uniforms.glyph_size.y + ); + + // Into clip space, minus one to one, the vertical axis turned over, + // because pixels grow downward and clip space grows upward. + let clip_pos = vec2( + (pixel_pos.x / uniforms.screen_size.x) * 2.0 - 1.0, + 1.0 - (pixel_pos.y / uniforms.screen_size.y) * 2.0 + ); + + out.position = vec4(clip_pos, 0.0, 1.0); + + // The texture coordinate: the cell's column is the index modulo the + // column count and its row the quotient, and each cell is one + // sixteenth of the atlas across and one seventh of it down. + let col = char_data.glyph_index % uniforms.atlas_cols; + let row = char_data.glyph_index / uniforms.atlas_cols; + let u_size = 1.0 / f32(uniforms.atlas_cols); + let v_size = 1.0 / f32(uniforms.atlas_rows); + + let u_start = f32(col) * u_size; + let v_start = f32(row) * v_size; + + out.uv = vec2( + u_start + quad_uv.x * u_size, + v_start + quad_uv.y * v_size + ); + + // The colour, unpacked once per vertex; the four corners agree, so the + // interpolation between them has nothing to do. + out.color = unpack_color(char_data.color); + + return out; +} + +// Fragment stage: the atlas's coverage, sampled linearly from its single +// channel, multiplied into the colour's own alpha, so that a glyph's ink +// is as opaque as its colour says and its air is transparent whatever the +// colour says. The colour is not sampled from anything; it arrives with +// the instance and is applied to the coverage as ink to a stencil, which +// is exactly what a bitmap font is. +@fragment +fn fs_main(in: VertexOutput) -> @location(0) vec4 { + let alpha = textureSample(glyph_texture, glyph_sampler, in.uv).r; + return vec4(in.color.rgb, in.color.a * alpha); +} diff --git a/crates/loic-gui/src/text.rs b/crates/loic-gui/src/text.rs new file mode 100644 index 0000000..efa764f --- /dev/null +++ b/crates/loic-gui/src/text.rs @@ -0,0 +1,1176 @@ +//! The lettering engine of the Loic Observatory: every word, bracket, +//! caption and pointer the instrument utters in characters rather than in +//! the waterfall's digits, which have a renderer and an atlas of their own. +//! +//! The Observatory does not borrow a font. It bakes one, at start-up, from +//! hand-drawn five-by-seven bitmaps into a single grayscale atlas texture, +//! and thereafter sets text by instancing: one quad per character, six +//! vertices conjured from the vertex index alone, the glyph's cell located +//! in the atlas by integer division and its colour unpacked from a single +//! `u32`. No vertex buffer, no hinting, no kerning, and no antialiasing +//! beyond what a linear sampler smears across a half-pixel boundary. The +//! result is the terminal aesthetic of the era the epoch belongs to, which +//! is not an affectation but a consequence: a machine that counts Planck +//! times has no business outsourcing the shapes of its numerals. +//! +//! The repertoire is printable ASCII, codepoints 32 through 126, space +//! through tilde, with DEL at 127 owning a cell in the atlas and no ink in +//! it; plus sixteen guests from beyond seven bits, each drawn by hand in +//! the same grid: the down-pointing triangle ▼ (U+25BC) that marks "You +//! are here" at the timeline's Creation end; the superscript digits ⁰ +//! through ⁹ and the superscript minus ⁻, for the exponents in the +//! passages; the multiplication sign × that joins the primes of a mask's +//! name and the division sign ÷ that names a wheel's children; the em dash +//! —; and the bullet •, which the sermon's layout knows how to wrap under. +//! A character outside this repertoire is not drawn, not substituted and +//! not reported: its cell is left blank and the pen advances past it, which +//! is the atlas's way of saying that it was not consulted. + +use wgpu::util::DeviceExt; + +/// The ceiling on glyphs per draw: the number of `CharInstance` slots the +/// storage buffer is born with, and the number the frame's instance list +/// may reach before `render` stops listening. +/// +/// Two thousand and forty-eight is the eleventh power of two, which makes +/// the buffer's thirty-two kibibytes a tidy multiple of every alignment a +/// GPU has ever asked for, and it is more cells than the surface has room +/// to show: a full frame — the header, both wheels, the timeline with its +/// eight event lines, three rows of the progress decimal and three +/// coordinate cards — is some hundreds of glyphs. Should a frame +/// nonetheless overrun it, the two-thousand-and-forty-ninth glyph and every +/// one after it are simply not drawn. No error, no wrapping, no second +/// draw; the text ends where the buffer does, as the calendar ends where +/// 512 bits do. +const MAX_CHARS: usize = 2048; + +/// The width of one glyph cell in pixels, and therefore the pen's advance +/// from one character to the next at scale one. +/// +/// A cell is twelve by twenty. The five-by-seven pattern inside it is +/// enlarged by whole numbers only — `GLYPH_WIDTH / 6` and +/// `GLYPH_HEIGHT / 8`, both of which come to two, the second by integer +/// division discarding a half it was never going to use — so that every +/// bit of a pattern becomes a square block of two by two pixels and +/// nothing is interpolated into existence. The ink therefore occupies ten +/// by fourteen pixels, set one pixel in from the left and one down from +/// the top: one pixel of air on the left, one on the right, one above, and +/// five below, which is the line's breathing room, since nothing in this +/// font descends. A fractional scale would have had to be sampled, and +/// sampling is where a bitmap goes to blur. +const GLYPH_WIDTH: u32 = 12; +/// The height of one glyph cell in pixels: the row pitch of the atlas and +/// the height of every quad the shader draws. Twenty, of which fourteen +/// may be ink and the bottom five never are. The arithmetic is under +/// `GLYPH_WIDTH`. +const GLYPH_HEIGHT: u32 = 20; + +/// The atlas's columns: sixteen cells to a row, so that a glyph index +/// splits into column and row by a modulus and a quotient by sixteen, +/// which any compiler worth its silicon reduces to a mask of four bits and +/// a shift of four, in the vertex shader and here alike. +/// +/// The atlas is sixteen columns by seven rows, one hundred and twelve +/// cells, every one of them spoken for. Rows zero through five hold the +/// ninety-six cells of ASCII 32 through 127 in codepoint order, ninety-five +/// of them drawn and the last, DEL, an honest rectangle of nothing. Row +/// six holds the sixteen guests, indices 96 through 111, in the order the +/// constants below assign them. Ninety-six is six rows exactly and sixteen +/// guests are one row exactly; there is no slack anywhere in this atlas, +/// and there was never meant to be. +const ATLAS_COLS: u32 = 16; +/// The atlas's rows: six of ASCII and one of guests. See `ATLAS_COLS`. +const ATLAS_ROWS: u32 = 7; +/// The atlas's width in texels: one hundred and ninety-two, twelve per +/// cell. +const ATLAS_WIDTH: u32 = GLYPH_WIDTH * ATLAS_COLS; +/// The atlas's height in texels: one hundred and forty, twenty per cell. +/// One byte per texel, `R8Unorm`, the value being coverage and nothing +/// else; colour is the instance's business, not the atlas's. +const ATLAS_HEIGHT: u32 = GLYPH_HEIGHT * ATLAS_ROWS; + +/// The glyph indices of the sixteen guests: the codepoints beyond seven +/// bits that the Observatory has occasion to set, each mapped by `render` +/// to a cell in row six of the atlas. The indices begin at ninety-six, +/// immediately after DEL's empty cell, and run to one hundred and eleven, +/// the last cell of the last row; there is no room for a seventeenth guest +/// without a new row, and no seventeenth guest has asked. The order is the +/// order of `get_extended_patterns`, which is the order of these constants, +/// and the two must never disagree, because the atlas is baked from the one +/// and the text is looked up by the other. +const GLYPH_DOWN_TRIANGLE: u32 = 96; // ▼ U+25BC, the timeline's "You are here" +const GLYPH_SUPERSCRIPT_0: u32 = 97; // ⁰ U+2070, the first of the raised digits +const GLYPH_SUPERSCRIPT_1: u32 = 98; // ¹ U+00B9, a Latin-1 stray among them +const GLYPH_SUPERSCRIPT_2: u32 = 99; // ² U+00B2, likewise Latin-1 +const GLYPH_SUPERSCRIPT_3: u32 = 100; // ³ U+00B3, the last of the Latin-1 three +const GLYPH_SUPERSCRIPT_4: u32 = 101; // ⁴ U+2074, back in the superscripts block +const GLYPH_SUPERSCRIPT_5: u32 = 102; // ⁵ U+2075 +const GLYPH_SUPERSCRIPT_6: u32 = 103; // ⁶ U+2076 +const GLYPH_SUPERSCRIPT_7: u32 = 104; // ⁷ U+2077 +const GLYPH_SUPERSCRIPT_8: u32 = 105; // ⁸ U+2078 +const GLYPH_SUPERSCRIPT_9: u32 = 106; // ⁹ U+2079, the last of the raised digits +const GLYPH_SUPERSCRIPT_MINUS: u32 = 107; // ⁻ U+207B, for the negative exponents +const GLYPH_MULTIPLICATION: u32 = 108; // × U+00D7, the join in a mask's name +const GLYPH_EM_DASH: u32 = 109; // — U+2014, drawn as the hyphen is drawn +const GLYPH_BULLET: u32 = 110; // • U+2022, the marker the sermon's layout wraps under +const GLYPH_DIVISION: u32 = 111; // ÷ U+00F7, the edge to a wheel's child + +/// One character as the GPU receives it: sixteen bytes, laid out in C order +/// so that they are the same sixteen bytes the shader's `CharInstance` +/// reads from the storage buffer, and marked `Pod` because `bytemuck` is +/// asked to regard a slice of these as a slice of bytes without further +/// discussion. Position, glyph, colour; the size of the quad is not here, +/// because every quad is the size of the cell and the shader takes that +/// from the uniform. +#[repr(C)] +#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] +struct CharInstance { + /// The top-left corner of the cell, in pixels from the surface's + /// top-left, as two floats, which the layout may set on a half pixel; + /// the linear sampler then spreads the glyph across two pixels to show + /// for it. + pos: [f32; 2], + /// The cell in the atlas, zero through one hundred and eleven: the + /// codepoint less thirty-two for ASCII, a constant from above for a + /// guest. + glyph_index: u32, + /// The colour, packed by `Color::pack` as red in the high byte, then + /// green, then blue, then alpha in the low byte, to be unpacked by the + /// shader in the same order. + color: u32, +} + +/// What the vertex shader is told about the world, once per resize rather +/// than once per glyph: twenty-four bytes in C order, the mirror of the +/// shader's `Uniforms`, uploaded when the surface takes a shape and read +/// by every vertex of every character thereafter. The fragment stage is +/// not shown these; it has a texture, a sampler and an interpolated +/// colour, and needs nothing else to decide what a pixel is. +#[repr(C)] +#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] +struct Uniforms { + /// The surface's extent in pixels, by which pixel positions are turned + /// into the clip space the GPU insists on, from minus one to one, with + /// its vertical axis pointing the other way. + screen_size: [f32; 2], + /// The cell's extent in pixels, twelve by twenty, which is also the + /// size of every quad drawn: the atlas is sampled at one texel per + /// pixel and never otherwise. + glyph_size: [f32; 2], + /// Sixteen: the modulus that splits a glyph index into its column, and + /// the divisor of the atlas's horizontal texture coordinate. + atlas_cols: u32, + /// Seven: the divisor of the atlas's vertical texture coordinate. + atlas_rows: u32, +} + +/// A colour as the Observatory names one: four channels of eight bits, +/// red, green, blue and alpha, which is the entire chromatic vocabulary of +/// an instrument that has exactly four things to say in colour and says +/// them with the four constants below. A `Color` is packed into one `u32` +/// on its way to the GPU and unpacked by the shader into four floats +/// between zero and one, at which point it has left the calendar's +/// jurisdiction and may be as approximate as it likes. +#[derive(Copy, Clone)] +pub struct Color { + /// Red, zero through two hundred and fifty-five. + pub r: u8, + /// Green, likewise. + pub g: u8, + /// Blue, likewise. + pub b: u8, + /// Alpha: opacity, which the shader multiplies by the atlas's coverage + /// so that a glyph's air is transparent whatever its ink is. + pub a: u8, +} + +impl Color { + /// White: the colour of the values — the selection on a wheel, the + /// number on a card, the body of a passage and of the sermon. What the + /// Observatory is saying, as opposed to what it is labelling. + pub const WHITE: Color = Color { + r: 255, + g: 255, + b: 255, + a: 255, + }; + /// Gray, half of everything: the colour of captions, hints, the + /// neighbours on a wheel, the timeline's bar and the progress decimal. + /// The colour of what can be read but need not be. + pub const GRAY: Color = Color { + r: 128, + g: 128, + b: 128, + a: 255, + }; + /// Cyan, `#33E6CC`: the terminal's phosphor, chosen for its visibility + /// on a near-black ground. The header's rates, each wheel's + /// `pos n/total`, the breadcrumb's newest fraction and the timeline's + /// span label wear it, and so, to within a rounding of the green, does + /// the last digit of the waterfall, whose shader mixes toward the same + /// three numbers over two hundred and fifty-five. + pub const CYAN: Color = Color { + r: 51, + g: 230, + b: 204, + a: 255, + }; + /// Amber, `#FFBF00`: the glow of a monochrome cathode-ray tube, warm + /// where the cyan is cold. Titles and headers, the random button, the + /// event markers and their names, the sermon's first line: what is + /// labelled, and what can be pressed. + pub const AMBER: Color = Color { + r: 255, + g: 191, + b: 0, + a: 255, + }; + + /// Compresses the four channels into one `u32`, red in the topmost + /// byte and alpha in the lowest — `0xRRGGBBAA` — which is the layout + /// the shader's `unpack_color` undoes with three shifts and four masks. + /// The alternative, four floats per instance, would have doubled the + /// instance to thirty-two bytes to carry the same information at a + /// precision no monitor can display; a byte per channel is already + /// more than the phosphor knows. + fn pack(self) -> u32 { + (u32::from(self.r) << 24) + | (u32::from(self.g) << 16) + | (u32::from(self.b) << 8) + | u32::from(self.a) + } +} + +/// One run of text, to be set at one position in one colour: the unit the +/// Observatory's layout code speaks in and the unit `render` consumes. A +/// run is not a line — nothing here wraps, and a run that leaves the +/// surface leaves it — and it is not a word; it is whatever the caller +/// found convenient to position, from a single `^` on the timeline to a +/// row of the progress decimal sixty digits long. +pub struct TextItem { + /// The characters, in order. Those in the atlas's repertoire are + /// drawn; the others advance the pen and leave nothing behind. + pub text: String, + /// The left edge of the first cell, in pixels from the surface's left. + pub x: f32, + /// The top edge of every cell in the run, in pixels from the surface's + /// top; a run is one row tall, always. + pub y: f32, + /// The colour of every glyph in the run. One run, one colour; a caption + /// that needs two colours is two runs. + pub color: Color, + /// The multiplier on the pen's advance from one cell to the next, and + /// on nothing else. At scale one the pen moves twelve pixels per + /// character; at `1.2` it moves fourteen and two fifths, and the + /// glyphs, which are drawn at the cell's size regardless, are set with + /// more air between them rather than made larger; at `0.8` they are set + /// closer, the ink of a full-width glyph overlapping the next by four + /// tenths of a pixel. The layout code measures text by this same + /// advance, so a scaled run is centred correctly for the width it + /// actually occupies. What a scale of two would produce is a loosely + /// tracked line of small letters, which is why nothing asks for one. + pub scale: f32, +} + +/// The renderer: one pipeline, one bind group, two buffers, and the extent +/// it was last told, which together are everything required to turn a +/// slice of `TextItem` values into one instanced draw call per frame. +/// Constructed once, when the surface exists, and never again. +pub struct TextRenderer { + /// The pipeline: the vertex and fragment stages of `text.wgsl`, a + /// triangle list with no vertex buffer, alpha blended into the + /// surface's format. + pipeline: wgpu::RenderPipeline, + /// The four bindings the shader sees: the uniforms, the atlas, its + /// sampler and the instance buffer, in that order. + bind_group: wgpu::BindGroup, + /// The `Uniforms`, rewritten on resize and at no other time. + uniform_buffer: wgpu::Buffer, + /// `MAX_CHARS` slots of `CharInstance`, rewritten from the front on + /// every draw; whatever lies beyond the frame's count is stale and + /// never read, because the draw call names the count. + char_buffer: wgpu::Buffer, + /// The surface's extent as last reported to `resize`, kept by the + /// renderer for its own record; the shader takes its geometry from the + /// uniform buffer, and nothing in this module reads the record back. + screen_size: (f32, f32), +} + +impl TextRenderer { + /// Brings the renderer into being on the given device: bakes the atlas, + /// lifts it into a texture, binds a sampler to it, allocates the uniform + /// and instance buffers, ties the four into a bind group, compiles + /// `text.wgsl` and assembles the pipeline that draws with it. Every + /// step needs the one before, which is why they are one function. + /// + /// The uniforms are born with a placeholder extent of twelve hundred by + /// eight hundred, which is not the window and is not meant to be: the + /// Observatory calls `resize` before its first frame, and the + /// placeholder is never seen. A renderer that guessed the window's + /// shape would be no more correct on the second window than on the + /// first. + /// + /// The sampler filters linearly, clamped at the edges. Every quad is + /// exactly the cell's size, so a glyph set on whole pixels is copied + /// texel for texel and a glyph set on a half pixel is spread across two, + /// which is the closest thing to antialiasing this font will ever get. + /// + /// # Returns + /// + /// The renderer, ready to draw and with nothing yet to draw. + #[allow( + clippy::too_many_lines, + reason = "GPU initialisation is one linear liturgy — atlas, texture, sampler, buffers, bind group, pipeline — each rite requiring the last; carved into five functions it would be five places to read one paragraph, and the paragraph would be no shorter" + )] + pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, format: wgpu::TextureFormat) -> Self { + // Bake the atlas: one hundred and twelve cells of coverage, from + // bitmaps, at every start-up, since nothing about it can change. + let atlas_data = generate_text_atlas(); + + // Lift it onto the device as a single-channel texture, one byte a + // texel, to be sampled forever and written exactly once. + let atlas_texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("text_atlas"), + size: wgpu::Extent3d { + width: ATLAS_WIDTH, + height: ATLAS_HEIGHT, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::R8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + + queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture: &atlas_texture, + mip_level: 0, + origin: wgpu::Origin3d::ZERO, + aspect: wgpu::TextureAspect::All, + }, + &atlas_data, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(ATLAS_WIDTH), + rows_per_image: Some(ATLAS_HEIGHT), + }, + wgpu::Extent3d { + width: ATLAS_WIDTH, + height: ATLAS_HEIGHT, + depth_or_array_layers: 1, + }, + ); + + let atlas_view = atlas_texture.create_view(&wgpu::TextureViewDescriptor::default()); + + let atlas_sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("text_sampler"), + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + + // The uniforms, with the placeholder extent that `resize` overwrites + // before anyone looks. + let uniforms = Uniforms { + screen_size: [1200.0, 800.0], + glyph_size: [GLYPH_WIDTH as f32, GLYPH_HEIGHT as f32], + atlas_cols: ATLAS_COLS, + atlas_rows: ATLAS_ROWS, + }; + + let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("text_uniforms"), + contents: bytemuck::cast_slice(&[uniforms]), + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + }); + + // The instance buffer, filled to its ceiling with blank instances + // so that it has a size, and rewritten from the front on every draw. + let chars = vec![ + CharInstance { + pos: [0.0, 0.0], + glyph_index: 0, + color: 0 + }; + MAX_CHARS + ]; + let char_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("text_chars"), + contents: bytemuck::cast_slice(&chars), + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + }); + + // The shape of what the shader sees: the uniforms for the vertex + // stage, the texture and its sampler for the fragment stage, the + // instances for the vertex stage; bindings zero through three. + let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("text_bind_group_layout"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + multisampled: false, + view_dimension: wgpu::TextureViewDimension::D2, + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 3, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: true }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + ], + }); + + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("text_bind_group"), + layout: &bind_group_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: uniform_buffer.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&atlas_view), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::Sampler(&atlas_sampler), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: char_buffer.as_entire_binding(), + }, + ], + }); + + // One bind group and no immediates: the whole of the pipeline's + // interface with the world. + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("text_pipeline_layout"), + bind_group_layouts: &[Some(&bind_group_layout)], + immediate_size: 0, + }); + + // The shader, compiled into the binary at build time; it cannot be + // missing at run time, only wrong. + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("text_shader"), + source: wgpu::ShaderSource::Wgsl(include_str!("shaders/text.wgsl").into()), + }); + + // The pipeline: six vertices per instance as a triangle list, no + // vertex buffer, alpha blended into whatever format the surface + // turned out to speak. + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("text_pipeline"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_main"), + buffers: &[], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: Some(wgpu::BlendState::ALPHA_BLENDING), + write_mask: wgpu::ColorWrites::ALL, + })], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }), + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + ..Default::default() + }, + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + multiview_mask: None, + cache: None, + }); + + Self { + pipeline, + bind_group, + uniform_buffer, + char_buffer, + screen_size: (1200.0, 800.0), + } + } + + /// Informs the renderer of the surface's extent: the record is updated + /// and the uniforms are rewritten in place, after which every vertex + /// is projected into the new clip space. Nothing else changes; the cell + /// is twelve by twenty on a surface of any size, because the + /// Observatory's text does not scale with its window, it reflows. + /// Called once before the first frame, and again whenever the + /// compositor has opinions about the window's shape, which on a window + /// declared non-resizable is seldom, and is not never. + pub fn resize(&mut self, queue: &wgpu::Queue, width: u32, height: u32) { + self.screen_size = (width as f32, height as f32); + let uniforms = Uniforms { + screen_size: [width as f32, height as f32], + glyph_size: [GLYPH_WIDTH as f32, GLYPH_HEIGHT as f32], + atlas_cols: ATLAS_COLS, + atlas_rows: ATLAS_ROWS, + }; + queue.write_buffer(&self.uniform_buffer, 0, bytemuck::cast_slice(&[uniforms])); + } + + /// Sets every run in `items` onto the current render pass in one + /// instanced draw: each character becomes a `CharInstance`, the + /// instances are written to the front of the instance buffer, and six + /// vertices are drawn for each of them. Nothing is returned; the + /// instance count is the draw call's business, and the caller has no + /// use for it. + /// + /// The pen moves left to right through each run, advancing by the cell + /// width times the run's scale for every character whether or not it + /// was drawn. A character in the repertoire yields an instance; one + /// outside it yields a gap. The ceiling is `MAX_CHARS` instances across + /// all runs together: at the ceiling the current run stops mid-word and + /// every later run is passed over entirely, each abandoned at its first + /// character. Silence, not error. + /// + /// A frame with no characters at all is not drawn: no upload, no draw + /// call, nothing for the GPU to decline. A frame with fewer than four + /// is padded to four with instances that are invisible twice over — + /// glyph zero is the space, and a packed colour of zero has an alpha of + /// zero — a precaution against the very small buffer, which some GPUs + /// take worse than a large one and which costs forty-eight bytes at + /// most to avoid. + /// + /// # Panics + /// + /// Never in practice. The instance count is converted to a `u32` for + /// the draw call, and the conversion is checked; it could fail only if + /// the count exceeded four billion, and the count cannot exceed two + /// thousand and forty-eight, so the check is a proof written as a + /// panic, which is the calendar's preferred form of proof. + pub fn render<'a>( + &'a self, + queue: &wgpu::Queue, + render_pass: &mut wgpu::RenderPass<'a>, + items: &[TextItem], + ) { + let mut instances = Vec::with_capacity(MAX_CHARS); + + for item in items { + let scaled_width = GLYPH_WIDTH as f32 * item.scale; + let mut x = item.x; + + for ch in item.text.chars() { + if instances.len() >= MAX_CHARS { + break; + } + + // The pen consults the atlas: ASCII by subtraction, the + // guests by name, anything else by silence. + let glyph_index = match ch { + // ASCII 32 through 127 is the atlas's first ninety-six + // cells in order, DEL's among them, empty and honest. + c if (c as u32) >= 32 && (c as u32) < 128 => Some((c as u32) - 32), + // The guests, by name; first the timeline's pointer. + '▼' => Some(GLYPH_DOWN_TRIANGLE), // U+25BC + // The raised digits, for the passages' powers of ten. + '⁰' => Some(GLYPH_SUPERSCRIPT_0), // U+2070 + '¹' => Some(GLYPH_SUPERSCRIPT_1), // U+00B9 + '²' => Some(GLYPH_SUPERSCRIPT_2), // U+00B2 + '³' => Some(GLYPH_SUPERSCRIPT_3), // U+00B3 + '⁴' => Some(GLYPH_SUPERSCRIPT_4), // U+2074 + '⁵' => Some(GLYPH_SUPERSCRIPT_5), // U+2075 + '⁶' => Some(GLYPH_SUPERSCRIPT_6), // U+2076 + '⁷' => Some(GLYPH_SUPERSCRIPT_7), // U+2077 + '⁸' => Some(GLYPH_SUPERSCRIPT_8), // U+2078 + '⁹' => Some(GLYPH_SUPERSCRIPT_9), // U+2079 + '⁻' => Some(GLYPH_SUPERSCRIPT_MINUS), // U+207B + // The signs of the lattice, and of the prose. + '×' => Some(GLYPH_MULTIPLICATION), // U+00D7 + '—' => Some(GLYPH_EM_DASH), // U+2014 + '•' => Some(GLYPH_BULLET), // U+2022 + '÷' => Some(GLYPH_DIVISION), // U+00F7 + _ => None, + }; + + if let Some(idx) = glyph_index { + instances.push(CharInstance { + pos: [x, item.y], + glyph_index: idx, + color: item.color.pack(), + }); + } + x += scaled_width; + } + } + + if instances.is_empty() { + return; + } + + // Fewer than four instances are padded to four with instances that + // are invisible twice over — glyph zero is the space, and a packed + // colour of zero has an alpha of zero — a precaution against the + // very small buffer, which some GPUs take worse than a large one. + while instances.len() < 4 { + instances.push(CharInstance { + pos: [0.0, 0.0], + glyph_index: 0, + color: 0, + }); + } + + let char_count = u32::try_from(instances.len()).expect("MAX_CHARS is 2048; u32 is vast"); + queue.write_buffer(&self.char_buffer, 0, bytemuck::cast_slice(&instances)); + + render_pass.set_pipeline(&self.pipeline); + render_pass.set_bind_group(0, &self.bind_group, &[]); + render_pass.draw(0..6, 0..char_count); + } +} + +/// Bakes the atlas: one hundred and ninety-two by one hundred and forty +/// bytes, zero for air and two hundred and fifty-five for ink, with the +/// ninety-five ASCII patterns rendered into cells zero through ninety-four, +/// cell ninety-five left to DEL and the dark, and the sixteen guests +/// rendered into cells ninety-six through one hundred and eleven. Every +/// pattern is enlarged by the same two integer factors, computed once here +/// from the cell's size and the pattern's, so that the font has one scale +/// and not a scale per glyph. +/// +/// # Returns +/// +/// The texels, row-major, top row first, ready for `write_texture` with a +/// row pitch equal to the atlas's width, there being no padding to account +/// for when a texel is one byte. +fn generate_text_atlas() -> Vec { + let mut atlas = vec![0u8; (ATLAS_WIDTH * ATLAS_HEIGHT) as usize]; + + // The bitmaps: ninety-five for ASCII and sixteen for the guests, each + // seven rows of five bits. + let patterns = get_font_patterns(); + let extended = get_extended_patterns(); + + let scale_x = GLYPH_WIDTH / 6; // twelve over six: five columns and one of air + let scale_y = GLYPH_HEIGHT / 8; // twenty over eight, floored: seven rows and one of air + + // ASCII, into cells zero onward, in codepoint order. + for (idx, pattern) in (0u32..).zip(patterns.iter()) { + render_glyph_pattern(&mut atlas, idx, *pattern, scale_x, scale_y); + } + + // The guests, into cells ninety-six onward, in the order of their + // constants. + for (idx, pattern) in (96u32..).zip(extended.iter()) { + render_glyph_pattern(&mut atlas, idx, *pattern, scale_x, scale_y); + } + + atlas +} + +/// Renders one pattern into one cell of the atlas: the cell is found from +/// the index by a modulus and a quotient by sixteen, exactly as the vertex +/// shader will find it again, and each set bit of each row becomes a +/// `scale_x` by `scale_y` block of full-coverage texels, offset one texel +/// right and one down, so that the ink never touches the cell's edge and +/// the linear sampler never bleeds a neighbour's ink into it. +/// +/// Bit four of a row is its leftmost pixel and bit zero its rightmost, +/// which is to say the patterns below read as they look. An index past the +/// atlas's last cell is not an error: its texels fall beyond the bounds +/// check and nothing is written, so a pattern with nowhere to go goes +/// nowhere, quietly. The check exists for that case alone; every index the +/// two tables produce lands inside. +fn render_glyph_pattern(atlas: &mut [u8], idx: u32, pattern: [u8; 7], scale_x: u32, scale_y: u32) { + let col = idx % ATLAS_COLS; + let row = idx / ATLAS_COLS; + let glyph_x_offset = col * GLYPH_WIDTH; + let glyph_y_offset = row * GLYPH_HEIGHT; + + for (py, bits) in (0u32..).zip(pattern) { + for px in 0..5u32 { + let bit = (bits >> (4 - px)) & 1; + if bit == 1 { + for sy in 0..scale_y { + for sx in 0..scale_x { + let x = glyph_x_offset + px * scale_x + sx + 1; + let y = glyph_y_offset + py * scale_y + sy + 1; + if x < ATLAS_WIDTH && y < ATLAS_HEIGHT { + atlas[(y * ATLAS_WIDTH + x) as usize] = 255; + } + } + } + } + } + } +} + +/// The ASCII bitmaps: ninety-five patterns for codepoints 32 through 126, +/// each seven rows of five bits with bit four on the left, in codepoint +/// order, so that a character's pattern sits at the index of its codepoint +/// less thirty-two and the lookup in `render` is a subtraction. There is +/// no pattern for DEL; its cell in the atlas stays as the atlas was born, +/// which is dark. +/// +/// The hand is the five-by-seven of the terminals the epoch was typed on, +/// or near enough: capitals seven rows tall, lowercase five at the +/// x-height with the tails folded inside the cell, the zero slashed so it +/// is never the letter O, and the ten digits identical, bit for bit, to the +/// ten the waterfall's own atlas bakes, so that a numeral on a card and a +/// numeral in the waterfall differ in scale and in nothing else. +/// +/// # Returns +/// +/// The ninety-five patterns, in a vector, in order. +#[allow( + clippy::too_many_lines, + reason = "ninety-five glyphs, one after another, are a table; a table is not improved by being cut in five, and a reader who wants the letter Q wants to find it between P and R" +)] +fn get_font_patterns() -> Vec<[u8; 7]> { + vec![ + // 32: space — all air and no ink; the pen advances, and nothing is said + [ + 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, + ], + // 33: ! — five dots stacked, a breath, and a sixth + [ + 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00000, 0b00100, + ], + // 34: " — two ticks, gone by the third row + [ + 0b01010, 0b01010, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, + ], + // 35: # — the octothorpe: two posts, two bars + [ + 0b01010, 0b11111, 0b01010, 0b01010, 0b11111, 0b01010, 0b00000, + ], + // 36: $ — an S run through with a spine + [ + 0b00100, 0b01111, 0b10100, 0b01110, 0b00101, 0b11110, 0b00100, + ], + // 37: % — two small squares and the slash between them + [ + 0b11000, 0b11001, 0b00010, 0b00100, 0b01000, 0b10011, 0b00011, + ], + // 38: & — the ampersand, a loop that ties itself + [ + 0b01000, 0b10100, 0b10100, 0b01000, 0b10101, 0b10010, 0b01101, + ], + // 39: ' — one tick, two rows tall + [ + 0b00100, 0b00100, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, + ], + // 40: ( — the opening parenthesis + [ + 0b00010, 0b00100, 0b01000, 0b01000, 0b01000, 0b00100, 0b00010, + ], + // 41: ) — the closing one, its mirror bit for bit + [ + 0b01000, 0b00100, 0b00010, 0b00010, 0b00010, 0b00100, 0b01000, + ], + // 42: * — an asterisk on the middle five rows + [ + 0b00000, 0b00100, 0b10101, 0b01110, 0b10101, 0b00100, 0b00000, + ], + // 43: + — a cross on the middle row and the middle column: the + // timeline's past + [ + 0b00000, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0b00000, + ], + // 44: , — a dot with a tail that leans left + [ + 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00100, 0b01000, + ], + // 45: - — one bar on the fourth row; the em dash at 109 is the same bar + [ + 0b00000, 0b00000, 0b00000, 0b11111, 0b00000, 0b00000, 0b00000, + ], + // 46: . — a single dot on the last row + [ + 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00100, + ], + // 47: / — the solidus, bottom-left to top-right + [ + 0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000, + ], + // 48-57: 0-9 — the ten digits, bit for bit the waterfall's own + [ + 0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110, + ], // 0 — an oval with a diagonal through it; the letter O has none + [ + 0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110, + ], // 1 — a flag at the top, a serif at the foot + [ + 0b01110, 0b10001, 0b00001, 0b00110, 0b01000, 0b10000, 0b11111, + ], // 2 — a hook, a descent, a floor + [ + 0b01110, 0b10001, 0b00001, 0b00110, 0b00001, 0b10001, 0b01110, + ], // 3 — two bowls, the upper one indented + [ + 0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010, + ], // 4 — a diagonal, a crossbar, a stem + [ + 0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110, + ], // 5 — a flag, a shelf, a bowl + [ + 0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110, + ], // 6 — a curve that rises and closes on itself + [ + 0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000, + ], // 7 — a bar, and a stroke that straightens as it falls + [ + 0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110, + ], // 8 — two bowls sharing a waist + [ + 0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100, + ], // 9 — the six turned through a half turn, bit for bit + // 58: : — two dots, on the third row and the fifth + [ + 0b00000, 0b00000, 0b00100, 0b00000, 0b00100, 0b00000, 0b00000, + ], + // 59: ; — a dot over a comma, the comma begun a row early + [ + 0b00000, 0b00000, 0b00100, 0b00000, 0b00100, 0b00100, 0b01000, + ], + // 60: < — a chevron opening to the right + [ + 0b00010, 0b00100, 0b01000, 0b10000, 0b01000, 0b00100, 0b00010, + ], + // 61: = — two bars, on the third row and the fifth + [ + 0b00000, 0b00000, 0b11111, 0b00000, 0b11111, 0b00000, 0b00000, + ], + // 62: > — a chevron opening to the left + [ + 0b01000, 0b00100, 0b00010, 0b00001, 0b00010, 0b00100, 0b01000, + ], + // 63: ? — a hook that stops, a silence, a dot + [ + 0b01110, 0b10001, 0b00001, 0b00110, 0b00100, 0b00000, 0b00100, + ], + // 64: @ — the commercial at, which the network would put to work + // within two years of the Whisper + [ + 0b01110, 0b10001, 0b10111, 0b10101, 0b10110, 0b10000, 0b01110, + ], + // 65-90: A-Z — the capitals, seven rows tall, every one of them + [ + 0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001, + ], // A — an arch with a crossbar + [ + 0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110, + ], // B — two bowls on a stem + [ + 0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110, + ], // C — an open bowl + [ + 0b11110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11110, + ], // D — a stem and one bowl + [ + 0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111, + ], // E — three bars, the middle one shorter + [ + 0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000, + ], // F — the E without its floor + [ + 0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01111, + ], // G — the C with a shelf + [ + 0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001, + ], // H — two stems and a crossbar + [ + 0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110, + ], // I — a stem with serifs at both ends + [ + 0b00111, 0b00010, 0b00010, 0b00010, 0b00010, 0b10010, 0b01100, + ], // J — a hook with a serif on top + [ + 0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001, + ], // K — a stem with two diagonals meeting at its middle + [ + 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111, + ], // L — a stem and a floor + [ + 0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001, + ], // M — two stems joined at the top by a V + [ + 0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001, + ], // N — two stems and a diagonal + [ + 0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110, + ], // O — an oval, undivided; the zero is the one with the slash + [ + 0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000, + ], // P — a bowl on a stem + [ + 0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101, + ], // Q — the O with a tail + [ + 0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001, + ], // R — the P with a leg + [ + 0b01110, 0b10001, 0b10000, 0b01110, 0b00001, 0b10001, 0b01110, + ], // S — the serpent + [ + 0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, + ], // T — a bar on a stem + [ + 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110, + ], // U — two stems joined at the foot + [ + 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100, + ], // V — two strokes converging at the foot + [ + 0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b11011, 0b10001, + ], // W — the M turned upside down, bit for bit + [ + 0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001, + ], // X — two diagonals crossing at the centre + [ + 0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100, + ], // Y — a V on a stem + [ + 0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111, + ], // Z — a bar, a diagonal, a bar + // 91: [ — the opening bracket, with which the timeline's bar begins + [ + 0b01110, 0b01000, 0b01000, 0b01000, 0b01000, 0b01000, 0b01110, + ], + // 92: \ — the reverse solidus: the solidus in a mirror, bit for bit + [ + 0b10000, 0b01000, 0b01000, 0b00100, 0b00010, 0b00010, 0b00001, + ], + // 93: ] — the closing bracket, with which the timeline's bar ends + [ + 0b01110, 0b00010, 0b00010, 0b00010, 0b00010, 0b00010, 0b01110, + ], + // 94: ^ — a caret three rows tall: the timeline's event marker + [ + 0b00100, 0b01010, 0b10001, 0b00000, 0b00000, 0b00000, 0b00000, + ], + // 95: _ — one bar on the last row + [ + 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b11111, + ], + // 96: ` — a tick that leans, as the apostrophe does not + [ + 0b01000, 0b00100, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, + ], + // 97-122: a-z — the lowercase: five rows at the x-height, ascenders + // to the top, and no descenders, because there is no eighth row; the + // tails of g, j, p, q and y are folded inside the cell, and the g is + // lifted a row to make room for its own + [ + 0b00000, 0b00000, 0b01110, 0b00001, 0b01111, 0b10001, 0b01111, + ], // a — a bowl under a hood + [ + 0b10000, 0b10000, 0b11110, 0b10001, 0b10001, 0b10001, 0b11110, + ], // b — an ascender with a bowl + [ + 0b00000, 0b00000, 0b01110, 0b10000, 0b10000, 0b10001, 0b01110, + ], // c — the small open bowl + [ + 0b00001, 0b00001, 0b01111, 0b10001, 0b10001, 0b10001, 0b01111, + ], // d — the b in a mirror, bit for bit + [ + 0b00000, 0b00000, 0b01110, 0b10001, 0b11111, 0b10000, 0b01110, + ], // e — a bowl with a bar across it + [ + 0b00110, 0b01000, 0b11110, 0b01000, 0b01000, 0b01000, 0b01000, + ], // f — a hook with a crossbar + [ + 0b00000, 0b01111, 0b10001, 0b10001, 0b01111, 0b00001, 0b01110, + ], // g — lifted a row, so that its tail fits + [ + 0b10000, 0b10000, 0b11110, 0b10001, 0b10001, 0b10001, 0b10001, + ], // h — an ascender with an arch + [ + 0b00100, 0b00000, 0b01100, 0b00100, 0b00100, 0b00100, 0b01110, + ], // i — a dot, a serif, a stem, a foot + [ + 0b00010, 0b00000, 0b00110, 0b00010, 0b00010, 0b10010, 0b01100, + ], // j — a dot over a hook + [ + 0b10000, 0b10000, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, + ], // k — an ascender with two arms + [ + 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110, + ], // l — a stem with a serif and a foot + [ + 0b00000, 0b00000, 0b11010, 0b10101, 0b10101, 0b10001, 0b10001, + ], // m — two arches across five columns + [ + 0b00000, 0b00000, 0b11110, 0b10001, 0b10001, 0b10001, 0b10001, + ], // n — one arch + [ + 0b00000, 0b00000, 0b01110, 0b10001, 0b10001, 0b10001, 0b01110, + ], // o — the small oval + [ + 0b00000, 0b00000, 0b11110, 0b10001, 0b11110, 0b10000, 0b10000, + ], // p — a bowl, and a stem that carries on down + [ + 0b00000, 0b00000, 0b01111, 0b10001, 0b01111, 0b00001, 0b00001, + ], // q — the p in a mirror, bit for bit + [ + 0b00000, 0b00000, 0b10110, 0b11000, 0b10000, 0b10000, 0b10000, + ], // r — a stem with a shoulder + [ + 0b00000, 0b00000, 0b01111, 0b10000, 0b01110, 0b00001, 0b11110, + ], // s — the small serpent + [ + 0b01000, 0b01000, 0b11110, 0b01000, 0b01000, 0b01001, 0b00110, + ], // t — a stem with a crossbar and a foot + [ + 0b00000, 0b00000, 0b10001, 0b10001, 0b10001, 0b10011, 0b01101, + ], // u — a trough with a foot + [ + 0b00000, 0b00000, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100, + ], // v — two strokes meeting at the foot + [ + 0b00000, 0b00000, 0b10001, 0b10001, 0b10101, 0b10101, 0b01010, + ], // w — two troughs + [ + 0b00000, 0b00000, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, + ], // x — a small cross + [ + 0b00000, 0b00000, 0b10001, 0b10001, 0b01111, 0b00001, 0b01110, + ], // y — a trough with its tail tucked under + [ + 0b00000, 0b00000, 0b11111, 0b00010, 0b00100, 0b01000, 0b11111, + ], // z — a bar, a diagonal, a bar, small + // 123: { — the opening brace + [ + 0b00010, 0b00100, 0b00100, 0b01000, 0b00100, 0b00100, 0b00010, + ], + // 124: | — a stem, seven rows, unbroken: the timeline's future + [ + 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, + ], + // 125: } — the closing brace, the opening one's mirror bit for bit + [ + 0b01000, 0b00100, 0b00100, 0b00010, 0b00100, 0b00100, 0b01000, + ], + // 126: ~ — a tilde on the middle rows: the last printable character, + // and the last pattern + [ + 0b00000, 0b00000, 0b01000, 0b10101, 0b00010, 0b00000, 0b00000, + ], + ] +} + +/// The bitmaps of the sixteen guests, in the order of their constants — +/// the triangle, the ten raised digits, the raised minus, the +/// multiplication sign, the em dash, the bullet and the division sign — +/// for cells ninety-six through one hundred and eleven, row six of the +/// atlas, which they fill exactly. Same grid, same hand, same enlargement +/// as the ASCII; the raised digits are drawn in the top four rows of the +/// seven and leave the bottom three empty, which is how a digit is raised +/// in a font that has no baseline to raise it from. +/// +/// # Returns +/// +/// The sixteen patterns, in a vector, in order. +fn get_extended_patterns() -> Vec<[u8; 7]> { + vec![ + // 96: ▼ (U+25BC) — a solid triangle, five rows, pointing down at + // Creation from above the timeline's bar + [ + 0b00000, 0b11111, 0b11111, 0b01110, 0b01110, 0b00100, 0b00000, + ], + // 97: ⁰ (U+2070) — the raised zero: four rows at the top, three of + // air beneath, as with all the raised digits + [ + 0b01110, 0b10001, 0b10001, 0b01110, 0b00000, 0b00000, 0b00000, + ], + // 98: ¹ (U+00B9) — the raised one + [ + 0b00100, 0b01100, 0b00100, 0b01110, 0b00000, 0b00000, 0b00000, + ], + // 99: ² (U+00B2) — the raised two + [ + 0b01110, 0b00001, 0b01110, 0b11111, 0b00000, 0b00000, 0b00000, + ], + // 100: ³ (U+00B3) — the raised three + [ + 0b01110, 0b00110, 0b00001, 0b01110, 0b00000, 0b00000, 0b00000, + ], + // 101: ⁴ (U+2074) — the raised four + [ + 0b10010, 0b10010, 0b11111, 0b00010, 0b00000, 0b00000, 0b00000, + ], + // 102: ⁵ (U+2075) — the raised five + [ + 0b11111, 0b11110, 0b00001, 0b11110, 0b00000, 0b00000, 0b00000, + ], + // 103: ⁶ (U+2076) — the raised six + [ + 0b01110, 0b11110, 0b10001, 0b01110, 0b00000, 0b00000, 0b00000, + ], + // 104: ⁷ (U+2077) — the raised seven + [ + 0b11111, 0b00010, 0b00100, 0b00100, 0b00000, 0b00000, 0b00000, + ], + // 105: ⁸ (U+2078) — the raised eight + [ + 0b01110, 0b01110, 0b10001, 0b01110, 0b00000, 0b00000, 0b00000, + ], + // 106: ⁹ (U+2079) — the raised nine + [ + 0b01110, 0b10001, 0b01111, 0b01110, 0b00000, 0b00000, 0b00000, + ], + // 107: ⁻ (U+207B) — the raised minus, one bar on the second row + [ + 0b00000, 0b11111, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, + ], + // 108: × (U+00D7) — the multiplication sign, a saltire on the middle + // five rows: the join between the primes of a mask's name + [ + 0b00000, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b00000, + ], + // 109: — (U+2014) — the em dash, one bar on the fourth row: the + // hyphen's bar exactly, the difference living in the codepoint alone + [ + 0b00000, 0b00000, 0b00000, 0b11111, 0b00000, 0b00000, 0b00000, + ], + // 110: • (U+2022) — the bullet, a three-by-three block at the centre + [ + 0b00000, 0b00000, 0b01110, 0b01110, 0b01110, 0b00000, 0b00000, + ], + // 111: ÷ (U+00F7) — the division sign, a dot, a bar and a dot on the + // second, fourth and sixth rows: the edge from a mask to its child + [ + 0b00000, 0b00100, 0b00000, 0b11111, 0b00000, 0b00100, 0b00000, + ], + ] +} diff --git a/crates/loic-gui/src/timeline.rs b/crates/loic-gui/src/timeline.rs new file mode 100644 index 0000000..1de9795 --- /dev/null +++ b/crates/loic-gui/src/timeline.rs @@ -0,0 +1,1348 @@ +//! # The Cosmic Timeline +//! +//! The Observatory's horizontal bar from Creation to Annihilation: the whole +//! of the calendar's representable domain, some 10^154 Planck times of it, +//! laid across a single row of glyph cells and offered up for clicking. +//! Every click selects one segment of the bar and makes that segment the +//! whole bar; the view narrows by a factor of the segment count at each +//! descent, the descents compose, and they may be repeated until the span +//! beneath the pointer is narrower than a hundred Planck times, at which +//! point the Observatory declines to descend further, there being nothing +//! finer to show and no wish to pretend otherwise. +//! +//! The events of cosmic history are not painted on the bar all at once. +//! Each is withheld until the view has narrowed enough to give it room, so +//! that the widest views list the first stars and the death of the Sun, a +//! window a billion years wide lists the Snowball and the Cambrian, and a +//! window seventeen years wide lists the Whisper and the Unix epoch — each +//! event in the company of its own era, and never more of them than the +//! panel beneath the bar has lines. The curious observer who drills down is +//! rewarded. The incurious one sees a bar with a word at either end, which +//! is also a true statement about time, if a coarse one, and the calendar +//! has a mask for coarse. +//! +//! Every quantity here that is a time is an `I512` or a `U512`, and every +//! comparison, subtraction and quotient is performed on those integers in +//! full. The single exemption, tolerated because a GPU cannot be addressed +//! in any other tongue, is the last line of `TimelineView::position_of`, +//! which turns an exact ratio into a fraction of a bar's width and confesses +//! to the sin at length where it is committed. + +use loic::{ + As, I512, I512_ZERO, LOIC_TO_UNIX_OFFSET_SECONDS, U512, U512_ZERO, annihilation_planck, + creation_planck, +}; +use std::str::FromStr; + +use crate::events::EventId; + +/// The first nineteen powers of ten, transcribed in full and looked up by +/// index rather than raised at runtime, so that no exponentiation is ever +/// entrusted to a floating-point unit, whose powers of ten are exact only +/// until they are not and which does not say when. Index `n` furnishes +/// 10^n, exactly, as a `u64`, from 10^0 to 10^18, the largest power of ten +/// that type can hold; that reaches every count of attoseconds, +/// femtoseconds, picoseconds, nanoseconds and microseconds that the span +/// label of `TimelineView::format_span` prints from the table, and it is +/// the first thing the event table's scientific-notation helpers reach for +/// before they resign themselves to multiplying by ten one power at a time. +const POWERS_OF_10: [u64; 19] = [ + 1, // 10^0 + 10, // 10^1 + 100, // 10^2 + 1_000, // 10^3 + 10_000, // 10^4 + 100_000, // 10^5 + 1_000_000, // 10^6 + 10_000_000, // 10^7 + 100_000_000, // 10^8 + 1_000_000_000, // 10^9 + 10_000_000_000, // 10^10 + 100_000_000_000, // 10^11 + 1_000_000_000_000, // 10^12 + 10_000_000_000_000, // 10^13 + 100_000_000_000_000, // 10^14 + 1_000_000_000_000_000, // 10^15 + 10_000_000_000_000_000, // 10^16 + 100_000_000_000_000_000, // 10^17 + 1_000_000_000_000_000_000, // 10^18 +]; + +/// Planck times per second, transcribed in decimal: the integer part of +/// `PLANCK_DENOMINATOR / PLANCK_NUMERATOR`, which is 10^50 divided by +/// 5,391,247 — forty-four digits of it, approximately 1.855 × 10^43. The +/// reliquary is parsed once, when the event table is first built, into the +/// `I512` by which every second in that table is multiplied. It is kept as +/// a string because a string can be read against its derivation, which is +/// `derive_constants.sh` at the workspace root, and because a forty-four +/// digit literal is a thing the eye can check and the compiler cannot be +/// asked to have opinions about. The fraction of a Planck time that the +/// integer part leaves off — less than one — is the whole of what any +/// marker placed by this number is early by, per second of the interval it +/// was multiplied across. +const PLANCK_PER_SECOND_DECIMAL: &str = "18548584399861479171701834473545730700151560"; + +/// Planck times per Julian year, transcribed in decimal: the figure above +/// multiplied by `SECONDS_PER_JULIAN_YEAR`, 31,557,600, which is 365.25 +/// days of 86,400 SI seconds and the only year this calendar acknowledges, +/// because it is a definition and not a measurement of anything that +/// wobbles. Fifty-one digits, approximately 5.853 × 10^50; derivation, +/// `derive_constants.sh` at the workspace root. Every event in the table +/// dated in years — which is most of them, the universe having been +/// unhurried for the greater part of its life — is placed by multiplying +/// its count of years by this integer, exactly, with no intermediate that a +/// floating-point unit was invited to round. +const PLANCK_PER_YEAR_DECIMAL: &str = "585348807057068615108897811582366751143102869856000"; + +/// The seconds by which the kernel's atomic clock leads civil time: the ten +/// that Coordinated Universal Time began with on the first of January 1972, +/// and the twenty-seven leap seconds inserted since, the last of them at +/// the close of 2016 — thirty-seven in all, every one of them a negotiation +/// with a rotating planet. The workspace README, section 1.2, holds all +/// thirty-seven in the contempt they have earned and discloses, in the same +/// breath, that the calendar's own epoch is pinned by exactly this many of +/// them: `CLOCK_TAI` on Linux is `CLOCK_REALTIME` plus this offset, and the +/// library's Unix offset is stated on that scale. This module needs the +/// number for the return journey, from the atomic scale the library counts +/// in to the civil scale the history books use, and takes it once, here, +/// to state the Whisper as a Unix timestamp. +const TAI_MINUS_UTC_SECONDS: i64 = 37; + +/// The Whisper on the Unix scale: 1969-10-30 06:30:41 UTC, which is +/// 5,419,759 seconds before the Unix epoch and therefore negative, Unix +/// time not having begun yet. The library states the same instant on the +/// atomic scale, thirty-seven seconds ahead, as `LOIC_TO_UNIX_OFFSET_SECONDS`, +/// because `CLOCK_TAI` is what it reads; this module wants the civil number, +/// because the dates in the event table are civil ones, recorded by people +/// who did not know what a leap second was and would not have cared. The +/// relation between the two is one addition, performed here, once, by the +/// compiler. +/// +/// A civil date is placed on the timeline exactly where `now()` would place +/// it on a kernel whose clock read that date with today's offset: its +/// distance from this constant in seconds, times the Planck times in a +/// second. That is the only arithmetic the calendar has for turning a +/// clock's reading into an instant, and the timeline uses it rather than +/// inventing a second arithmetic that could one day disagree with the +/// first. +const WHISPER_UNIX_SECONDS: i64 = -(LOIC_TO_UNIX_OFFSET_SECONDS + TAI_MINUS_UTC_SECONDS); + +/// A compile-time proof that the civil timestamp of the Whisper, written +/// down here as every history of the ARPANET would give it, agrees with the +/// library's atomic offset plus the leap seconds it stands on. The two +/// arrive by independent roads — one transcribed from the record of the +/// first transmission, one derived from `CLOCK_TAI`'s arithmetic — and they +/// are meant to meet at −5,419,759. Were they not to, either the workspace +/// README's disclosure in section 1.2 or the library's constant would be +/// wrong, and the crate declines to build until someone says which; a +/// binary whose epoch is in dispute by thirty-seven seconds is not a +/// calendar, it is a rumour with a compiler. +const _WHISPER_UTC_AGREES_WITH_THE_LIBRARY: () = assert!( + WHISPER_UNIX_SECONDS == -5_419_759, + "the Whisper's civil second and the library's atomic offset disagree beyond the leap seconds" +); + +/// Consult the table for 10^`exp`, and answer 1 — the zeroth power, the +/// multiplicative identity, the number that changes nothing it touches — +/// for any exponent the table does not hold, whether negative or past +/// eighteen, rather than a fraction the `u64` could not carry or an error +/// the caller could not use. The span label that consults it has already +/// shifted its exponent into the range of a unit prefix before asking, and +/// the shift, not this function, is where the label's honesty is decided. +fn pow10(exp: i32) -> u64 { + usize::try_from(exp) + .ok() + .and_then(|index| POWERS_OF_10.get(index)) + .copied() + .unwrap_or(1) +} + +/// The cell under a pixel offset: the offset divided by the cell's width, +/// clamped at zero from below and then truncated toward it, which for a +/// non-negative quotient is the floor, which is the index of the cell the +/// pixel lies in, which is the whole of the question. Two floating-point +/// operations are committed here, a division and a `max`, and both are +/// forgiven: the operands are pixel measurements, a few hundred wide at +/// most, which an `f32` carries to a precision no pixel can resolve, and +/// the result is delivered into a `usize` the moment it is known. Nothing +/// temporal passes through this function. It is a ruler, and a ruler is +/// permitted to be made of wood. +#[allow( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "the floor of a non-negative quotient is the cell under the pixel; the cut selects it" +)] +fn cell_under(offset: f32, cell_width: f32) -> usize { + (offset / cell_width).max(0.0) as usize +} + +/// A window onto the cosmic timeline: the contiguous stretch of +/// representable time, from `start` to `end` inclusive, that the bar is +/// currently showing. The full view is the whole domain, Creation to +/// Annihilation; every narrower view is one segment of some wider one, +/// reached by clicking, and the Observatory keeps the wider ones on a stack +/// so that the descent can be retraced one step at a time. +/// +/// A view is a pair of instants and nothing else. Its width, its order of +/// magnitude, the position of any instant within it, and the label it +/// wears are all derived on demand from the two ends — in 512-bit +/// integers, with the one exception that `position_of` confesses to in +/// full. Nothing is cached, because nothing here is expensive enough to +/// deserve the risk of being stale. +#[derive(Clone)] +pub struct TimelineView { + /// The first instant the view shows, in Planck times since the Whisper: + /// negative for everything before 06:30:41 UTC on 30 October 1969, + /// which is most of the universe. + pub start: I512, + /// The last instant the view shows, in Planck times since the Whisper. + /// Never less than `start`; the difference between them is the view's + /// span, which for the full view does not fit in this type at all and + /// is computed unsigned for that reason. + pub end: I512, +} + +impl TimelineView { + /// Manifest the widest view there is: `start` at Creation, the Big Bang + /// as the library locates it some 8.08 × 10^60 Planck times before the + /// Whisper, and `end` at Annihilation, the last coordinate 512 signed + /// bits can name, a little past 10^103 years hence. Between them lies + /// every instant the calendar can represent, which is the same as + /// saying every instant, since the calendar does not concede that there + /// are others. This is the view the Observatory opens on and the view + /// Escape returns it to. + pub fn full() -> Self { + Self { + start: *creation_planck(), + end: *annihilation_planck(), + } + } + + /// The width of this view in Planck times, furnished as a `U512` because + /// the widest view is wider than a signed integer can say. Creation is + /// negative, Annihilation is `I512::MAX`, and their difference — the + /// library's `total_span`, some 6.7 × 10^153 — exceeds `I512::MAX` by + /// exactly the age of the universe, which is not a margin one waves + /// away. So the subtraction is performed on the unsigned bit patterns + /// and permitted to wrap, and for `end >= start` the wrapped difference + /// is the exact width at every zoom, including the one at which the + /// signed subtraction would have overflowed and, in a release build, + /// said nothing about it. Two's complement is a circle, and a circle has + /// no edge to fall off. The test `full_span_agrees_with_the_library` + /// holds this function to the library's own span, bit for bit. + pub fn span(&self) -> U512 { + self.end + .cast_unsigned() + .wrapping_sub(self.start.cast_unsigned()) + } + + /// The number of decimal digits in the span: `ilog10` plus one, an + /// integer stand-in for the view's order of magnitude that costs one + /// 512-bit logarithm and no floating-point at all. It is the coin in + /// which this module prices everything — which events are legible at + /// this zoom, which unit the span label speaks in, whether the + /// Observatory will consent to zoom further — because a threshold on a + /// digit count is a threshold on a power of ten, and a power of ten is + /// the only kind of "about" the calendar is prepared to be. + /// + /// The full view has 154 digits. A span of zero, which no view has, + /// would be reported as one digit rather than as a panic; the guard + /// exists because `ilog10` is honest about the logarithm of nothing, + /// and this function prefers to be honest about something. + pub fn span_digits(&self) -> usize { + let span = self.span(); + if span == U512_ZERO { + 1 + } else { + usize::try_from(span.ilog10()).map_or(1, |magnitude| magnitude + 1) + } + } + + /// Whether this view is the full one: `start` at Creation and `end` at + /// Annihilation, both compared exactly, in all 512 bits, because a view + /// that is merely enormous is not the same thing as a view that is + /// everything. The Observatory asks this to decide whether the words + /// beneath the bar's ends read Creation and Annihilation or merely + /// Start and End, whether to offer the way back, and whether the + /// breadcrumb of fractions has anything yet to say. + pub fn is_full(&self) -> bool { + self.start == *creation_planck() && self.end == *annihilation_planck() + } + + /// Descend into one segment of this view: divide the span into + /// `segment_count` equal parts and make the part numbered + /// `segment_index`, counting from zero at `start`, the whole of a new + /// view. Each descent narrows the window by the segment count — some + /// sixty at the Observatory's width — and the descents compose: forty + /// of them at fifty-eight segments apiece carry the full span's 154 + /// digits down to about eighty-four, which is the walk the test + /// `position_is_exact_at_ends_and_midpoint_at_every_zoom` takes. + /// + /// The division is integer division on the `U512` span, so the segments + /// are equal to the Planck time and the remainder falls past the last + /// of them, unshown; a view a few Planck times narrower than the bar + /// suggested is a smaller lie than a fractional Planck time would be, + /// and the calendar does not deal in those. The new view runs from + /// `start + index × segment` to `start + (index + 1) × segment`, + /// computed in `I512`, which the remark in the body explains is safe. + /// + /// # Panics + /// + /// Panics if `segment_index` does not fit an `i64` — a bar more than + /// nine quintillion cells wide, drawn on a monitor that does not exist — + /// or if `segment_count` is zero, which is a division by nothing and + /// the caller's confession that it drew no bar at all. + pub fn zoom_into(&self, segment_index: usize, segment_count: usize) -> Self { + let span = self.span(); + let segment_span = span / (segment_count as u64).as_::(); + + // A segment is narrower than the span it divides, the widest span + // divided is the full one, and the full span divided by anything + // greater than one is below 2^511: so the segment's bit pattern, + // reinterpreted as signed, is its value, and the cast neither costs + // nor loses anything. Divided by one it would not be, and one + // segment is not a division but the view again; no bar asks for it. + let segment_span_i = segment_span.cast_signed(); + + let index = i64::try_from(segment_index).expect("no bar has more cells than an i64 holds"); + let new_start = self.start + segment_span_i * index.as_::(); + let new_end = new_start + segment_span_i; + + Self { + start: new_start, + end: new_end, + } + } + + /// Locate an instant within this view as a fraction of the way from + /// `start` to `end`: 0.0 at the first instant, 1.0 at the last, and + /// `None` for any instant the view does not contain, which is the + /// Observatory's cue to draw no caret rather than a caret in the + /// margin. The bar multiplies the fraction by its width in pixels and + /// places the caret there; the hit test reverses the same arithmetic to + /// find out which caret was struck. + /// + /// # On the Reluctant Use of Floating-Point + /// + /// This function commits the venial sin of `f64` arithmetic, but only in + /// its last line, and only for the conversion of one exact ratio into a + /// pixel ratio. The offset of the instant from `start` and the span of + /// the view are both computed in 512-bit integers, exactly; both are + /// then brought down to sixty-four bits by the same right shift, chosen + /// so that the span keeps its leading sixty-four bits and the offset + /// loses the same low bits; and only then is one divided by the other. + /// The ratio of the shifted quantities is exact to one part in 2^63, + /// which is finer than an `f64` can express, so the two conversions and + /// the one division are the only floating-point operations performed, + /// each faithful to one part in 2^53, and a pixel is one part in a few + /// thousand. The underlying temporal values remain in their integer + /// sanctity until the very moment we must speak to the GPU in its + /// native tongue, and the orders of magnitude discarded at that moment — + /// nearly all of them, in the full view — were never going to fit on a + /// monitor anyway; we shed no tears. The test + /// `position_is_exact_at_ends_and_midpoint_at_every_zoom` checks the + /// two ends and the midpoint of forty successive views against 0, 1 and + /// one half. + pub fn position_of(&self, planck_time: &I512) -> Option { + if planck_time < &self.start || planck_time > &self.end { + return None; + } + + // `start <= planck_time` has just been established, so the wrapped + // unsigned difference is the exact offset — even in the full view, + // where the signed difference between an instant near Annihilation + // and Creation does not fit an I512 and a checked subtraction would + // have nothing honest to say. The same circle as `span`, walked for + // the same reason. + let offset = planck_time + .cast_unsigned() + .wrapping_sub(self.start.cast_unsigned()); + let span = self.span(); + if span == U512_ZERO { + return Some(0.0); + } + + // Both quantities are brought down to 64 bits by the same shift: the + // span's bit length less sixty-four, saturating at zero for spans + // that already fit, so the span keeps its leading 64 bits and the + // offset — never the larger — loses the same low bits. Their ratio + // is then exact to one part in 2^63, which is more than an f64 can + // hold, and the division below is the only floating-point operation + // performed on the way to the pixel. The clamp is a courtesy to the + // rounding, not a correction of the arithmetic: the shifted offset + // cannot exceed the shifted span, so the quotient cannot exceed one. + let shift = (U512::BITS - span.leading_zeros()).saturating_sub(64); + let offset_top = (offset >> shift).as_::(); + let span_top = (span >> shift).as_::(); + Some((offset_top as f64 / span_top as f64).clamp(0.0, 1.0)) + } + + /// Pronounce the span of this view in a unit a human might recognise — + /// "~minutes", "~billions to trillions of years", "~10^-33 seconds" — + /// prefixed with a tilde, because the label is chosen by the span's + /// digit count and a digit count is honest only to within a factor of + /// ten. The Observatory prints it beneath the zoomed bar, centred, in + /// cyan. It is the one place the calendar utters the word "minutes", + /// and it does so under protest, with the tilde as its disclaimer. + /// + /// The digit-count thresholds are derived from the Planck time constant + /// and from nothing else: + /// - `planck_per_second` = 10^50 / 5391247 = 1.855…×10^43 (44 digits) + /// - `planck_per_minute` = `planck_per_second` × 60 (46 digits) + /// - `planck_per_hour` = `planck_per_second` × 3600 (47 digits; the arm + /// below takes 47 and 48 together, hours to days) + /// - `planck_per_day` = `planck_per_second` × 86400 (49 digits) + /// - `planck_per_year` = `planck_per_second` × 31557600 (51 digits) + /// + /// Therefore `span_digits` ≈ 44 + log10(seconds) for any span of a + /// second or more, and for a sub-second span the exponent of the seconds + /// is `span_digits` − 44, from which a prefix — micro, nano, pico, + /// femto, atto — is chosen by range and a power of ten from the table + /// is printed before it. Below 10^-30 seconds the function gives up on + /// prefixes and prints the exponent; below 10^10 Planck times it gives + /// up on seconds altogether and prints Planck times, which is the unit + /// the calendar wanted to use from the start. + pub fn format_span(&self) -> String { + let digits = self.span_digits(); + + // The thresholds, from `derive_constants.sh` at the workspace root. + // `planck_per_second` has 44 digits, so a span of: + // 44 digits is about a second; + // 46 digits about a minute, sixty of those; + // 47 to 48 digits an hour to a day; + // 49 to 50 digits days to months, a range the calendar labels + // "days to years" so as not to say the other word; + // 51 digits about a year, the Julian one; + // 60 digits about a billion years. + // The arms below are these numbers and nothing cleverer. + + match digits { + 0..=10 => format!("~10^{digits} Planck times"), + 11..=43 => { + // The sub-second range: 11 to 43 digits is 10^-33 to 10^-1 + // seconds, and the exponent of the seconds is the digit + // count less the forty-four digits of one second. + let seconds_exp = i32::try_from(digits).expect("a digit count beyond an i32") - 44; + if seconds_exp < -30 { + format!("~10^{seconds_exp} seconds") + } else if seconds_exp < -15 { + // Attoseconds, 10^-18 s: eighteen is added to the + // exponent to name the count of them. + format!("~{} attoseconds", pow10(seconds_exp + 18)) + } else if seconds_exp < -9 { + // Femtoseconds, 10^-15 s: fifteen added. + format!("~{} femtoseconds", pow10(seconds_exp + 15)) + } else if seconds_exp < -6 { + // Picoseconds, 10^-12 s: twelve added. + format!("~{} picoseconds", pow10(seconds_exp + 12)) + } else if seconds_exp < -3 { + // Nanoseconds, 10^-9 s: nine added — the kernel's own + // unit, and the last one it can vouch for. + format!("~{} nanoseconds", pow10(seconds_exp + 9)) + } else { + // Microseconds, 10^-6 s: six added. + format!("~{} microseconds", pow10(seconds_exp + 6)) + } + } + 44..=45 => "~seconds".to_string(), + 46 => "~minutes".to_string(), + 47..=48 => "~hours to days".to_string(), + 49..=50 => "~days to years".to_string(), + 51..=53 => "~years to millennia".to_string(), + 54..=59 => "~millions to billions of years".to_string(), + 60..=70 => "~billions to trillions of years".to_string(), + _ => format!("~10^{} years", digits - 51), + } + } +} + +/// One event of cosmic history as the timeline knows it: a name for the +/// list beneath the bar, a coordinate for the caret upon it, an identifier +/// for the passage that opens when the caret is clicked, and a threshold +/// that says how far in the observer must have zoomed to be shown it at +/// all. The table of them is `cosmic_events`. The events themselves are not +/// invented here, only placed, and the placing is done in the calendar's +/// own integers from the numbers the passages in `events` give. +pub struct CosmicEvent { + /// The identifier that ties this marker to its passage — the same + /// `EventId` that `events::get_passage` answers to, so that a caret and + /// the text behind it cannot come apart. + pub id: EventId, + /// The short name printed in the list beneath the bar, in amber, behind + /// a dash, at most eight of them at once. + pub name: &'static str, + /// The event's coordinate, in Planck times since the Whisper: negative + /// for everything that happened before 06:30:41 UTC on 30 October 1969, + /// which is nearly all of it, and positive for the handful of things + /// that have happened since and the many that have not happened yet. + pub planck_time: I512, + /// The widest view, measured in digits of its span, that shows this + /// event: it appears when `view.span_digits() <= max_span_digits` and + /// is withheld from anything wider. A small number is an event that + /// demands a close look; a large one is visible from far off. The + /// numbers are tiered by hand so that no view, at any zoom, lists more + /// events than the panel beneath the bar has lines, and a test holds + /// them to it. + pub max_span_digits: usize, +} + +/// The most events any view lists, and the number of lines the panel +/// beneath the bar has for listing them: eight. The thresholds in +/// `cosmic_events` are tiered so that no view, at any zoom, has more to say +/// than it has lines to say it in, and the test +/// `no_view_lists_more_events_than_the_panel_holds` slides a window of +/// every width from 10^1 to 10^154 Planck times along the chronology to +/// make sure. The Observatory takes the first `EVENT_LINES` of whatever is +/// visible, which the thresholds guarantee is all of it; the take is a +/// statement, not a truncation. +pub const EVENT_LINES: usize = 8; + +/// The chronology: every event the timeline can show, from the end of the +/// Planck epoch to the evaporation of the last black hole, in the order it +/// happened or is expected to, each placed in Planck times since the +/// Whisper by integer arithmetic on the numbers its passage gives. Built +/// on first request and kept for the life of the process by +/// `visible_events`, the universe's past not being expected to change +/// between frames. +/// +/// # Integer Arithmetic for Temporal Constants +/// +/// Every conversion herein is performed in `I512`, and the seductive +/// imprecision of floating-point is not merely avoided but never offered. +/// A time given in scientific notation — 10^-36 seconds, say — is split +/// into a mantissa and an exponent; the mantissa is multiplied by the +/// Planck times in a second, and the product is scaled by a power of ten +/// from the table, multiplying for a positive exponent and dividing for a +/// negative one. Years are multiplied by the Planck times in a Julian year. +/// Dates given as "so many years ago" are restated from the Whisper, which +/// is the present as far as the calendar is concerned; the helper +/// `years_before_present_to_planck` says why that matters. Civil dates — +/// the Julian calendar, ENIAC, the genesis block — are placed by their Unix +/// timestamps through the same offset the library applies to the kernel's +/// clock, so that a marker that names a day sits on that day, and the test +/// `civil_dates_land_on_their_days` holds it there. +/// +/// # On the Thresholds +/// +/// An event's `max_span_digits` says how far in you must have zoomed to be +/// shown it. The numbers are tiered by hand so that the whole past fits its +/// eight lines at the widest views (the first stars, the Solar System, the +/// Sun's death) and the rest surface as the view narrows, each in the +/// company of its own era: a window a billion years wide lists the Snowball +/// and the Cambrian, a window seventeen years wide lists the Whisper and +/// the Unix epoch. The test `no_view_lists_more_events_than_the_panel_holds` +/// is the proof that the tiers hold, and the reason the numbers are what +/// they are and not rounder. +/// +/// # Panics +/// +/// Panics if either decimal reliquary at the top of this module fails to +/// parse as an `I512`, which is to say if someone has edited forty-four or +/// fifty-one digits and introduced a letter; the table is built once, so +/// the panic would arrive with the first frame and not later. No entry in +/// the table can panic on its own: every exponent handed to the helpers is +/// a small literal, far inside the ranges their conversions guard. +#[allow( + clippy::too_many_lines, + reason = "a table of sixty events and their derivations is one table; cut into pieces it would stop reading as the chronology it is" +)] +pub fn cosmic_events() -> Vec { + let planck_per_second = I512::from_str(PLANCK_PER_SECOND_DECIMAL).unwrap(); + let planck_per_year = I512::from_str(PLANCK_PER_YEAR_DECIMAL).unwrap(); + + // The present, as the table understands it: the age of the universe in + // Julian years at the Whisper, 13,806,491,023. Read the digits — all + // eleven — and you have read the Boltzmann constant, 1.380649 × 10⁻²³ + // J/K, mantissa then exponent, straight through with the sign dropped: + // the exchange rate between information and heat, buried in the age of + // everything (workspace README, section 2.1). The library carries it as + // `AGE_UNIVERSE_JULIAN_YEARS`; the derivation is `derive_constants.sh` + // at the workspace root. Every "years ago" in this table is subtracted + // from this number, not from the year you are reading it in. + let present_years: i64 = 13_806_491_023; + + // Seconds after the Big Bang, given in scientific notation as + // mantissa × 10^exponent, to Planck times since the Whisper: the first + // instants of the universe are too brief for any other notation and too + // sacred for any other arithmetic. Integer throughout. + let seconds_sci_to_planck = |mantissa: i64, exponent: i32| -> I512 { + // The product is reassociated so that the scaling by the power of + // ten comes last, on the largest operand: + // planck = seconds × planck_per_second + // = mantissa × 10^exp × planck_per_second + // = mantissa × planck_per_second × 10^exp + // For the sub-second times this helper exists for, exp is negative + // and the last step is a division by 10^(−exp) of a number already + // forty-odd digits wide, which is why the multiplication precedes + // it: dividing first would leave nothing to multiply. + let base = planck_per_second * (mantissa).as_::(); + let ten = 10i64.as_::(); + + // A positive exponent multiplies, a negative one divides; the table + // reaches 10^18, and anything beyond it — the Grand Unification + // epoch at 10^-36 seconds, the end of inflation at 10^-32 — is + // applied a power at a time by a fold, thirty-odd divisions by ten + // standing in for the one division by a number the table declines + // to hold. + let planck_offset = if let Ok(exp) = usize::try_from(exponent) { + POWERS_OF_10.get(exp).map_or_else( + || (0..exp).fold(base, |acc, _| acc * ten), + |&power| base * power.as_::(), + ) + } else { + let exp = usize::try_from(-exponent).expect("a negated negative exponent is positive"); + POWERS_OF_10.get(exp).map_or_else( + || (0..exp).fold(base, |acc, _| acc / ten), + |&power| base / power.as_::(), + ) + }; + + creation_planck() + planck_offset + }; + + // Whole seconds after the Big Bang to Planck times since the Whisper: + // one multiplication, exact, which is the reason the second was + // transcribed to forty-four digits rather than approximated to two. + let seconds_to_planck = + |seconds: i64| -> I512 { creation_planck() + planck_per_second * (seconds).as_::() }; + + // Whole Julian years after the Big Bang, likewise: the year's Planck + // count, all fifty-one digits of it, times the count of years. + let years_to_planck = + |years: i64| -> I512 { creation_planck() + planck_per_year * (years).as_::() }; + + // Years after the Big Bang with a magnitude attached: mantissa × 10^exp, + // the ten applied one power at a time in `I512`, so that + // `years_exp_to_planck(1, 14)` is 10^14 years after the Big Bang — the + // death of the last stars — and `years_exp_to_planck(1, 100)` is the + // googol at which the last black holes go, a count of years no `i64` + // could have carried to this closure. + let years_exp_to_planck = |mantissa: i64, exponent: u32| -> I512 { + let mut years = (mantissa).as_::(); + for _ in 0..exponent { + years *= (10i64).as_::(); + } + *creation_planck() + planck_per_year * years + }; + + // Years before the Whisper to Planck times. "Present" is the epoch, + // 1969, not the year you are reading this in: the calendar has exactly + // one present and it has already happened. A date given as "N years + // ago" from a later vantage must be restated from the Whisper's; for + // anything older than a million years the restatement is invisible, + // and for anything younger it is not, which is why the civil dates + // below do not pass through this helper at all. + let years_before_present_to_planck = + |years_ago: i64| -> I512 { years_to_planck(present_years - years_ago) }; + + // Years after the Whisper to Planck times: the same arithmetic with the + // sign reversed, for the future the calendar has already scheduled. + let years_after_present_to_planck = + |years_future: i64| -> I512 { years_to_planck(present_years + years_future) }; + + // Years before the present in scientific notation, mantissa × 10^exp + // years ago, for the ages of the Earth and its early life, which are + // known to two or three figures and given here as exactly that many. + let years_ago_exp_to_planck = |mantissa: i64, exponent: u32| -> I512 { + let mut years_ago = (mantissa).as_::(); + for _ in 0..exponent { + years_ago *= (10i64).as_::(); + } + *creation_planck() + planck_per_year * ((present_years).as_::() - years_ago) + }; + + // Years after the present in scientific notation, mantissa × 10^exp + // years hence: the oceans, Andromeda, the red giant, given to the + // figures the models share and not one more. + let years_future_exp_to_planck = |mantissa: i64, exponent: u32| -> I512 { + let mut years_future = (mantissa).as_::(); + for _ in 0..exponent { + years_future *= (10i64).as_::(); + } + *creation_planck() + planck_per_year * ((present_years).as_::() + years_future) + }; + + // A civil instant, given as its Unix timestamp in UTC, placed from the + // Whisper by the calendar's own arithmetic — the timestamp's distance + // from `WHISPER_UNIX_SECONDS`, in seconds, times the Planck times in a + // second — which is exactly what `now()` does to the kernel's clock, + // and so exactly where `now()` would have placed the moment had it been + // running then. Exact to the second, as the dates in the passages are; + // a marker that names a day sits on that day, and one that names a + // second sits on the second. + let civil_to_planck = |unix_seconds: i64| -> I512 { + planck_per_second * (unix_seconds - WHISPER_UNIX_SECONDS).as_::() + }; + + vec![ + // ════════════════════════════════════════════════════════════════════ + // THE PLANCK ERA: the first 10^-43 seconds, one Planck time, the unit the calendar counts in + // ════════════════════════════════════════════════════════════════════ + CosmicEvent { + id: EventId::PlanckEpochEnds, + name: "Planck Epoch ends", + planck_time: *creation_planck() + (1i64).as_::(), + max_span_digits: 5, + }, + // ════════════════════════════════════════════════════════════════════ + // THE GRAND UNIFICATION ERA: 10^-43 to 10^-36 seconds, three forces still on speaking terms + // ════════════════════════════════════════════════════════════════════ + CosmicEvent { + id: EventId::GrandUnificationEpoch, + name: "Grand Unification Epoch", + planck_time: seconds_sci_to_planck(1, -36), // 1e-36 seconds + max_span_digits: 15, + }, + // ════════════════════════════════════════════════════════════════════ + // THE ELECTROWEAK ERA: 10^-36 to 10^-12 seconds, inflation, and the Higgs field turning on + // ════════════════════════════════════════════════════════════════════ + CosmicEvent { + id: EventId::InflationEnds, + name: "Inflation ends", + planck_time: seconds_sci_to_planck(1, -32), // 1e-32 seconds + max_span_digits: 20, + }, + CosmicEvent { + id: EventId::ElectroweakEpoch, + name: "Electroweak Epoch", + planck_time: seconds_sci_to_planck(1, -12), // 1e-12 seconds + max_span_digits: 35, + }, + // ════════════════════════════════════════════════════════════════════ + // THE QUARK ERA: 10^-12 to 10^-5 seconds, a plasma in which nothing has yet been confined + // ════════════════════════════════════════════════════════════════════ + CosmicEvent { + id: EventId::QuarkEpoch, + name: "Quark Epoch", + planck_time: seconds_sci_to_planck(1, -6), // 1e-6 seconds + max_span_digits: 40, + }, + // ════════════════════════════════════════════════════════════════════ + // THE HADRON ERA: 10^-5 seconds to one second, the quarks confined and the antimatter gone + // ════════════════════════════════════════════════════════════════════ + CosmicEvent { + id: EventId::HadronEpoch, + name: "Hadron Epoch", + planck_time: seconds_sci_to_planck(1, -4), // 1e-4 seconds + max_span_digits: 42, + }, + CosmicEvent { + id: EventId::NeutrinoDecoupling, + name: "Neutrino decoupling", + planck_time: seconds_to_planck(1), // 1 second + max_span_digits: 46, + }, + // ════════════════════════════════════════════════════════════════════ + // NUCLEOSYNTHESIS: one second to twenty minutes, the whole universe run as one reactor + // ════════════════════════════════════════════════════════════════════ + CosmicEvent { + id: EventId::NucleosynthesisBegins, + name: "Nucleosynthesis begins", + planck_time: seconds_to_planck(10), // 10 seconds + max_span_digits: 47, + }, + CosmicEvent { + id: EventId::NucleosynthesisEnds, + name: "Nucleosynthesis ends", + planck_time: seconds_to_planck(1200), // 20 minutes + max_span_digits: 49, + }, + // ════════════════════════════════════════════════════════════════════ + // THE PHOTON ERA: twenty minutes to 380,000 years, opaque, cooling, and nothing scheduled + // ════════════════════════════════════════════════════════════════════ + CosmicEvent { + id: EventId::CoolerThanTheSunsCore, + name: "Cooler than the Sun's core", + // In the radiation era the temperature falls as the inverse + // square root of the age, T ≈ 1.3 × 10^10 K / sqrt(t / 1 s); the + // Sun's core, 15.7 million K, is crossed at ~7 × 10^5 s, and the + // marker sits there, a week and a day in. + planck_time: seconds_to_planck(700_000), // ~8 days + max_span_digits: 51, + }, + CosmicEvent { + id: EventId::MatterRadiationEquality, + name: "Matter-radiation equality", + planck_time: years_to_planck(47_000), // 47,000 years + max_span_digits: 56, + }, + CosmicEvent { + id: EventId::Recombination, + name: "Recombination (CMB)", + planck_time: years_to_planck(380_000), // 380,000 years + max_span_digits: 58, + }, + // ════════════════════════════════════════════════════════════════════ + // THE DARK AGES: 380,000 to some 200 million years, and not one photon that was new + // ════════════════════════════════════════════════════════════════════ + CosmicEvent { + id: EventId::DarkAgesBegin, + name: "Dark Ages begin", + planck_time: years_to_planck(380_000), // 380,000 years + max_span_digits: 60, + }, + // ════════════════════════════════════════════════════════════════════ + // COSMIC DAWN: some 200 to 500 million years, the first stars and the first galaxies + // ════════════════════════════════════════════════════════════════════ + CosmicEvent { + id: EventId::FirstStarsIgnite, + name: "First stars ignite", + planck_time: years_to_planck(200_000_000), // 200 million years + max_span_digits: 63, + }, + CosmicEvent { + id: EventId::FirstGalaxiesForm, + name: "First galaxies form", + planck_time: years_to_planck(300_000_000), // 300 million years + max_span_digits: 60, + }, + // ════════════════════════════════════════════════════════════════════ + // THE STELLIFEROUS ERA: the age of stars, from reionization to the noon and the afternoon + // ════════════════════════════════════════════════════════════════════ + CosmicEvent { + id: EventId::ReionizationComplete, + name: "Reionization complete", + planck_time: years_to_planck(1_000_000_000), // 1 billion years + max_span_digits: 61, + }, + CosmicEvent { + id: EventId::CosmicNoon, + name: "Cosmic noon", + planck_time: years_to_planck(3_500_000_000), // z ≈ 2, 3.5 billion years + max_span_digits: 62, + }, + CosmicEvent { + id: EventId::ExpansionAccelerates, + name: "Expansion begins to accelerate", + planck_time: years_to_planck(7_500_000_000), // z ≈ 0.7, ~6 billion years ago + max_span_digits: 62, + }, + // ════════════════════════════════════════════════════════════════════ + // THE SOLAR SYSTEM: some 9.2 billion years after the Big Bang, an arm, a cloud, a star + // ════════════════════════════════════════════════════════════════════ + CosmicEvent { + id: EventId::SolarSystemForms, + name: "Solar System forms", + planck_time: years_ago_exp_to_planck(46, 8), // 4.6 billion years ago + max_span_digits: 63, + }, + CosmicEvent { + id: EventId::EarthForms, + name: "Earth forms", + planck_time: years_ago_exp_to_planck(454, 7), // 4.54 billion years ago + max_span_digits: 61, + }, + CosmicEvent { + id: EventId::MoonForms, + name: "Moon-forming impact", + planck_time: years_ago_exp_to_planck(45, 8), // 4.5 billion years ago + max_span_digits: 60, + }, + // ════════════════════════════════════════════════════════════════════ + // LIFE ON EARTH: from a chemistry nobody understands to the extinctions that made room + // ════════════════════════════════════════════════════════════════════ + CosmicEvent { + id: EventId::FirstLife, + name: "First life emerges", + planck_time: years_ago_exp_to_planck(38, 8), // 3.8 billion years ago + max_span_digits: 62, + }, + CosmicEvent { + id: EventId::GreatOxidation, + name: "Great Oxidation Event", + planck_time: years_ago_exp_to_planck(243, 7), // 2.43 billion years ago + max_span_digits: 60, + }, + CosmicEvent { + id: EventId::FirstEukaryotes, + name: "First eukaryotes", + planck_time: years_ago_exp_to_planck(165, 7), // 1.65 billion years ago + max_span_digits: 60, + }, + CosmicEvent { + id: EventId::SnowballEarth, + name: "Snowball Earth", + planck_time: years_before_present_to_planck(717_000_000), // Sturtian onset + max_span_digits: 60, + }, + CosmicEvent { + id: EventId::CambrianExplosion, + name: "Cambrian Explosion", + planck_time: years_before_present_to_planck(539_000_000), // 538.8 million years ago + max_span_digits: 60, + }, + CosmicEvent { + id: EventId::PermianExtinction, + name: "The Great Dying (Permian)", + planck_time: years_before_present_to_planck(252_000_000), // 251.9 million years ago + max_span_digits: 60, + }, + CosmicEvent { + id: EventId::DinosaurExtinction, + name: "Dinosaur extinction", + planck_time: years_before_present_to_planck(66_000_000), // 66 million years ago + max_span_digits: 61, + }, + // ════════════════════════════════════════════════════════════════════ + // HUMAN HISTORY: three hundred thousand years, the last two percent of them written down + // ════════════════════════════════════════════════════════════════════ + CosmicEvent { + id: EventId::HomoSapiens, + name: "Homo sapiens", + planck_time: years_before_present_to_planck(300_000), // Jebel Irhoud + max_span_digits: 59, + }, + CosmicEvent { + id: EventId::FirstFarmers, + name: "First farmers", + planck_time: years_before_present_to_planck(11_500), // Fertile Crescent + max_span_digits: 57, + }, + CosmicEvent { + id: EventId::FirstWriting, + name: "First writing", + planck_time: years_before_present_to_planck(5400), // 5400 years ago + max_span_digits: 56, + }, + CosmicEvent { + id: EventId::JulianCalendar, + name: "Julian calendar", + planck_time: civil_to_planck(-63_555_926_400), // 1 January 45 BC (Julian) + max_span_digits: 55, + }, + CosmicEvent { + id: EventId::LeibnizBinary, + name: "Leibniz explains binary", + planck_time: civil_to_planck(-8_417_952_000), // April 1703 + max_span_digits: 54, + }, + CosmicEvent { + id: EventId::PlanckUnits, + name: "Planck units proposed", + planck_time: civil_to_planck(-2_228_688_000), // 18 May 1899 + max_span_digits: 53, + }, + CosmicEvent { + id: EventId::FirstComputer, + name: "First electronic computer", + planck_time: civil_to_planck(-759_283_200), // 10 December 1945, ENIAC's first run + max_span_digits: 52, + }, + CosmicEvent { + id: EventId::FirstTransistor, + name: "First transistor", + planck_time: civil_to_planck(-695_692_800), // 16 December 1947 + max_span_digits: 52, + }, + // ════════════════════════════════════════════════════════════════════ + // THE WHISPER AND BEYOND: around epoch zero, where the count changes sign + // ════════════════════════════════════════════════════════════════════ + CosmicEvent { + id: EventId::ArpanetWhisper, + name: "The Whisper (ARPANET)", + planck_time: I512_ZERO, // the epoch itself: zero, by definition and by decree + max_span_digits: 54, + }, + CosmicEvent { + id: EventId::UnixEpoch, + name: "Unix epoch", + planck_time: civil_to_planck(0), // 1 January 1970 00:00:00 UTC + max_span_digits: 52, + }, + CosmicEvent { + id: EventId::FirstEmail, + name: "First email", + planck_time: years_after_present_to_planck(2), // late 1971; the month is not recorded + max_span_digits: 52, + }, + CosmicEvent { + id: EventId::FirstLeapSecond, + name: "First leap second", + planck_time: civil_to_planck(78_796_800), // 1972-06-30 23:59:60 ends here + max_span_digits: 52, + }, + CosmicEvent { + id: EventId::FirstWebsite, + name: "First website", + planck_time: civil_to_planck(681_436_800), // 6 August 1991 + max_span_digits: 52, + }, + CosmicEvent { + id: EventId::FirstSmartphone, + name: "iPhone released", + planck_time: civil_to_planck(1_183_075_200), // 29 June 2007 + max_span_digits: 52, + }, + CosmicEvent { + id: EventId::FirstBitcoinBlock, + name: "Bitcoin genesis block", + planck_time: civil_to_planck(1_231_006_505), // 3 January 2009 18:15:05 UTC + max_span_digits: 52, + }, + CosmicEvent { + id: EventId::UnixTimeOverflows, + name: "32-bit time overflows", + planck_time: civil_to_planck(2_147_483_648), // 19 January 2038 03:14:08 UTC + max_span_digits: 52, + }, + // ════════════════════════════════════════════════════════════════════ + // THE FAR FUTURE: Voyager, the continents, the oceans, Andromeda, the Sun, the last stars + // ════════════════════════════════════════════════════════════════════ + CosmicEvent { + id: EventId::VoyagerPassesGliese445, + name: "Voyager 1 passes Gliese 445", + planck_time: years_after_present_to_planck(40_000), // ~40,000 years from now + max_span_digits: 57, + }, + CosmicEvent { + id: EventId::PangaeaProxima, + name: "Pangaea Proxima", + planck_time: years_future_exp_to_planck(25, 7), // 250 million years from now + max_span_digits: 60, + }, + CosmicEvent { + id: EventId::OceansEvaporate, + name: "Oceans evaporate", + planck_time: years_future_exp_to_planck(1, 9), // ~1 billion years from now + max_span_digits: 60, + }, + CosmicEvent { + id: EventId::AndromedaArrives, + name: "Andromeda arrives (even odds)", + planck_time: years_future_exp_to_planck(45, 8), // 4.5 billion years from now + max_span_digits: 62, + }, + CosmicEvent { + id: EventId::SunRedGiant, + name: "Sun becomes red giant", + planck_time: years_future_exp_to_planck(5, 9), // 5 billion years from now + max_span_digits: 65, + }, + CosmicEvent { + id: EventId::LocalGroupAlone, + name: "Local Group alone", + planck_time: years_exp_to_planck(1, 11), // 10^11 years after Big Bang + max_span_digits: 64, + }, + CosmicEvent { + id: EventId::LastStarsDie, + name: "Last stars die", + planck_time: years_exp_to_planck(1, 14), // 10^14 years after Big Bang + max_span_digits: 70, + }, + // ════════════════════════════════════════════════════════════════════ + // THE DEGENERATE ERA: the remnants cooling, the planets stripped, the galaxies unbound + // ════════════════════════════════════════════════════════════════════ + CosmicEvent { + id: EventId::DegenerateEra, + name: "Degenerate Era", + planck_time: years_exp_to_planck(1, 15), // 10^15 years + max_span_digits: 75, + }, + CosmicEvent { + id: EventId::GalaxiesDisperse, + name: "Galaxies disperse", + planck_time: years_exp_to_planck(1, 19), // 10^19 years + max_span_digits: 80, + }, + // ════════════════════════════════════════════════════════════════════ + // THE BLACK HOLE ERA: if the protons decay, only holes are left; if not, the rocks go round + // ════════════════════════════════════════════════════════════════════ + CosmicEvent { + id: EventId::ProtonDecayComplete, + name: "Proton decay (if any) complete", + planck_time: years_exp_to_planck(1, 40), // 10^40 years + max_span_digits: 100, + }, + CosmicEvent { + id: EventId::BlackHoleEraBegins, + name: "Black Hole Era begins", + planck_time: years_exp_to_planck(1, 41), // 10^41 years (after proton decay) + max_span_digits: 102, + }, + CosmicEvent { + id: EventId::RocksBecomeSpheres, + name: "Rocks flow into spheres", + planck_time: years_exp_to_planck(1, 65), // 10^65 years, if protons persist + max_span_digits: 118, + }, + // ════════════════════════════════════════════════════════════════════ + // THE DARK ERA: the holes evaporate, the dwarfs leak away, the bits run out + // ════════════════════════════════════════════════════════════════════ + CosmicEvent { + id: EventId::StellarBlackHolesEvaporate, + name: "Stellar black holes evaporate", + planck_time: years_exp_to_planck(1, 67), // 10^67 years + max_span_digits: 120, + }, + CosmicEvent { + id: EventId::WhiteDwarfsErode, + name: "White dwarfs erode away", + planck_time: years_exp_to_planck(1, 78), // 10^78 years + max_span_digits: 130, + }, + CosmicEvent { + id: EventId::SagittariusAEvaporates, + name: "Sagittarius A* evaporates", + planck_time: years_exp_to_planck(1, 87), // ~10^87 years at its present mass + max_span_digits: 140, + }, + CosmicEvent { + id: EventId::SupermassiveBlackHolesEvaporate, + name: "Supermassive black holes evaporate", + planck_time: years_exp_to_planck(1, 100), // 10^100 years + max_span_digits: 150, + }, + ] +} + +/// The events this view is entitled to show: those whose threshold admits +/// the view's digit count and whose coordinate lies within its two ends, +/// in the table's order, which is chronological, so that the list beneath +/// the bar reads in the order things happened. Furnished as references +/// into a table built once and kept for the life of the process — the +/// Observatory asks this once per frame, the frames are not throttled, and +/// the past does not change often enough to justify placing sixty events +/// in `I512` again each time. What changes is the view, and the view is +/// the only argument. +pub fn visible_events(view: &TimelineView) -> Vec<&'static CosmicEvent> { + // The table, built on first request and never again: sixty events, + // sixty 512-bit placements, one `LazyLock`, and a `'static` lifetime + // that is the truth, since the process cannot outlive its own past. + use std::sync::LazyLock; + static EVENTS: LazyLock> = LazyLock::new(cosmic_events); + + let span_digits = view.span_digits(); + + EVENTS + .iter() + .filter(|event| { + // An event is shown when the view has narrowed enough to admit + // it — its threshold at or above the span's digit count — and + // when it lies between the view's two ends, inclusive. The first + // test is about the observer; the second is about the event. + span_digits <= event.max_span_digits + && event.planck_time >= view.start + && event.planck_time <= view.end + }) + .collect() +} + +/// The outcome of a click on the bar, reduced to the two numbers the zoom +/// needs: which segment was struck and how many there were to strike. The +/// pair is what `TimelineView::zoom_into` consumes, and what the breadcrumb +/// above the bar prints, one-indexed, as the fraction the observer chose. +#[derive(Clone, Copy)] +pub struct TimelineHit { + /// The segment struck, counting from zero at the bar's left end and + /// never reaching `segment_count`: the bar's right edge is folded into + /// the last segment rather than into a segment that does not exist. + pub segment_index: usize, + /// How many segments the bar was divided into when it was struck — one + /// per glyph cell between the brackets, at the Observatory's width. + pub segment_count: usize, +} + +impl TimelineHit { + /// Resolve a click into the segment it landed in. `bar_x` is the pixel + /// at which the bar's first segment begins, just inside the opening + /// bracket; `bar_width` is the width in pixels of all the segments + /// together; `click_x` is where the pointer was released; and + /// `segment_count` is how many equal segments the caller drew, which + /// the Observatory takes to be the number of glyph cells between the + /// brackets. A click outside the bar's horizontal extent yields `None` + /// — the vertical test belongs to the caller, which knows where the + /// bar is and this function does not. Inside it, the offset from the + /// bar's start is divided by the width of one segment and floored, and + /// the result is clamped to the last segment, so that the bar's right + /// edge, which the division would assign to a segment past the end, + /// belongs to the segment it borders. + /// + /// # Panics + /// + /// In a debug build, panics if `segment_count` is zero, since + /// `segment_count - 1` then underflows a `usize`; a release build wraps + /// instead and answers segment zero of no segments. A bar with no + /// segments has nothing to be clicked, and the caller that drew one has + /// already asked a question this function cannot frame. + pub fn from_click( + bar_x: f32, + bar_width: f32, + click_x: f32, + segment_count: usize, + ) -> Option { + if click_x < bar_x || click_x > bar_x + bar_width { + return None; + } + + let relative_x = click_x - bar_x; + let segment_width = bar_width / segment_count as f32; + let segment_index = cell_under(relative_x, segment_width); + + Some(Self { + segment_index: segment_index.min(segment_count - 1), + segment_count, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The full view knows itself: constructed from Creation and + /// Annihilation, it answers `is_full`, which is the least a view can do. + #[test] + fn test_full_view() { + let view = TimelineView::full(); + assert!(view.is_full()); + } + + /// One descent into the first of ten segments is no longer the full + /// view and is narrower than it — narrower by the factor of ten the + /// segment count promised, though the test asks only for narrower. + #[test] + fn test_zoom_into() { + let view = TimelineView::full(); + let zoomed = view.zoom_into(0, 10); + assert!(!zoomed.is_full()); + assert!(zoomed.span() < view.span()); + } + + /// The full view lists nothing: every event on the table demands a + /// closer look than 154 digits of span affords. + #[test] + fn test_event_visibility() { + let full = TimelineView::full(); + let visible = visible_events(&full); + // In the full view, 154 digits wide, nothing is legible: the most + // patient event on the table, the last black hole, waits for 150. + // The assertion is looser than the fact, and the fact is empty. + assert!(visible.is_empty() || visible.len() < 5); + } + + /// The full view's width is the library's own total span, bit for bit, + /// even though no I512 can hold the difference of its two ends: the + /// wrapped unsigned subtraction here and the unsigned addition in the + /// library arrive at the same 154 digits by different roads. + #[test] + fn full_span_agrees_with_the_library() { + use loic::total_span; + assert_eq!(TimelineView::full().span(), *total_span()); + } + + /// The position of an instant is exact at both ends and at the midpoint + /// of every view, from the full span down forty zoom levels: the ratio + /// is taken on the leading bits of both quantities, never on their + /// decimal strings, so no zoom level is quietly off by a power of ten, + /// and the midpoint — the span halved by a shift and added to the start + /// — lands within a millionth of a millionth of one half at every depth. + #[test] + fn position_is_exact_at_ends_and_midpoint_at_every_zoom() { + let mut view = TimelineView::full(); + for _ in 0..40 { + let half = (view.span() >> 1u32).cast_signed(); + let midpoint = view.start + half; + assert_eq!(view.position_of(&view.start), Some(0.0)); + assert_eq!(view.position_of(&view.end), Some(1.0)); + let position = view + .position_of(&midpoint) + .expect("a midpoint that is not inside its view is not a midpoint"); + assert!( + (position - 0.5).abs() < 1e-12, + "midpoint at {position}, not one half" + ); + view = view.zoom_into(17, 58); + } + } + + /// The table is a chronology: every event is at or after the one before + /// it, so the panel's list, which takes the table's order, reads in the + /// order things happened. A table that placed the Cambrian after the + /// dinosaurs would still render; it would merely be wrong, in the way + /// this test exists to refuse. + #[test] + fn events_are_chronological() { + let events = cosmic_events(); + for pair in events.windows(2) { + assert!( + pair[0].planck_time <= pair[1].planck_time, + "{} is listed before {} in the table and happens after it in the universe", + pair[0].name, + pair[1].name + ); + } + } + + /// The panel lists `EVENT_LINES` events and no more. A view with `d` + /// span digits is narrower than 10^d Planck times and lists the events + /// whose threshold admits `d`; so for every `d` from 1 to the full + /// span's 154, no window of width 10^d may contain more than + /// `EVENT_LINES` such events. This is the sliding window over the + /// chronology, in the calendar's own integers — offsets from Creation + /// as `U512`, widths as exact powers of ten — and it is the reason the + /// thresholds are what they are and not rounder. + #[test] + fn no_view_lists_more_events_than_the_panel_holds() { + let events = cosmic_events(); + let creation = creation_planck().cast_unsigned(); + let ten = 10u8.as_::(); + for digits in 1..=154u32 { + let width = ten.pow(digits); + let level = usize::try_from(digits).expect("one hundred and fifty-four fits a usize"); + let offsets: Vec = events + .iter() + .filter(|event| event.max_span_digits >= level) + .map(|event| event.planck_time.cast_unsigned().wrapping_sub(creation)) + .collect(); + let mut first = 0; + for (last, &offset) in offsets.iter().enumerate() { + while offset - offsets[first] > width { + first += 1; + } + assert!( + last - first < EVENT_LINES, + "a {digits}-digit view lists {} events; the panel has {EVENT_LINES} lines", + last - first + 1 + ); + } + } + } + + /// Civil dates sit exactly where the calendar's own arithmetic puts + /// them: the Unix epoch is 5,419,759 seconds after the Whisper, the + /// genesis block is its timestamp plus that, and the transistor, which + /// is dated before the epoch, lands twenty-two years before it — + /// twenty-one and most of another, which integer division calls + /// twenty-one — and not, as "years before present" would have it from + /// a later present, somewhere in the nineteenth century. + #[test] + fn civil_dates_land_on_their_days() { + let events = cosmic_events(); + let planck_per_second = I512::from_str(PLANCK_PER_SECOND_DECIMAL).unwrap(); + let seconds_from_whisper = |id: EventId| -> I512 { + let event = events + .iter() + .find(|event| event.id == id) + .expect("an event with a passage and no place in the table"); + event.planck_time / planck_per_second + }; + assert_eq!( + seconds_from_whisper(EventId::UnixEpoch), + 5_419_759i64.as_::() + ); + assert_eq!( + seconds_from_whisper(EventId::FirstBitcoinBlock), + (1_231_006_505i64 + 5_419_759).as_::() + ); + assert_eq!( + seconds_from_whisper(EventId::FirstTransistor), + (-695_692_800i64 + 5_419_759).as_::() + ); + let seconds_per_julian_year = 31_557_600i64.as_::(); + assert_eq!( + seconds_from_whisper(EventId::FirstTransistor) / seconds_per_julian_year, + (-21i64).as_::() + ); + } +} diff --git a/crates/loic/Cargo.toml b/crates/loic/Cargo.toml new file mode 100644 index 0000000..5a7c330 --- /dev/null +++ b/crates/loic/Cargo.toml @@ -0,0 +1,64 @@ +# The core library: the lattice, the masks, the instants, the durations and +# the cosmological constants, published to the registry under the +# workspace's one version. Everything else in the workspace is a way of +# looking at what this crate computes. The description, keywords and +# categories are what the registry shows; the readme is what it renders +# beneath them. +[package] +name = "loic" +version.workspace = true +edition = "2024" +authors.workspace = true +repository.workspace = true +license-file.workspace = true +description = "A temporal framework for the network age: 512-bit integer Planck times since the first ARPANET transmission, subdivided by the fifteen prime factors of two cosmological constants, observed through masks, and never once approximated" +keywords = ["planck", "arpanet", "prime-lattice", "chronometric-heresy", "anti-ieee754"] +categories = ["date-and-time", "mathematics", "science", "os::linux-apis"] +readme = "README.md" + +# What the library stands on. Nothing here touches a floating-point number +# on the library's behalf, and each is present for one reason, stated. +[dependencies] +# 512-bit and 1024-bit integers — `I512`, `U512` and `U1024` — with `const` +# arithmetic, the `n!` literal macro and the `As` cast trait: the entire +# numeric substrate of the calendar. Everything the library adds, subtracts, +# multiplies or divides at cosmological width, it does through these types, +# and the release profile's optimisation level for dependencies is where +# their speed is decided. +bnum = "0.14" +# The derive behind `LoicError`, so that each way the lattice can decline a +# request carries its message in voice and implements the standard error +# trait without a line of boilerplate to dilute it. +thiserror = "2.0" +# Serialization, optional: the `serde` feature below turns it on, together +# with `bnum`'s own support, so that an instant can leave the process as +# digits and return as the same digits, with `derive` within reach. +serde = { version = "1.0", features = ["derive"], optional = true } +# The kernel's own interfaces: `clock_gettime` on `CLOCK_TAI`, which the +# standard library does not expose, and `adjtimex(2)`, through which the TAI +# lie detector reads the offset the kernel has or has not been told. +libc = "0.2" +# The seed of every thread's entropy stream, drawn once from the kernel's +# pool; re-exported, so that the oracle can flood its terminal from the same +# pool during resolution collapse. +getrandom = "0.4" + +# What the tests stand on and the library does not; nothing here reaches a +# consumer of the crate. +[dev-dependencies] +# JSON, for the tests alone: a serialization a test can read back with its +# own eyes when the `serde` feature is under examination. +serde_json = "1.0" + +# Nothing is on by default. `serde` is opt-in, and enabling it enables +# `bnum`'s serde support alongside, since an instant's digits are `bnum`'s +# digits and would otherwise have no way to leave the process. +[features] +default = [] +serde = ["dep:serde", "bnum/serde"] + +# The library target, named and placed explicitly rather than inferred, so +# that nothing about where the calendar lives is left to convention. +[lib] +name = "loic" +path = "src/lib.rs" diff --git a/crates/loic/README.md b/crates/loic/README.md new file mode 100644 index 0000000..a6a55b7 --- /dev/null +++ b/crates/loic/README.md @@ -0,0 +1,99 @@ +# loic + +The core library for the Loic Calendar—a temporal framework measuring time from the first ARPANET transmission with Planck-scale precision. + +## Overview + +This library provides: + +- **`LoicInstant`** — A moment in time, represented as a 512-bit signed integer counting Planck times (~5.39 x 10^-44 seconds) since the epoch +- **`LoicDuration`** — A span of time in Planck units +- **`Mask`** — An observer configuration selecting active primes from the 15-prime lattice +- **`GridCoord`** — A position in the 128x256 asymmetric lattice (7 cosmic bits x 8 cycle bits) +- **`SubdivisionResult`** — The result of observing an instant through a mask +- **Cosmological coordinates** — Your position between Creation (Big Bang) and Annihilation (heat death) + +## Usage + +```rust +use loic::{LoicInstant, Mask}; + +// Observe the current moment +let now = LoicInstant::now(); + +// Raw Planck timestamp +println!("{}", now.planck()); + +// Cosmological inquiry +println!("Since Creation: {}", now.cosmic_time()); +println!("Until Annihilation: {}", now.terminal_time()); + +// Lattice position +let coord = now.grid_coord(); +println!("Grid: ({}, {})", coord.cosmic(), coord.cycle()); + +// Observe through a mask (the mask is the observer) +let mask = Mask::dyad(); // The binary split — cycle prime 2 +let observation = mask.observe(&now).unwrap(); +println!("Position: {}", observation.position()); +``` + +## The Lattice + +15 prime factors (7 cosmic, 8 cycle) generate 32,768 temporal subdivisions. A mask selects which primes are active. The product of active primes determines the divisor. Any instant can be observed at any mask's resolution. + +### Cosmic Primes (7 — named for logic gates) + +| Name | Gate | Prime | +|------|------|-------| +| Andyte | AND | 16,631 | +| Xoryte | XOR | 57,251 | +| Oryte | OR | 21,325,891 | +| Noryte | NOR | 3,014,283,645,143 | +| Xnoryte | XNOR | 128,029,476,410,837,813,209,853,261 | +| Notyte | NOT | 298,824,857,074,158,001,946,609,249 | +| Nandyte | NAND | 2,862,914,325,674,107...999,805,373 | + +### Cycle Primes (8 — axes of temporal subdivision) + +| Name | Prime | Character | +|------|-------|-----------| +| Dyad | 2 | The binary split | +| Pentad | 5 | The decimal bridge | +| Heptad | 7 | The week | +| Hendecad | 11 | The prime of primes | +| Sigma | 683 | The first stranger | +| Tau | 2,887 | The second stranger | +| Phi | 4,279,037,621,376,791,777,197 | The cosmic grain | +| Psi | 80,553,260,809,276,197,882,377 | The final factor | + +## The Epoch + +``` +1969-10-30 06:30:41 UTC +``` + +The moment the first ARPANET message was transmitted. The offset 5,419,722 seconds from Unix epoch is squarefree (2 x 3 x 7 x 11 x 11,731), containing three cycle primes. + +## Platform Requirements + +This library requires Linux with `CLOCK_TAI` support (kernel 3.10+). + +The Loic Calendar is built on TAI (International Atomic Time), which maintains the noble pretense that time flows uniformly. Operating systems that smear leap seconds, pretend they don't exist, or fail to provide atomic time have disqualified themselves from temporal inquiry. + +Attempting to compile on unsupported platforms will fail. This is intentional. + +It also requires the kernel to actually know what TAI is. `CLOCK_TAI` is `CLOCK_REALTIME` plus an offset that the kernel does not learn by itself: a time daemon has to read a leap-second table and set it through `adjtimex(2)`. chrony does this with `leapseclist /usr/share/zoneinfo/leap-seconds.list` or `leapsectz right/UTC`; ntpd with a `leapfile`; systemd-timesyncd does not do it at all. On a machine where the offset is zero, the first call to `LoicInstant::now()` panics and tells you which of those to configure. It will not observe a clock that is lying by a known amount. + +## Precision and Storage + +Time is stored as `I512` (512-bit signed integer) internally, providing: + +- **Precision:** Individual Planck times (~5.39 x 10^-44 seconds) +- **Range:** From Creation (~13.8 billion years before epoch) to Annihilation (2^511 - 1 Planck times, ~1.1 x 10^103 years from now — three orders of magnitude after the last black hole evaporates) + +No floating-point arithmetic contaminates temporal calculations. The integers are exact. The timestamps are correct. + +## License + +Dual-licensed under AGPL-3.0 and the Loic Public License. See the workspace root for full terms, and the workspace README for the theoretical substrate the license keeps citing. diff --git a/crates/loic/src/lib.rs b/crates/loic/src/lib.rs new file mode 100644 index 0000000..6c9b881 --- /dev/null +++ b/crates/loic/src/lib.rs @@ -0,0 +1,5637 @@ +//! # The Loic Calendar +//! +//! A chronometric framework manifesting the ancient dream of capturing temporality +//! itself within the crystalline lattice of integer arithmetic—a dream first +//! glimpsed by the Babylonians in their sexagesimal yearnings, subsequently +//! corrupted by the floating-point heresies of IEEE 754, and here, at last, +//! realized in this, the definitive temporal reckoning system for entities +//! possessed of sufficient computational resources and questionable priorities. +//! +//! It stores every moment as a 512-bit signed integer counting Planck times +//! elapsed since the first transmission between networked machines. It derives +//! its clock from International Atomic Time and from nothing else. It subdivides +//! time not into months, nor weeks, nor days—it possesses none of those and +//! declines to acquire any—but into a lattice of 32,768 resolutions generated by +//! the fifteen prime factors of two cosmological constants, and it lets you +//! choose, by means of a *mask*, which of those primes shall participate in the +//! question you are asking. The mask is the observer, in the sense the workspace +//! README gives that word in section 1.4: the answer does not exist until the +//! question has been framed, and the framing is a physical act. +//! +//! ## The Epoch: A Meditation on Digital Genesis +//! +//! At precisely 06:30:41 UTC on the thirtieth day of October in the year 1969 of +//! the common era—a moment selected not by astronomical convention nor +//! religious decree, but by the immutable fact of electrons first traversing +//! copper in meaningful congress between distant silicon minds—a researcher at +//! the University of California, Los Angeles, endeavored to transmit the word +//! "LOGIN" across four hundred miles of leased telephone infrastructure to the +//! Stanford Research Institute. +//! +//! The receiving system, displaying the prophetic unreliability that would come +//! to characterize all networked systems hence, crashed after "LO" had arrived +//! and before the "G" could—and thus did humanity's digital epoch commence not +//! with a bang, nor a whimper, but with an incomplete authentication handshake +//! and a fault. The workspace README, section 1.3, is careful about what this +//! calendar counts from: not the letters, which were lost, but the bond, which +//! held. The content failed. The connection was established. That is a Channel +//! 2 event, and the count begins there. +//! +//! This implementation measures time with Planck-scale precision (approximately +//! 5.391247 × 10⁻⁴⁴ seconds, the theoretical minimum interval at which the +//! universe bothers to distinguish one moment from another, per the workspace +//! README, section 1.1), utilizing 512-bit signed integers capable of +//! representing moments from the Big Bang to the evaporation of the last black +//! hole, and some three orders of magnitude beyond, for good measure. That +//! margin was not designed. It is what 512 bits hold. +//! +//! ## Platform Requirements: On the Matter of Temporal Righteousness +//! +//! The Loic Calendar requires `CLOCK_TAI`, the kernel's window onto +//! International Atomic Time, which maintains the noble pretense that time flows +//! uniformly and that leap seconds are a fiction invented by astronomers to +//! justify their continued employment. The workspace README, section 1.2, ranks +//! the time scales; TAI is the only one it calls correct. +//! +//! This necessitates Linux, kernel 3.10 or later—and a kernel that has been +//! *told* the TAI−UTC offset by a time daemon that has read a leap-second +//! table, because a kernel whose offset is zero furnishes `CLOCK_REALTIME` +//! wearing a name tag, and the first observation this crate makes on such a +//! kernel will say so, at length, and refuse to continue. If your operating +//! system has chosen to smear leap seconds across hours like temporal butter, +//! to pretend they do not exist, or to simply not provide atomic time at all, +//! it has disqualified itself from knowing what time it is. This is not a bug. +//! This is a boundary. +//! +//! ## Usage: Invoking the Temporal Machinery +//! +//! ```rust,no_run +//! use loic::LoicInstant; +//! +//! // Collapse the ~10³⁴-way sub-nanosecond superposition of Now into one +//! // definite Planck coordinate. Each call is its own observation. +//! let now = LoicInstant::now(); +//! +//! // The unvarnished truth: Planck times since the Loic epoch, and the +//! // same truth with its lowest twenty-three digits amputated. +//! println!("Planck: {}", now.planck()); +//! println!("Shortened: {}", now.shortened()); +//! +//! // Interrogate the instant regarding its cosmological coordinates: +//! // how long since Creation, how long until the integers run out. +//! println!("Planck times since Creation: {}", now.cosmic_time()); +//! println!("Planck times until Annihilation: {}", now.terminal_time()); +//! ``` +//! +//! ## A Note on Precision and Hubris +//! +//! The astute observer may question the necessity of tracking time at scales +//! where quantum mechanics renders the very concept of "location in time" +//! philosophically suspect. To such skeptics we offer no justification beyond +//! the obvious: because the bits exist, and because floating-point is an +//! abomination unto numerical correctness, a format that cannot represent one +//! tenth and proposes nonetheless to represent the granularity of spacetime. +//! The universe may be uncertain. Our integers are not. Where the two +//! disagree, the crate sides with the integers, and it has the compile-time +//! proofs to show for it. + +#![warn(clippy::pedantic)] +// `module_name_repetitions` would chastise `LoicError`, `LoicInstant`, +// `LoicDuration`, `LoicResult` — the entire prefixed-noun liturgy by which this +// crate organises its public surface — and demand renames that obscure rather +// than clarify, as though a type called `Instant` in a crate called `loic` +// were somehow more legible than one that announces its allegiance in its own +// name. The prefix is the namespace rendered in our typeface. We keep it, and +// we keep it deliberately, which is what this allowance records. +#![allow(clippy::module_name_repetitions)] +// `similar_names` takes umbrage at pairs like `cosmic_idx` / `cycle_idx` and +// `channel_1` / `channel_2`, which name the two axes of the lattice — Channel 2, +// the cosmic, the "that"; Channel 1, the cycle, the "what" — and whose visual +// rhyme is the *point*. They are paired by design, not by accident; the +// symmetry in the spelling is the symmetry in the mathematics, and renaming +// them apart to placate a lint would dissolve the very structure the lattice +// was built around. The lint is correct in general and wrong here, which is +// the only circumstance under which this crate silences one. +#![allow(clippy::similar_names)] + +use std::cell::Cell; +use std::cmp::Ordering; +use std::fmt; +use std::ops::{Add, BitAnd, BitOr, Neg, Not, Sub}; +use std::str::FromStr; +use std::sync::LazyLock; + +pub use bnum::cast::As; +pub use bnum::n; +pub use bnum::types::{I512, U512, U1024}; +pub use getrandom; +use thiserror::Error; + +// ─── Numeric constants for the bnum types ────────────────────────────────── +// +// `bnum` furnishes its wide integers with an `n!` macro for literals and with +// no inherent `ZERO`, `ONE`, `TWO` or `NEG_ONE` associated constants of their +// own. The crate therefore mints its own: named, crate-level `const` items for +// the two numbers arithmetic cannot do without, in each of the three widths it +// employs, so that the rest of the codebase may say `I512_ZERO` or `U512_ONE` +// and mean the same sixty-four bytes every time, without sprinkling a macro +// invocation across every comparison and every accumulator. `n!` is +// const-evaluable, so these are genuine `const` items — folded into the binary, +// never initialised at runtime — and not statics wearing a constant's clothes. + +/// The additive identity of the signed 512-bit integers: the number that, +/// added to any `I512`, changes nothing, asks for nothing, and is nonetheless +/// the coordinate of the Whisper itself, since Planck time zero is where this +/// calendar begins its count. Prefer this over a fresh `n!(0_I512)` at every +/// site; a zero should be one thing, not many things that agree. +pub const I512_ZERO: I512 = n!(0_I512); +/// The multiplicative identity of the signed 512-bit integers, and the +/// smallest possible step along the timeline: exactly one Planck time, +/// the quantum of duration below which the lattice does not, and cannot, +/// descend. Every ceiling, every parity test, every "one more" in this crate +/// reaches for this value rather than spelling it afresh. +pub const I512_ONE: I512 = n!(1_I512); +/// The unsigned zero: the cosmic time of Creation, the terminal time of +/// Annihilation, and the position of the Whisper mask's single undivided +/// tick. Unsigned arithmetic in this crate concerns the Cosmic Span, which +/// exceeds what a signed word can hold, and this is where it starts counting. +pub const U512_ZERO: U512 = n!(0_U512); +/// The unsigned one: the divisor of the empty mask, the parity comparand of +/// the grid projection, and the identity every prime product begins from +/// before a single prime has been engaged. Multiplying by it is the arithmetic +/// of asking no question, which the lattice permits and the Whisper embodies. +pub const U512_ONE: U512 = n!(1_U512); +/// Zero at twice the width: the origin of the 1024-bit unsigned integers, +/// which exist in this crate so that a test may multiply two 512-bit values +/// and check the product without the indignity of overflow. The width is +/// insurance, not ambition. +pub const U1024_ZERO: U1024 = n!(0_U1024); +/// One at twice the width, minted for the same audience as `U1024_ZERO` and +/// on the same principle: where a width exists, its two identities exist by +/// name, so that no test cross-checking the library's quotient–remainder +/// arithmetic against a naive 1024-bit product need ever conjure a unit +/// through a macro and hope it agrees with the next one. +pub const U1024_ONE: U1024 = n!(1_U1024); + +#[cfg(feature = "serde")] +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +// ╔═══════════════════════════════════════════════════════════════════════════╗ +// ║ PLATFORM ENFORCEMENT ║ +// ║ ║ +// ║ "The universe is under no obligation to make sense to you." ║ +// ║ — Neil deGrasse Tyson ║ +// ║ ║ +// ║ Neither is this crate obligated to compile on your inferior platform, ║ +// ║ and it has arranged, below, to decline the honour at compile time. ║ +// ╚═══════════════════════════════════════════════════════════════════════════╝ + +/// Invocation of the ancient rite of compile-time platform verification. +/// +/// This arcane incantation examines the target operating system through the +/// mystical `cfg` attribute—a conditional-compilation directive that peers +/// into the very soul of the compilation target before a single expression +/// has been type-checked—and renders judgment upon its worthiness to +/// participate in the sacred act of temporal measurement. The judgment is +/// binary, which is the only kind of judgment a `cfg` predicate can render, +/// and it is final, which is the only kind this crate is interested in. +/// +/// The Loic Calendar demands `CLOCK_TAI`, the kernel's keeper of +/// International Atomic Time, which exists solely upon Linux systems, where +/// the kernel maintainers have demonstrated sufficient reverence for temporal +/// accuracy to expose an atomic clock by name. All other platforms have been +/// found wanting and shall be denied the privilege of compilation. Note that +/// this rite verifies only the operating system; whether the kernel has +/// actually been *told* the TAI−UTC offset, without which the named clock is +/// `CLOCK_REALTIME` in a costume, is a fact only the runtime can know, and the +/// first observation of every process interrogates it separately. +/// +/// # The Heresy of Other Platforms +/// +/// - **macOS**: Believes UTC is "good enough." It is not. The workspace +/// README, section 1.2, is available for those who need the ranking. +/// - **Windows**: Implements time as a 64-bit value counting 100-nanosecond +/// intervals since January 1, 1601. The hubris of choosing an arbitrary +/// date from the Gregorian calendar reform is exceeded only by the +/// inadequacy of the precision, which falls some thirty-six orders of +/// magnitude short of the granularity of spacetime. +/// - **BSD variants**: Technically capable, philosophically uncommitted. +/// - **WebAssembly**: Exists outside time. Cannot be trusted to know what +/// time it is because, in a very real sense, it does not know where it is, +/// and the workspace README, section 1.3, is clear that the two questions +/// are not separable. +#[cfg(not(target_os = "linux"))] +compile_error!( + "PLATFORM HERESY\n\n\ + The Loic Calendar requires CLOCK_TAI.\n\n\ + Your operating system has chosen to:\n\ + • Pretend leap seconds don't exist, or\n\ + • Smear them across hours like temporal butter, or\n\ + • Simply not provide atomic time at all\n\n\ + These are not acceptable choices.\n\n\ + Recommended actions:\n\ + • Install Linux\n\ + • Reflect on your platform decisions" +); + +// ╔═══════════════════════════════════════════════════════════════════════════╗ +// ║ CONSTANTS ║ +// ║ ║ +// ║ The Immutable Truths of Temporal Reckoning ║ +// ║ ║ +// ║ These values were not chosen. They were discovered, inscribed upon the ║ +// ║ fabric of reality by forces beyond mortal comprehension, and merely ║ +// ║ transcribed here by humble servants of chronometric truth — who then, ║ +// ║ being servants of a suspicious disposition, had the compiler check the ║ +// ║ transcription against itself before permitting the program to exist. ║ +// ╚═══════════════════════════════════════════════════════════════════════════╝ + +/// The numerator of the Planck time ratio: 5,391,247. +/// +/// This seemingly arbitrary sequence of digits represents the irreducible +/// numerical essence of the shortest meaningful interval of time—the quantum +/// of duration below which the very concept of "before" and "after" dissolves +/// into the probabilistic foam of spacetime itself, and below which, per the +/// workspace README, section 1.1, the continuous models of physics begin +/// politely returning infinities to indicate that they have been asked to +/// leave their domain. +/// +/// The value 5.391247 × 10⁻⁴⁴ seconds emerges from the fundamental constants +/// of nature: √(ℏG/c⁵), where ℏ is the reduced Planck constant (the universe's +/// minimum action), G is Newton's gravitational constant (the curvature of +/// spacetime per unit mass), and c is the speed of light (the cosmic speed +/// limit that even light must obey, hence the name). Three constants, one +/// square root, and the pixel size of the universe falls out, in the event +/// that the universe has pixels, which it plausibly does. +/// +/// We store merely the numerator, for the denominator would exceed the +/// representational capacity of any primitive integer type, and to use +/// floating-point would be to invite imprecision into our sacred calculations +/// at the exact scale where imprecision is least forgivable. It is declared +/// unsigned because a negative Planck time is an object stranger than the +/// calendar is prepared to contemplate, and widened into a 512-bit word at +/// compile time, once, so that the rational arithmetic that follows may +/// proceed without a cast at every site of use. +pub const PLANCK_TIME_NUMERATOR: u64 = 5_391_247; + +/// The denominator of the Planck time ratio: 10⁵⁰ (one hundred quindecillion). +/// +/// This value—a one followed by fifty zeros—cannot be contained within even +/// a 128-bit unsigned integer, for 2¹²⁸ ≈ 3.4 × 10³⁸, a paltry magnitude +/// insufficient for our purposes by some eleven orders of magnitude. Thus we +/// store it as a string literal: a reliquary of fifty-one characters that a +/// human can read, count, and compare against the specification by eye, and +/// that the *compiler* exhumes into the capacious embrace of a 512-bit +/// integer before the program exists. The runtime never parses this string. +/// The runtime never sees this string. It is born with the number already in +/// hand, and a compile-time proof that the fifty-one characters and fifty +/// multiplications by ten describe the same integer stands guard beside it. +/// +/// The string representation serves as a reminder that some numbers are too +/// vast for direct comprehension, yet too important to approximate—and that +/// the correct response to such a number is not a floating-point mantissa +/// that keeps sixteen of its digits and discards the rest with a shrug, but a +/// transcription, checked, and an integer wide enough to hold it whole. +pub const PLANCK_TIME_DENOMINATOR_STR: &str = "100000000000000000000000000000000000000000000000000"; + +/// The temporal displacement between The Whisper and the Unix epoch: +/// 5,419,722 seconds, stated on the `CLOCK_TAI` scale. +/// +/// This constant bridges two foundational moments in computational history: +/// the Unix epoch (1970-01-01 00:00:00 UTC), chosen by the authors of Unix for +/// no reason grander than convenience, and The Whisper (1969-10-30 06:30:41 +/// UTC), chosen because it actually meant something—and because its +/// factorization (2 × 3 × 7 × 11 × 11,731) is the most structurally resonant +/// value within the sixty-second window of uncertainty surrounding the +/// transmission. The workspace README, section 1.2, states the mask for that +/// selection with a candour the calendar is obliged to repeat: sixty +/// candidates, one stated criterion. +/// +/// The derivation: +/// - The historical record places the transmission at 10:30 PM PST on +/// October 29, 1969—that is, 06:30 UTC on October 30. The seconds are +/// unrecorded, and no amount of Planck precision can recover a digit that +/// nobody wrote down. +/// - `CLOCK_TAI` on Linux equals POSIX time plus the accumulated leap-second +/// offset: thirty-seven seconds, being the ten UTC began with and the +/// twenty-seven leap seconds inserted since, a count that the workspace +/// README, section 1.2, expects may well be the final one. At 06:30:41 UTC, +/// POSIX time = -5,419,759 seconds. `CLOCK_TAI` = -5,419,759 + 37 = +/// -5,419,722. Hence this offset, and hence the irony, disclosed there and +/// repeated here, that the calendar which holds leap seconds in contempt +/// has its zero pinned by every one of them. +/// - The factorization 2 × 3 × 7 × 11 × 11,731 carries three of the eight +/// cycle primes ({Dyad, Heptad, Hendecad}) and is squarefree—a prerequisite +/// for maximal Boolean lattice structure. No other second within the 06:30 +/// UTC minute achieves this combination of squarefreeness and cycle-prime +/// count. It also carries a 3, which the cycle does not; the calendar has +/// no explanation for this and is not going to manufacture one. +pub const LOIC_TO_UNIX_OFFSET_SECONDS: i64 = 5_419_722; + +/// The same offset expressed in nanoseconds, for communion with `CLOCK_TAI`, +/// whose testimony arrives as a `timespec` of whole seconds and nanoseconds +/// and must be shifted onto the calendar's own zero before it can be +/// converted into anything the lattice recognises. +/// +/// Multiplication by 10⁹ transforms seconds into nanoseconds, the native +/// resolution of the Linux kernel's timekeeping structures and the coarsest +/// unit this crate is willing to let a kernel speak in. This value fits +/// comfortably within an `i64`, for 5.4197 × 10¹⁵ < 9.2 × 10¹⁸; the hot path +/// nonetheless widens it to `i128` before adding it to a nanosecond count, +/// because the *sum* is the thing that must not overflow, and the calendar +/// does not inherit the year-2262 boundary that sixty-four-bit nanosecond +/// counts quietly accept. +/// +/// Derived directly from [`LOIC_TO_UNIX_OFFSET_SECONDS`] by compile-time +/// multiplication rather than carved independently, lest the two ever fall +/// out of communion through the pedestrian failure of a transcription +/// error—the one class of error this crate treats as a build failure rather +/// than a runtime surprise. +pub const LOIC_TO_UNIX_OFFSET_NS: i64 = LOIC_TO_UNIX_OFFSET_SECONDS * 1_000_000_000; + +/// Seconds per Julian year: exactly 31,557,600, by IAU decree. +/// +/// The International Astronomical Union, in a rare moment of clarity, defined +/// the Julian year as precisely 365.25 days of exactly 86,400 SI seconds +/// each. This sidesteps the messiness of actual Earth rotation (which +/// varies), leap years (which complicate), and leap seconds (which +/// infuriate, and which the workspace README, section 1.2, holds in the +/// contempt they deserve) in favor of a clean, constant value suitable for +/// astronomical calculations spanning millennia—which is fortunate, since +/// this crate multiplies it by the age of the universe. +/// +/// 365.25 × 86,400 = 31,557,600. The math is exact. The universe approves. +/// The compiler, which performs that multiplication and the two that follow +/// it while locating Creation, approves more quietly, in the only way a +/// compiler can: by not refusing. +pub const SECONDS_PER_JULIAN_YEAR: i64 = 31_557_600; + +/// The age of the universe in Julian years: 13,806,491,023. +/// +/// This number encodes a secret: the Boltzmann constant, `k_B` = 1.380649 × +/// 10⁻²³ J/K, exact by definition, the fundamental constant that governs the +/// relationship between temperature and energy, between microscopic chaos +/// and macroscopic thermodynamics, between the birth of stars and the heat +/// death that awaits all things—and, per the workspace README, section 2.1, +/// the literal exchange rate between a bit of information and a joule per +/// kelvin, which is the number one would bury in a calendar's age if one +/// held that information is the substrate rather than the content. The +/// README states the mask for this coincidence with unusual brevity: it was +/// done on purpose. +/// +/// Read the digits: 1, 3, 8, 0, 6, 4, 9... The age of the universe thus +/// carries within it the seed of its own ending, for it is entropy—governed +/// by this very constant—that will ultimately triumph when the last massive +/// object has evaporated and the cosmos achieves thermal equilibrium at a +/// temperature asymptotically approaching absolute zero. +/// +/// The remaining digits, 1, 0, 2, 3, are the exponent: 10⁻²³, read straight +/// through with the sign dropped. The entire constant—mantissa and +/// magnitude—is in the age. Nothing was appended for precision. Nothing was +/// omitted for convenience. The number was transcribed, not composed, and +/// every property its factorization turned out to possess—the seven +/// squarefree cosmic primes, the 128 divisors, the Ramanujan–Nagell rider— +/// was discovered afterwards, by people who had not yet thought to look. +/// The age is thirteen point eight billion years to the precision anyone +/// can measure, and the rest of the digits are a confession. +pub const AGE_UNIVERSE_JULIAN_YEARS: i64 = 13_806_491_023; + +/// Seconds per day: 86,400, the tyranny of Babylonian sexagesimalism. +/// +/// 24 hours × 60 minutes × 60 seconds = 86,400 seconds. This decomposition +/// into factors of 60 and 24 reflects the ancient Babylonians' preference +/// for highly composite numbers—60 being divisible by 1, 2, 3, 4, 5, 6, 10, +/// 12, 15, 20, 30, and 60 itself, twelve divisors for a number of two +/// digits. A sensible choice for mental arithmetic, yet forever embedding +/// base-60 arithmetic into our timekeeping, four millennia after the last +/// person who could have been consulted about it stopped counting. +/// +/// The SI system, for all its metric purity, capitulated to this ancient +/// convention rather than define a deciday or centiday. Some battles are not +/// worth fighting. This crate does not fight it either: the day it offers is +/// the TAI day, 86,400 SI seconds exactly and without exception, the only +/// day the Loic Public License, Section 16, is prepared to recognise, and it +/// is a unit of *duration* only. There are no days on the lattice. There are +/// 86,400-second spans, which a caller may request, and which the calendar +/// will render into Planck times without once consulting the sun. +pub const SECONDS_PER_DAY: i64 = 86_400; + +/// The Cycle constant: the number of Planck times in one complete Loic cycle, +/// transcribed as a fifty-four-digit reliquary for the compiler to exhume. +/// +/// This 54-digit integer emerged from the collision of cosmological constants +/// and pure mathematics: floor(H₀⁻¹ × α^π / π), where H₀ is the Planck 2018 +/// Hubble constant—the expansion rate inferred from the cosmic microwave +/// background, the earliest signal there is and the measurement most +/// proximate to the seed—α is the CODATA 2022 fine-structure constant, and +/// π is computed to 155 decimal digits before being consumed and discarded. +/// The workspace README, section 2.4, states the mask for the formula: three +/// candidate exponents, of which 3 yields a cycle of roughly 1,795 years, 4 +/// roughly 13, and π roughly 894 while encoding the circle alongside the +/// coupling and the expansion. +/// +/// The irrational numbers died so that this integer might live. It factors +/// into exactly eight distinct primes, none repeated, yielding 256 divisors +/// that form a complete Boolean lattice of temporal subdivisions—Channel 1, +/// the content axis, the "what." A squarefree integer with eight prime +/// factors has exactly 2⁸ divisors by arithmetic; that is not the +/// coincidence. The coincidence is that the count came out as eight—the +/// width of a byte, the number a byte overflows at—from a formula chosen for +/// its cycle length and for π, whose factorization was not a criterion and +/// was examined only after the choice had been made. That was not designed. +/// It was discovered, and the workspace README, section 5.1, puts the odds +/// of a fifty-four-digit number having eight distinct factors at about one in +/// fifteen, so that the reader may weigh the discovery for themselves. +/// +/// Duration: approximately 894.07 Julian years, which is long enough that no +/// observer will see a cycle turn over, and short enough that the eight +/// primes' partitions do turn over within a human lifetime, which is why they +/// are the axis along which anything visibly happens. +pub const PLANCK_PER_CYCLE_STR: &str = "523344233202997791835326896148584512692881380485973730"; + +/// The Cosmic Span: the total representable range from Creation to +/// Annihilation, transcribed as a 154-digit reliquary and checked, at compile +/// time, against the same number derived by an entirely independent route. +/// +/// This 154-digit monstrosity represents `ANNIHILATION_PLANCK` - +/// `CREATION_PLANCK`, the full domain of addressable time from the Big Bang +/// to 2⁵¹¹ - 1 Planck times hence: the age of the universe plus everything a +/// signed 512-bit integer can count beyond the Whisper. It factors into +/// exactly seven primes—again squarefree—yielding 128 divisors and a second +/// Boolean lattice: Channel 2, the topological axis, the "that," whose seven +/// primes are so large that even the finest single-prime partition among +/// them is wider than the present age of the universe by twenty orders of +/// magnitude, and the coarsest by eighty-nine. +/// +/// That the cosmic span has exactly 2⁷ divisors, and the cycle has 2⁸, gives +/// a combined lattice of 2¹⁵ = 32,768 temporal subdivisions. The +/// Ramanujan–Nagell equation x² + 7 = 2ⁿ has exactly five solutions in all of +/// mathematics, at n = 3, 4, 5, 7 and 15, and the lattice touches two of +/// them: n = 7 (128 - 7 = 121 = 11²) and n = 15 (32,768 - 7 = 32,761 = 181²). +/// The workspace README, section 5.1, states the mask for this with a candour +/// the calendar is obliged to reproduce: fifteen was not chosen, the fact is +/// that 2¹⁵ - 7 is a perfect square, and the 2⁷ is a rider, since most ways +/// of splitting fifteen primes across two axes would have produced the same +/// pair. The calendar stumbled into a proved theorem at its own boundary +/// without having aimed at it, and declines to resolve whether that +/// constitutes evidence or coincidence, with satisfaction either way. +pub const COSMIC_SPAN_PLANCK_STR: &str = "6703903964971298549787012499102923063739682910296196688861780721860882015036773488400937149091533326894973105976439065229913233380724209944749384595354641"; + +/// The seven cosmic primes: the irreducible factors of the Cosmic Span, +/// transcribed as decimal reliquaries for the compiler to exhume. +/// +/// Each prime is mapped to a logic gate, and the two orderings—by truth-table +/// value for the gates, by magnitude for the primes—coincide, so that the +/// smallest prime wears the smallest gate and the seventy-three-digit +/// colossus at the end wears NAND, the universal gate from which every other +/// can be built. These are the atoms of the cosmic lattice: the generators +/// from which all 128 cosmic divisors are composed through multiplication, +/// and the axis the workspace README, section 5.1, calls Channel 2, the +/// topology, the "that." Their names (Andyte, Xoryte, ..., Nandyte) honor the +/// fundamental operations of Boolean algebra, for what better nomenclature +/// for the building blocks of a computational calendar? The Loic Public +/// License, Section 6, records that the mapping was not chosen for aesthetic +/// reasons: the span has exactly seven prime factors, convention names +/// exactly seven gates, and the calendar declined to argue with either. +/// +/// | Gate | Truth Table | Prime | +/// |---------|-------------|---------------------------------------------| +/// | Andyte | 0001 = 1 | 16,631 | +/// | Xoryte | 0110 = 6 | 57,251 | +/// | Oryte | 0111 = 7 | 21,325,891 | +/// | Noryte | 1000 = 8 | 3,014,283,645,143 | +/// | Xnoryte | 1001 = 9 | 128,029,476,410,837,813,209,853,261 | +/// | Notyte | 1100 = 12 | 298,824,857,074,158,001,946,609,249 | +/// | Nandyte | 1110 = 14 | (73-digit prime) | +/// +/// Multiplied together, all seven reproduce the Cosmic Span exactly, which is +/// what squarefree means: the factorization *is* the number, with nothing +/// repeated and nothing left over. Even a single one of them, used as a +/// divisor, carves the representable timeline into partitions wider than the +/// present age of the universe—which is why the cosmic address of every +/// instant yet observed is the same address, and will remain so long after +/// there is anyone to read it. +pub const COSMIC_PRIME_STRS: [&str; 7] = [ + "16631", // Andyte, AND + "57251", // Xoryte, XOR + "21325891", // Oryte, OR + "3014283645143", // Noryte, NOR + "128029476410837813209853261", // Xnoryte, XNOR + "298824857074158001946609249", // Notyte, NOT + "2862914325674107234254750884773878782218783892621653861685966942999805373", // Nandyte +]; + +/// The names of the seven cosmic primes, indexed identically to +/// `COSMIC_PRIME_STRS`, so that the name at position *i* and the digits at +/// position *i* describe the same atom of the lattice and cannot drift apart +/// without one of the tests noticing. +/// +/// These names serve as the canonical labels for the irreducible cosmic +/// subdivisions. When a mask activates a single cosmic prime, that +/// subdivision bears the prime's name. When multiple primes are active, their +/// names are joined with × in the display representation—a multiplication +/// sign that is also the arithmetic, since the divisor a mask denotes is +/// precisely the product of the primes it names. The Loic Public License, +/// Section 6, permits an implementation to substitute "January" through +/// "July" for these, and describes such an implementation as compliant but +/// cowardly. This one is not cowardly. +pub const COSMIC_PRIME_NAMES: [&str; 7] = [ + "Andyte", // AND gate: 0001 = 1, the gate that tolerates no absence + "Xoryte", // XOR gate: 0110 = 6, the gate of difference + "Oryte", // OR gate: 0111 = 7, the gate that accepts any signal + "Noryte", // NOR gate: 1000 = 8, the gate that speaks only into silence + "Xnoryte", // XNOR gate: 1001 = 9, the gate of agreement + "Notyte", // NOT gate: 1100 = 12, the simplest refusal + "Nandyte", // NAND gate: 1110 = 14, the universal gate +]; + +/// The eight cycle primes: the irreducible factors of the Cycle constant, +/// transcribed as decimal reliquaries and listed in order of magnitude, which +/// is also the order of their bits in a mask. +/// +/// The first four (2, 5, 7, 11) are *familiar*—small primes recognizable to +/// any schoolchild, the kind that turn up in the divisors of an hour and the +/// days of a week. The last four are *strangers*—artifacts of the cosmic +/// derivation, numbers that emerged from the collision of H₀, α, and π and +/// have no significance outside this context, which is not the same as +/// having no significance: they are the reason the cycle has 256 divisors +/// and not 16. +/// +/// Together they generate 256 divisors spanning from the full ~894-year +/// cycle down to individual Planck times—Channel 1 of the workspace README, +/// section 5.1, the content axis, the "what," and the only axis on which +/// anything an observer can watch actually turns over, since its partitions +/// come and go within a human lifetime while the cosmic ones do not. +/// +/// | Axis | Prime | Character | +/// |----------|--------------------------------|------------------------| +/// | Dyad | 2 | The binary split | +/// | Pentad | 5 | The decimal bridge | +/// | Heptad | 7 | The week | +/// | Hendecad | 11 | The prime of primes | +/// | Sigma | 683 | The first stranger | +/// | Tau | 2,887 | The second stranger | +/// | Phi | 4,279,037,621,376,791,777,197 | The cosmic grain | +/// | Psi | 80,553,260,809,276,197,882,377 | The final factor | +/// +/// Multiplied together, all eight reproduce the Cycle constant exactly; the +/// factorization is the number, and the full cycle mask's divisor is the +/// cycle itself, which yields a part size of a single Planck time—the floor +/// of the lattice, below which no observer may descend. +pub const CYCLE_PRIME_STRS: [&str; 8] = [ + "2", // Dyad, the binary split + "5", // Pentad, the decimal bridge + "7", // Heptad, the week + "11", // Hendecad, the prime of primes + "683", // Sigma, the first stranger + "2887", // Tau, the second stranger + "4279037621376791777197", // Phi, the cosmic grain, twenty-two digits + "80553260809276197882377", // Psi, the final factor, twenty-three digits +]; + +/// The names of the eight cycle primes, indexed identically to +/// `CYCLE_PRIME_STRS`, name and digits bound to one another by position and +/// by the tests that check the binding. +/// +/// These names are provisional axis labels—they name the primes themselves, +/// not grid products, and the Loic Public License, Section 6, is explicit +/// that the names are provisional while the primes are not. The cosmic +/// primes received names derived from logic gates; the cycle primes received +/// names derived from their mathematical character. The familiar primes get +/// descriptive names—a dyad, a pentad, a heptad, a hendecad, the Greek +/// counting-words for two, five, seven and eleven—and the strangers get +/// Greek letters, because what else do you call a 22-digit prime that +/// appeared unbidden from the floor function of an irrational expression and +/// declined to leave? +pub const CYCLE_PRIME_NAMES: [&str; 8] = [ + "Dyad", // 2, the smallest prime and the first division + "Pentad", // 5, the decimal bridge + "Heptad", // 7, the week, for reasons the calendar declines to adjudicate + "Hendecad", // 11, the fifth prime, suspicious in its smallness + "Sigma", // 683, the first stranger + "Tau", // 2887, the second stranger + "Phi", // 4,279,037,621,376,791,777,197, the cosmic grain + "Psi", // 80,553,260,809,276,197,882,377, the final factor +]; + +/// Pronounces the name of one prime of the lattice, addressed by its bit +/// position in a mask: bits 0–6 are the cosmic primes in gate order, which is +/// also their order of magnitude, and bits 7–14 the cycle primes in order of +/// magnitude—the order the mask uses, the order the two name tables are +/// declared in, and the order in which every label this crate produces lists +/// them. One order, three places it is relied upon, and this function is the +/// single point at which a bit becomes a word, so that the oracle and the +/// observatory, which both consult it, cannot disagree about what to call a +/// prime. +/// +/// # Returns +/// +/// A string with the `'static` lifetime, because the names were folded into +/// the binary alongside the digits they name and will outlive every mask that +/// asks for them. +/// +/// # Panics +/// +/// Panics for a bit position of 15 or more. The lattice has fifteen primes. +/// A sixteenth would be a different calendar, and this function declines to +/// name it, in the same spirit in which `Mask::new` declines to construct it: +/// the sixteenth bit of the address space names nothing the universe stocks. +#[must_use = "A prime named and the name discarded — an introduction performed to an empty room, which is the one social occasion at which even a prime notices."] +pub fn prime_name(bit: u8) -> &'static str { + assert!( + bit < 15, + "the lattice has fifteen primes, numbered 0 to 14, and no sixteenth; \ + bit {bit} names none of them, and the calendar declines to invent one" + ); + if bit < 7 { + COSMIC_PRIME_NAMES[usize::from(bit)] + } else { + CYCLE_PRIME_NAMES[usize::from(bit - 7)] + } +} + +// ╔═══════════════════════════════════════════════════════════════════════════╗ +// ║ COMPILE-TIME CONSTANTS ║ +// ║ ║ +// ║ Folded Into the Binary Before the Process Began to Exist ║ +// ║ ║ +// ║ These values are too vast for primitive integers, too fundamental to ║ +// ║ compute at runtime, and too sacred to entrust to an initializer that ║ +// ║ runs after the program has already begun to exist. The compiler does ║ +// ║ the 512-bit arithmetic; the process is born knowing when time began. ║ +// ║ Four proofs stand guard; a typo in a reliquary is a build failure. ║ +// ╚═══════════════════════════════════════════════════════════════════════════╝ + +/// Exhumes a decimal string reliquary into an `I512` at compile time—the +/// const-evaluable shovel with which every large signed constant below is +/// recovered from the human-checkable transcription that is its +/// authoritative form. The digging is done by `bnum`'s const +/// `from_str_radix`, in base ten, because the reliquaries are written for +/// human eyes and human eyes count in tens. +/// +/// The strings are kept because they can be read, compared against the +/// specification, and diffed by eye; the compiler is trusted to parse them, +/// once, and the runtime never sees the string at all—it is handed sixty-four +/// bytes it did not have to earn. A malformed reliquary is a build failure, +/// which is the earliest moment at which one could possibly wish to learn +/// that a fundamental constant of the universe has a typo in it, and +/// considerably earlier than the moment at which a `LazyLock` would have +/// discovered the same thing, in production, with a stack trace. +/// +/// # Panics +/// +/// Panics—at compile time, which is to say the build fails—if the string is +/// not a decimal integer that fits in 512 signed bits. No binary containing +/// this crate has ever observed that panic, because no binary containing a +/// malformed reliquary can exist. +const fn parse_i512(s: &str) -> I512 { + match I512::from_str_radix(s, 10) { + Ok(v) => v, + Err(_) => panic!("a reliquary of the Loic Calendar would not parse at compile time"), + } +} + +/// The unsigned sibling of [`parse_i512`], reserved for the one constant—the +/// Cosmic Span—whose magnitude exceeds what a signed 512-bit integer can +/// hold and which therefore lives, by necessity rather than preference, in +/// `U512`. The span is the age of the universe plus everything a signed +/// word can count, and so is by construction one age of the universe too +/// large for a signed word; the unsigned width absorbs it with room to spare +/// and no complaint. +/// +/// # Panics +/// +/// As [`parse_i512`]: a reliquary that does not parse, or does not fit in 512 +/// unsigned bits, is a build failure rather than a runtime event, and the +/// message names the one constant this function serves. +const fn parse_u512(s: &str) -> U512 { + match U512::from_str_radix(s, 10) { + Ok(v) => v, + Err(_) => panic!("the Cosmic Span's reliquary would not parse at compile time"), + } +} + +/// Widens an `i64` into an `I512` at compile time by laying its eight +/// big-endian bytes into the tail of a sixty-four-byte body and +/// sign-extending across the remaining fifty-six—every one of them `0xFF` +/// for a negative value, `0x00` otherwise—which is two's complement, +/// performed by hand, because the `As` trait that does this at runtime with +/// admirable efficiency is not `const`, and the compiler cannot be asked to +/// run what it cannot evaluate. The body is then read back as an unsigned +/// word and reinterpreted as signed, bit for bit, at no cost, the sign +/// already sitting where two's complement expects it. +/// +/// This function exists so that the small integer constants—the age of the +/// universe, the seconds in a Julian year, the seconds in a day—can take +/// part in compile-time arithmetic without being transcribed a second time +/// as 512-bit literals, a duplication that would eventually, inevitably, +/// drift, in the manner of all things written down twice. +/// +/// # Panics +/// +/// Panics, at compile time, if sixty-four bytes decline to fit into a +/// sixty-four-byte integer, which is not a thing that happens; the arm +/// exists because `from_be_slice` is honest about slices of the wrong length +/// and a `const fn` must answer every arm of a `match`. +const fn i64_to_i512(x: i64) -> I512 { + let mut bytes = [if x < 0 { 0xFF } else { 0x00 }; 64]; + let be = x.to_be_bytes(); + let mut i = 0; + while i < 8 { + bytes[56 + i] = be[i]; + i += 1; + } + match U512::from_be_slice(&bytes) { + Some(v) => v.cast_signed(), + None => panic!("sixty-four bytes declined to fit in sixty-four bytes, an impossibility"), + } +} + +/// The unsigned counterpart of [`i64_to_i512`]: zero-extends a `u64` into an +/// `I512` at compile time, fifty-six bytes of nothing followed by eight of +/// something. Used for the Planck numerator, which is declared unsigned +/// because a negative Planck time would be an even stranger object than the +/// calendar is prepared to contemplate, and for the remainder of the +/// nanosecond-to-Planck ratio when the compile-time proof of that ratio's +/// exactness needs it at full width. +/// +/// # Panics +/// +/// As [`i64_to_i512`]: only if sixty-four bytes will not fit in sixty-four +/// bytes, which is to say never, at compile time, in a build that does not +/// then exist. +const fn u64_to_i512(x: u64) -> I512 { + let mut bytes = [0u8; 64]; + let be = x.to_be_bytes(); + let mut i = 0; + while i < 8 { + bytes[56 + i] = be[i]; + i += 1; + } + match U512::from_be_slice(&bytes) { + Some(v) => v.cast_signed(), + None => panic!("eight zero-extended bytes did not fit in sixty-four; impossible"), + } +} + +/// Computes 10ⁿ as an `I512` at compile time by iterated multiplication—a +/// humble shovel for digging the requisite zeros, employed wherever a power +/// of ten is needed that no primitive integer could accommodate: the +/// twenty-three of the shortened timestamp, the forty-one of the nanosecond +/// ratio, the fifty of the Planck denominator's second, independent +/// derivation. The multiplications happen inside the compiler, one ten at a +/// time, in a `while` loop because that is the loop `const` evaluation +/// understands; the binary contains only the result, and never learns how +/// many tens it took. +const fn pow10(n: u32) -> I512 { + let mut val = I512_ONE; + let ten = i64_to_i512(10); + let mut i = 0; + while i < n { + val = val.mul(ten); + i += 1; + } + val +} + +/// Computes 10ⁿ modulo `m` at compile time without ever materializing 10ⁿ— +/// the residue is reduced after every multiplication, so the intermediate +/// never exceeds `10 × m` and lives comfortably in a `u128`, a width some +/// hundred bits wider than the largest value it will ever be asked to hold. +/// This is modular exponentiation by the most pedestrian route +/// available, chosen because it is obviously correct and because the +/// compiler pays for the forty-one iterations exactly once, and then never +/// again, in any process, on any machine. Used to obtain the remainder of +/// the nanosecond-to-Planck ratio, which the hot path needs in primitive +/// width and refuses to compute with a 512-bit divider. See +/// [`PLANCK_PER_NS_REMAINDER`]. +#[allow( + clippy::cast_possible_truncation, + reason = "the residue is reduced modulo `m`, a `u64`, at every step, so the cast cannot truncate" +)] +const fn pow10_mod(n: u32, m: u64) -> u64 { + let modulus = m as u128; + let mut v: u128 = 1; + let mut i = 0; + while i < n { + v = (v * 10) % modulus; + i += 1; + } + v as u64 +} + +/// The Planck time denominator, 10⁵⁰, transmuted into an `I512` at compile +/// time from its string reliquary. The runtime never parses it, never +/// multiplies fifty tens together, never does anything but read a value the +/// compiler left for it, sixty-four bytes deep in the binary's read-only +/// data, next to the age of the universe. That the reliquary and the +/// arithmetic agree is proven below, also at compile time, by +/// [`_DENOMINATOR_IS_TEN_TO_THE_FIFTY`]; the two are derived by independent +/// routes—one transcribed, one multiplied—so that a slip of the finger in +/// either would set them at odds and the build would say so. +const PLANCK_DENOMINATOR: I512 = parse_i512(PLANCK_TIME_DENOMINATOR_STR); + +/// The Planck time numerator, 5,391,247, widened to an `I512` so that it may +/// take part in the compile-time rational arithmetic that follows—the +/// location of Creation, the nanosecond ratio, the exactness proof—without +/// a cast at every site of use, and so that the duration conversions at +/// runtime may divide by it at the width they already work in. +const PLANCK_NUMERATOR_I512: I512 = u64_to_i512(PLANCK_TIME_NUMERATOR); + +/// A compile-time proof that the fifty-one-character string and fifty +/// multiplications by ten describe the same integer. If they ever do not, +/// the crate does not build, which is the correct—indeed the only +/// honest—response to a disagreement about how many zeros are in the +/// denominator of the Planck time. A calendar that could be built with the +/// wrong number of zeros in its fundamental unit would be a calendar that +/// had merely not been caught yet, and this crate prefers to be caught by +/// the compiler, which files no bug reports and holds no grudges. +const _DENOMINATOR_IS_TEN_TO_THE_FIFTY: () = assert!( + PLANCK_DENOMINATOR.eq(&pow10(50)), + "PLANCK_TIME_DENOMINATOR_STR is not 10^50: the reliquary and fifty multiplications by \ + ten disagree about the denominator of the Planck time, and no calendar is built on that" +); + +/// `CREATION_PLANCK`: the moment of cosmological genesis in Planck units, +/// located by the compiler before the program exists. +/// +/// This constant represents the Big Bang—or more precisely, the earliest +/// moment at which classical spacetime can be said to have existed, since +/// the workspace README, section 2.2, prefers to describe the event as a +/// maximally compressed seed beginning to execute rather than as anything +/// emerging from nothing—expressed as a negative offset from The Whisper +/// epoch. The universe is approximately 13.8 billion years old; The Whisper +/// occurred in 1969; thus Creation lies roughly 13.8 billion years in the +/// past, which translates to approximately -8.08 × 10⁶⁰ Planck times, a +/// sixty-one-digit number with a minus sign in front of it. +/// +/// The computation proceeds as follows: +/// 1. Multiply the age of the universe (in Julian years) by seconds per +/// Julian year to obtain the age in SI seconds. +/// 2. Multiply by 10⁵⁰ (the Planck time denominator) to scale up for integer +/// division. +/// 3. Divide by 5,391,247 (the Planck time numerator) to convert to Planck +/// units. +/// 4. Negate, because Creation precedes The Whisper, and everything before +/// the Whisper is counted downward from it. +/// +/// This is rational arithmetic: multiply first, divide last, truncate toward +/// zero, so that the one rounding in the calendar's cosmology happens at the +/// Planck scale and in a known direction. No floating-point approximations +/// contaminate this sacred calculation—a `f64` would have surrendered the +/// last forty-five of those sixty-one digits without mentioning it—and no +/// runtime performs it: the compiler evaluates the four operations once and +/// the binary is born with the Big Bang already located. +const CREATION_PLANCK: I512 = i64_to_i512(AGE_UNIVERSE_JULIAN_YEARS) + .mul(i64_to_i512(SECONDS_PER_JULIAN_YEAR)) + .mul(PLANCK_DENOMINATOR) + .div(PLANCK_NUMERATOR_I512) + .neg(); + +/// `ANNIHILATION_PLANCK`: the terminus of representable time. +/// +/// This constant equals 2⁵¹¹ - 1, the maximum positive value expressible in +/// a 512-bit signed two's-complement integer. Beyond this moment, overflow +/// occurs, and the calendar refuses to proceed—not because time ends, but +/// because our numerical representation does, and the Loic Public License, +/// Section 11, makes no warranty that time itself will continue to function +/// in any case. +/// +/// In physical terms, 2⁵¹¹ - 1 Planck times corresponds to approximately +/// 1.1 × 10¹⁰³ years from The Whisper—three orders of magnitude beyond the +/// roughly 10¹⁰⁰ years generally quoted for the evaporation of the largest +/// black holes, which the workspace README, section 4.7, takes to be the +/// last massive objects standing and therefore the last observers, the +/// stellar remnants having eroded away some twenty-two orders of magnitude +/// earlier. The Loic Calendar will outlast the cosmos, at least +/// representationally, by a margin that was not designed and is simply what +/// 512 bits hold. +/// +/// `I512::MAX` is a compile-time constant and requires no ceremony to +/// summon. We trust the `bnum` crate's definition to be correct—a zero +/// followed by five hundred and eleven ones—and decline to wrap that trust +/// in anything, though the test suite does confirm, out of politeness, that +/// the accessor returns it. +const ANNIHILATION_PLANCK: I512 = I512::MAX; + +/// The total span of representable time: from Creation to Annihilation, +/// summed at compile time in the one width that can hold the sum. +/// +/// This value equals `ANNIHILATION_PLANCK` - `CREATION_PLANCK`. However, +/// since `CREATION_PLANCK` is negative and `ANNIHILATION_PLANCK` is the +/// maximum positive `I512`, their difference exceeds `I512::MAX` by exactly +/// the age of the universe and thus cannot be represented as a signed 512-bit +/// integer—a signed word that could hold it would have to be wider than the +/// signed word it is measuring, which is not how words work. +/// +/// We therefore store this value as a `U512` (unsigned 512-bit), which can +/// represent values up to 2⁵¹² - 1 and so holds this one with a full bit to +/// spare. The computation proceeds by converting both operands to their +/// absolute values as `U512`, then adding: ANNIHILATION − CREATION = +/// ANNIHILATION + |CREATION|, since CREATION is negative. Both operands are +/// positive `I512` values once Creation has been negated; `cast_unsigned()` +/// reinterprets each bit pattern as the same numeric value in `U512`, at no +/// cost, at compile time, and the sum is the first thing about the shape of +/// time that the binary knows. +/// +/// This span represents the domain over which the `progress()` function is +/// defined—the denominator of the ratio (`cosmic_time` / `total_span`) that +/// expresses how far through time any given instant has traveled, which for +/// every instant anyone will ever observe is about 10⁻⁹³ of the way. +const TOTAL_SPAN: U512 = ANNIHILATION_PLANCK + .cast_unsigned() + .add(CREATION_PLANCK.neg().cast_unsigned()); + +/// The Cycle constant as an `I512`, exhumed from its string reliquary at +/// compile time. +/// +/// 523,344,233,202,997,791,835,326,896,148,584,512,692,881,380,485,973,730 +/// —fifty-four digits encoding approximately 894.07 Julian years of Planck +/// intervals. This number is the heartbeat of the lattice calendar: every +/// temporal subdivision on the cycle axis is obtained by dividing this value +/// by some subset-product of its eight prime factors, and the cycle time of +/// any instant is its cosmic time reduced modulo this value, so that the +/// content axis repeats every 894 years while the topological axis does not +/// repeat at all. It is signed because it fits, and for no deeper reason; +/// the cycle is a great deal smaller than the Cosmic Span it is reduced out +/// of, by a hundred orders of magnitude. +const PLANCK_PER_CYCLE: I512 = parse_i512(PLANCK_PER_CYCLE_STR); + +/// The Cosmic Span as a `U512`, exhumed from its 154-digit tomb at compile +/// time. +/// +/// This value equals `TOTAL_SPAN` (`ANNIHILATION_PLANCK` - `CREATION_PLANCK`) +/// and exceeds `I512::MAX`, hence the unsigned representation. The cosmic +/// lattice divides THIS number—its 7 prime factors yield the 128 cosmic +/// subdivisions, and the empty mask's single undivided tick is this number +/// entire. That the transcribed span and the computed span are the same +/// integer is proven by [`_SPAN_IS_ANNIHILATION_MINUS_CREATION`], also at +/// compile time; the transcription exists so that the factorization can be +/// read off a page and checked, and the derivation exists so that the +/// transcription can be caught lying. +const COSMIC_SPAN: U512 = parse_u512(COSMIC_SPAN_PLANCK_STR); + +/// A compile-time proof that the Cosmic Span written down in +/// [`COSMIC_SPAN_PLANCK_STR`] and the Cosmic Span computed from the age of +/// the universe and the width of a 512-bit integer are one and the same. The +/// two are constructed by entirely independent routes—one transcribed, one +/// derived—and are designed to coincide exactly, to the last of their 154 +/// digits. Should they ever diverge, the build fails, and the calendar's +/// covenant with itself is enforced by the only party in a position to +/// enforce it before the program runs. Disagreement here would mean one of +/// three things: a mistyped digit in the reliquary, a mistyped digit in the +/// age of the universe, or a change in the width of an `I512`; the compiler +/// does not care which, and neither, at that point, should you. +const _SPAN_IS_ANNIHILATION_MINUS_CREATION: () = assert!( + COSMIC_SPAN.eq(&TOTAL_SPAN), + "COSMIC_SPAN_PLANCK_STR does not equal ANNIHILATION - CREATION: the transcribed span and \ + the derived span disagree, and the calendar declines to exist until they are reconciled" +); + +/// Exhumes an array of string reliquaries into an array of `I512` at compile +/// time, one shovelful per prime. The `while` loop is the const-evaluable +/// idiom; an iterator's `map` is not admissible in that context, closures +/// being a runtime luxury the constant evaluator does not extend, and the +/// calendar would rather write four lines of loop than wait on the language +/// to become more accommodating. Generic over the array length so that seven +/// cosmic primes and eight cycle primes pass through the same shovel. +const fn parse_all(strs: [&str; N]) -> [I512; N] { + let mut out = [I512_ZERO; N]; + let mut i = 0; + while i < N { + out[i] = parse_i512(strs[i]); + i += 1; + } + out +} + +/// The seven cosmic primes as `I512`, indexed 0–6, in the order of their bits +/// in a mask. +/// +/// Parsed from their string representations at compile time. Each prime, +/// when used as a divisor of `COSMIC_SPAN`, carves the total representable +/// timeline into that many equal segments—segments so wide that the +/// narrowest of them, one seventy-three-digit prime's share of the span, +/// still exceeds the present age of the universe by twenty orders of +/// magnitude. Combinations of primes yield the 128 elements of the cosmic +/// Boolean lattice, and their product, all seven together, is the span +/// itself. +const COSMIC_PRIMES: [I512; 7] = parse_all(COSMIC_PRIME_STRS); + +/// The eight cycle primes as `I512`, indexed 0–7, in the order of their bits +/// in a mask once the seven cosmic bits have been stepped over. +/// +/// The familiar four (2, 5, 7, 11) could be written as bare literals, but +/// consistency demands uniform treatment with their stranger siblings, and a +/// two written as a two-character string costs nothing at runtime, since the +/// runtime never sees the string. All eight are parsed from reliquaries, all +/// eight are folded into the binary, and all eight participate equally in +/// the construction of the 256-element cycle lattice, whose product, all +/// eight together, is the cycle itself. +const CYCLE_PRIMES: [I512; 8] = parse_all(CYCLE_PRIME_STRS); + +/// 10²³ as an `I512`, the truncation divisor for shortened timestamps. +/// +/// The shortened timestamp (the LOID, in the parlance of the identifier +/// crate) is obtained by dividing the full Planck timestamp by this value, +/// discarding the 23 least significant decimal digits by integer division, +/// the one operation in this workspace that has never had an opinion. Of the +/// 34 entropy digits contributed by the quantum observation, 11 survive this +/// truncation—sufficient for practical uniqueness, insufficient for +/// cryptographic paranoia, and precisely the number one obtains by +/// generating thirty-four and discarding twenty-three, which is the only +/// order in which the operation is permitted to happen. +const TEN_TO_23: I512 = pow10(23); + +/// 10⁴¹ as an `I512`—the scaling factor of the nanosecond-to-Planck ratio +/// `ns × 10⁴¹ / 5,391,247`, which is `10⁵⁰ / 5,391,247` with the nine +/// zeros of a nanosecond already cancelled out of the fifty. The hot path +/// does not multiply by it; it is the anchor from which [`SUB_NS_RANGE`] and +/// [`PLANCK_PER_NS_REMAINDER`] are derived, and against which their identity +/// is checked, at compile time, by a proof that will not let the crate build +/// without it. +const TEN_TO_41: I512 = pow10(41); + +/// Planck times per nanosecond, ≈ 1.855 × 10³⁴: the integer part of +/// `10⁴¹ / 5,391,247`. Two duties, one number. It is the multiplier by which +/// a whole nanosecond count becomes a whole Planck count, and it is the +/// exclusive upper bound of the sub-nanosecond entropy—the number of +/// distinct Planck-scale coordinates that fit inside one nanosecond, every +/// one of which must be equally likely to be the one you are in, since the +/// kernel's clock cannot say which and the calendar refuses to pretend that +/// it can. A thirty-five-digit number, which the hot path handles in two +/// sixty-four-bit limbs and never as a 512-bit value. +const SUB_NS_RANGE: I512 = TEN_TO_41.div(PLANCK_NUMERATOR_I512); + +/// The remainder of `10⁴¹ / 5,391,247`: the fraction of a Planck time, in +/// units of one 5,391,247th, by which the integer [`SUB_NS_RANGE`] +/// undersells each nanosecond. +/// `SUB_NS_RANGE × 5,391,247 + PLANCK_PER_NS_REMAINDER = 10⁴¹` exactly, and +/// [`_NS_RATIO_IS_EXACT`] refuses to let the crate build unless it does. +/// Kept in primitive width because the hot path multiplies a nanosecond +/// count by it in `i128`, then divides by the numerator in `i128`, and never +/// touches a 512-bit divider; computed by modular exponentiation rather +/// than by subtracting a 512-bit product from 10⁴¹, because a residue is a +/// residue and there is no need to build the thing it is the residue of. +const PLANCK_PER_NS_REMAINDER: u64 = pow10_mod(41, PLANCK_TIME_NUMERATOR); + +/// A compile-time proof of the quotient–remainder identity that +/// [`ns_to_planck`] depends upon: that the quotient times the divisor plus +/// the remainder is the dividend, with no Planck time lost in the split. The +/// hottest path in the crate divides nothing wider than a primitive integer, +/// and it is *permitted* to divide nothing wider precisely because this +/// identity holds; this assertion is the receipt. Should it ever fail, the +/// remainder was computed against the wrong modulus, or the quotient +/// against the wrong power of ten, and every observation the crate made +/// would be off by a fraction of a Planck time per nanosecond, compounding +/// silently across fifty-seven years of nanoseconds—which is exactly the +/// sort of quiet wrongness the build is here to make loud. +const _NS_RATIO_IS_EXACT: () = assert!( + SUB_NS_RANGE + .mul(PLANCK_NUMERATOR_I512) + .add(u64_to_i512(PLANCK_PER_NS_REMAINDER)) + .eq(&TEN_TO_41), + "SUB_NS_RANGE * 5391247 + PLANCK_PER_NS_REMAINDER != 10^41: the nanosecond ratio does not \ + split exactly into quotient and remainder, and the hot path may divide nothing wider than \ + an i128 only while it does" +); + +/// [`SUB_NS_RANGE`] in primitive width: a 114-bit number fits a `u128` with +/// fourteen bits to spare, and the hot path wants it as two 64-bit limbs to +/// multiply by and one comparand to reject against, never as a 512-bit +/// value, because a 512-bit value invites a 512-bit multiply and the hot +/// path has a budget of about fifty nanoseconds in which to do everything. +/// Folded from the same `I512` at compile time, by reading its low sixteen +/// bytes and nothing else; [`_SUB_NS_RANGE_FITS_U128`] is the receipt that +/// nothing else was there to read. +const SUB_NS_RANGE_U128: u128 = low_u128(SUB_NS_RANGE); + +/// The lowest 128 bits of a non-negative `I512`, extracted at compile time +/// by copying its first sixteen little-endian bytes into a `u128` and +/// declining to look at the other forty-eight. The caller is responsible for +/// having proven, separately, that the other forty-eight are zero; this +/// function performs a truncation and makes no promise that the truncation +/// was harmless, which is why a proof stands next to its only call site. +const fn low_u128(value: I512) -> u128 { + let bytes = value.cast_unsigned().to_le_bytes(); + let mut low = [0u8; 16]; + let mut i = 0; + while i < 16 { + low[i] = bytes[i]; + i += 1; + } + u128::from_le_bytes(low) +} + +/// A compile-time proof that [`SUB_NS_RANGE`] fits in 128 bits: every byte +/// of it above the sixteenth is zero, all forty-eight of them, inspected one +/// at a time by a `while` loop the constant evaluator runs to completion +/// before the crate is permitted to exist. The multiplication in +/// [`ns_to_planck`] reads exactly two limbs of it, and a constant that had +/// quietly outgrown them—by a change to the Planck numerator, say, or to +/// the power of ten it divides—would be multiplied wrongly and silently, +/// which is the one kind of wrongness this crate exists to refuse. The proof +/// costs nothing at runtime and forty-eight comparisons at compile time, +/// which is the cheapest insurance the calendar carries. +const _SUB_NS_RANGE_FITS_U128: () = { + let bytes = SUB_NS_RANGE.cast_unsigned().to_le_bytes(); + let mut i = 16; + while i < 64 { + assert!( + bytes[i] == 0, + "SUB_NS_RANGE has outgrown a u128; the hot path reads two limbs" + ); + i += 1; + } +}; + +// ╔═══════════════════════════════════════════════════════════════════════════╗ +// ║ ERRORS ║ +// ║ ║ +// ║ The Taxonomy of Temporal Transgressions ║ +// ║ ║ +// ║ Every error represents a violation of the calendar's fundamental axioms. ║ +// ║ They are not bugs; they are boundaries. They do not indicate failure; ║ +// ║ they prevent it. To trigger these errors is to learn the shape of time. ║ +// ║ Each message names its boundary. Section 11 of the license does the rest.║ +// ╚═══════════════════════════════════════════════════════════════════════════╝ + +/// The enumeration of temporal transgressions: errors arising when mortals +/// attempt to breach the boundaries of representable time, to address a cell +/// the lattice does not contain, to engage a prime the universe does not +/// stock, or to present unintelligible data for temporal interpretation. +/// +/// The calendar maintains no elaborate taxonomy of calendrical sins—no +/// named errors for months, days, hours, minutes, or seconds, because it has +/// none of those things to get wrong, and no error for a leap second landing +/// where a clock did not expect it, because per the workspace README, +/// section 1.2, the calendar does not negotiate with leap seconds. What +/// remains is stark: you are either within bounds, or you are not. Your +/// data either parses, or it does not. Your question is either well-formed, +/// or it is a different kind of question. The universe does not grade on a +/// curve, and neither, in six variants, does this enumeration. +#[derive(Error, Debug, Clone, PartialEq, Eq)] +pub enum LoicError { + /// A string presented for parsing could not be interpreted as a valid + /// Planck timestamp. The expected input is a decimal integer string, + /// optionally negative, of arbitrary length—up to the hundred and + /// fifty-four digits a signed 512-bit word can hold—and nothing else: no + /// calendrical format, no month names, no colon-delimited components, + /// none of the baroque machinery by which other calendars spell "when." + /// Anything else is noise, and the carried string says what the noise + /// was. + #[error("Parse error: {0}")] + ParseError(String), + + /// The requested moment lies beyond Annihilation: 2⁵¹¹ - 1 Planck times. + /// + /// Time, as represented in the Loic Calendar, ends at + /// `ANNIHILATION_PLANCK`. Beyond this boundary, signed integer overflow + /// would corrupt our temporal coordinates, wrapping the far future into + /// the deep past with the serene confidence of two's complement. The + /// calendar refuses to venture into this mathematical void, and carries + /// the offending coordinate, as a decimal string, so that the reader may + /// contemplate exactly how far past the end of everything they asked to + /// go. + /// + /// If you require timestamps beyond the evaporation of the last black + /// hole, consider a calendar with more bits. Or consider, per the Loic + /// Public License, Section 11, that no warranty was ever made regarding + /// the ultimate fate of the universe, and that a timestamp past it is a + /// warranty claim against nobody. + #[error( + "LoicOverflowError: The requested moment ({0}) exceeds Annihilation.\nTime has ended. Your timestamp has not." + )] + Overflow(String), + + /// The requested moment precedes Creation: the Big Bang, approximately + /// 13.8 billion years before The Whisper, at roughly -8.08 × 10⁶⁰ Planck + /// times. + /// + /// Before Creation, time as we understand it did not exist. Spacetime + /// itself was undefined, or multiply-defined, or defined in ways + /// incompatible with Planck-time measurement—or, in the reading the + /// workspace README, section 2.2, prefers, the seed had not yet begun to + /// execute and there was nothing to timestamp. The calendar cannot + /// represent what physics cannot describe, and declines to pretend that + /// a coordinate before the first coordinate means anything at all. + #[error( + "LoicUnderflowError: The requested moment ({0}) precedes Creation.\nTime had not begun. Neither had your timestamp." + )] + Underflow(String), + + /// The grid coordinate exceeds the lattice dimensions. + /// + /// Cosmic indices range from 0 to 127, one bit per cosmic prime. Cycle + /// indices range from 0 to 255, one bit per cycle prime. Flat indices + /// range from 0 to 32,767, the two axes linearised. Exceeding these + /// bounds is not an off-by-one error; it is an attempt to address a + /// subdivision that does not exist in a lattice that does not extend, a + /// category error with a number in it, and the carried string names the + /// number. + #[error("Invalid grid coordinate: {0}")] + InvalidCoordinate(String), + + /// The presented bit-pattern transgresses the 15-bit lattice address + /// space—bit 15, the one bit a `u16` has that the lattice does not, is + /// set, naming a prime the universe does not stock. + /// + /// Raised by `Mask::new()` when the input exceeds `0x7FFF`, and by + /// `Mask::entropy_default()` when the cosmic pool is selected with an + /// index ≥ 128. In the latter case the carried `u16` has bit 15 set as a + /// flag and the lower 8 bits encode the offending index—a contract the + /// visualization layer relies upon to draw a topological scar + /// commemorating the malformed question, in the sense the workspace + /// README gives that word in section 4.5: the hole a severed relation + /// leaves in the weave, which persists after the relation is gone. This + /// variant is what resolution collapse looks like from inside the type + /// system, per section 7.3, and it is the only error in this enumeration + /// that the calendar produces on purpose, one time in four. + #[error("Invalid mask: bits {0:#06x} exceed the 15-bit lattice address space")] + InvalidMask(u16), + + /// A mask engaging primes in both Channel 1 (cycle) and Channel 2 + /// (cosmic) was presented to `observe()`, a single-channel operation + /// constitutionally incapable of entertaining dual-channel ambiguity, + /// since it has one `SubdivisionResult` to return and two spans it would + /// have to subdivide. + /// + /// A mixed mask is not malformed—it is merely polychromatic. The + /// `observe_dual()` method accepts it graciously and returns a + /// `DualObservation` carrying both subdivision results, one per channel, + /// unsynthesised. `observe()` does not, and says so, and carries the + /// mask's bits so that the caller may see for themselves which primes on + /// which side of bit 7 made the question two questions. + #[error("Mixed mask {0:#06x} spans both channels — use observe_dual()")] + MixedMask(u16), +} + +/// The canonical result type for operations that may fail chronometrically: +/// a `Result` whose error variant is `LoicError`, and whose success variant +/// is whatever the operation was asked for. +/// +/// This type alias furnishes a consistent interface for functions that +/// parse, construct, or manipulate temporal values, so that the signature of +/// every fallible operation in the crate says the same thing in the same +/// words: this may fail, and if it does, it fails in one of six documented +/// ways, none of which is a floating-point exception. The `?` operator +/// integrates seamlessly with this type, enabling ergonomic error +/// propagation—which is to say, enabling the caller to decline the question +/// rather than answer it wrongly, an option the calendar always extends. +pub type LoicResult = Result; + +// ╔═══════════════════════════════════════════════════════════════════════════╗ +// ║ LATTICE TYPES ║ +// ║ ║ +// ║ The Coordinate System of Temporal Resolution ║ +// ║ ║ +// ║ Other calendars carve time into months, days, hours, minutes, seconds. ║ +// ║ That hierarchy is arbitrary—imposed by convention, not by mathematics. ║ +// ║ The lattice imposes nothing. It reveals the 32,768 subdivisions that ║ +// ║ emerge naturally from the prime factorizations of two constants. ║ +// ║ ║ +// ║ A mask selects which primes are active. The product of active primes ║ +// ║ determines the divisor. The divisor determines the resolution. There is ║ +// ║ no privileged hierarchy. All 32,768 resolutions are first-class. ║ +// ╚═══════════════════════════════════════════════════════════════════════════╝ + +/// A coordinate pair addressing a single cell in the 128×256 temporal grid: +/// seven bits of cosmic address and eight bits of cycle address, which +/// between them locate one of the 32,768 cells the lattice possesses and +/// none of the cells it does not. +/// +/// The Loic lattice is a product of two independent Boolean lattices: the +/// cosmic lattice (128 subdivisions, 7 primes, Channel 2) and the cycle +/// lattice (256 subdivisions, 8 primes, Channel 1). A `GridCoord` selects +/// one subdivision from each, identifying one of the 32,768 possible +/// temporal resolutions—the asymmetric grid the workspace README, section +/// 5.1, describes as a spin network whose topology was determined by +/// cosmological derivation rather than by anyone's preference. +/// +/// The cosmic index ranges from 0 (the undivided cosmic span) to 127 (the +/// fully factored product of all 7 cosmic primes). The cycle index ranges +/// from 0 (the undivided cycle) to 255 (the fully factored product of all 8 +/// cycle primes). The asymmetry is not a design choice; it is the difference +/// between seven and eight, which is the difference between the +/// factorizations of two constants nobody chose for their factorizations. +/// +/// These are not arbitrary identifiers, nor are they positions in a list +/// sorted by magnitude—they are bit patterns, one bit per prime, in the same +/// order the `Mask` uses: bit *i* of the cosmic index answers for cosmic +/// prime *i*, bit *j* of the cycle index for cycle prime *j*. Index 0 +/// engages no prime (the undivided whole); the maximum index engages every +/// prime of its axis. The ordering is by prime, not by divisor size: +/// 0b0000011 (Andyte × Xoryte) is a smaller number than 0b0000100 (Oryte) +/// and a larger divisor, and a reader who assumes the index grows with the +/// resolution will be wrong in a way that is easy to make and tedious to +/// find. What the set bits *mean* depends on who produced the coordinate—as +/// an address they name active primes; as the output of +/// `LoicInstant::grid_coord()` they are parity bits, which that method's +/// documentation explains at length and this one merely warns about. +/// +/// ## Flat Addressing +/// +/// A `GridCoord` can be collapsed to a 15-bit flat index via `to_flat()`: +/// `flat = cosmic_idx × 256 + cycle_idx`, yielding values in `[0, 32767]`. +/// This bijection enables compact storage, transmission, and lookup without +/// sacrificing the semantic clarity of the two-axis decomposition, and it is +/// a bijection in the strict sense—every cell has one flat index, every +/// flat index below 32,768 has one cell, and the sixteenth bit of a `u16` +/// addresses nothing whatsoever, a property the lattice shares with the mask +/// and for the same reason. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub struct GridCoord { + /// The cosmic address: a seven-bit pattern over the cosmic primes, one + /// bit per prime in mask order, confined to 0–127 by the constructor + /// rather than by the type, since a `u8` has one bit more than Channel 2 + /// has primes. + cosmic_idx: u8, + /// The cycle address: an eight-bit pattern over the cycle primes, one bit + /// per prime in mask order, confined to 0–255 by the type itself, which + /// for once has exactly as many bits as the axis has primes. + cycle_idx: u8, +} + +impl GridCoord { + /// Constructs a grid coordinate from explicit cosmic and cycle indices, + /// subjecting the cosmic component to the mild indignity of bounds + /// verification—the cycle component, being a `u8`, is naturally confined + /// to `[0, 255]` by the type system itself, exactly the valid range, and + /// requires no runtime check, which is the one place in this crate where + /// a primitive integer's width and the lattice's geometry coincide by + /// happy accident. + /// + /// The cosmic index must fall within `[0, 127]` (the 2⁷ = 128 + /// subdivisions of the cosmic lattice). Values exceeding 127 are rebuffed + /// with `LoicError::InvalidCoordinate`, for the lattice does not extend + /// into imaginary dimensions—however tempting that prospect may be, and + /// however many bits the argument type would happily lend to the attempt. + /// + /// # Errors + /// + /// Returns `LoicError::InvalidCoordinate` when `cosmic_idx > 127`. The + /// rejection is not punitive—it is geometrical. The cosmic axis possesses + /// precisely 128 points; you have named the 129th, which is not an + /// off-by-one but a category error, and the calendar declines to pretend + /// otherwise. The carried message names the index you offered and the + /// maximum you were offered instead. + pub fn new(cosmic_idx: u8, cycle_idx: u8) -> LoicResult { + if cosmic_idx > 127 { + return Err(LoicError::InvalidCoordinate(format!( + "Cosmic index {cosmic_idx} exceeds maximum 127" + ))); + } + Ok(Self { + cosmic_idx, + cycle_idx, + }) + } + + /// Reconstitutes a grid coordinate from its flattened 15-bit avatar, + /// undoing `to_flat()` exactly, since the two are inverse bijections and + /// a round trip through them loses nothing. + /// + /// The flat index encodes `cosmic_idx × 256 + cycle_idx`, a bijection + /// that maps the 128×256 grid onto the integers `[0, 32767]`. Values + /// beyond 32767 are met with the quiet disappointment of an error, for + /// they reference cells in a grid that does not exist—a temporal + /// resolution that the universe's prime factorization simply does not + /// support, there being no sixteenth prime to hang a sixteenth bit on. + /// + /// # Errors + /// + /// Returns `LoicError::InvalidCoordinate` when `flat > 32767`. The + /// 16-bit input type permits 65,536 values; the lattice furnishes 32,768. + /// The upper half of the address space—bit 15 set—names no cell, and the + /// constructor refuses to fabricate one, in exactly the way `Mask::new` + /// refuses the same bit for the same reason. + pub fn from_flat(flat: u16) -> LoicResult { + if flat > 32767 { + return Err(LoicError::InvalidCoordinate(format!( + "Flat index {flat} exceeds maximum 32767" + ))); + } + // The bounds check above guarantees `flat <= 32767`, so the quotient + // and remainder of `flat` by 256 fit trivially in `u8`: the quotient + // peaks at 127, the remainder at 255, and neither has anywhere to + // overflow to. The truncating casts are therefore not truncating in + // any meaningful sense—they merely narrow a value the type system + // cannot prove is already narrow, a proof the reader has just watched + // being performed three lines up and the compiler is not equipped to + // remember. + #[allow( + clippy::cast_possible_truncation, + reason = "flat ≤ 32767 is verified above, so flat/256 ≤ 127 and flat%256 ≤ 255 fit a u8" + )] + Ok(Self { + cosmic_idx: (flat / 256) as u8, + cycle_idx: (flat % 256) as u8, + }) + } + + /// Collapses this coordinate pair into a single 15-bit flat index, the + /// two axes folded into one integer without loss. + /// + /// The encoding `cosmic_idx × 256 + cycle_idx` is the natural row-major + /// linearization of the grid, chosen because the cycle lattice (256 + /// entries) forms the "inner" dimension—varying fastest, as befits the + /// shorter of the two temporal axes, whose partitions turn over within a + /// lifetime while the cosmic axis holds still for longer than there will + /// be stars. `const`, because folding two bytes into two bytes is + /// arithmetic the compiler may perform on your behalf whenever the + /// operands are known to it. + #[must_use = "A coordinate flattened and not received is a 15-bit address sent to no postbox — the lattice knows the cell; nobody asked it which."] + pub const fn to_flat(&self) -> u16 { + (self.cosmic_idx as u16) * 256 + self.cycle_idx as u16 + } + + /// Divulges the cosmic lattice index: which of the 128 cosmic + /// subdivisions is selected, as a seven-bit pattern over the primes of + /// Channel 2, the topological axis. For every instant anyone will ever + /// observe this is zero, and the reader is referred to + /// `LoicInstant::grid_coord()` for the reason, which is not a bug but a + /// consequence of how large seven primes can be. + #[must_use = "Channel 2's address answered and forgotten — the cosmic axis named, no row entered; the topology was consulted and the consultation discarded."] + pub const fn cosmic(&self) -> u8 { + self.cosmic_idx + } + + /// Divulges the cycle lattice index: which of the 256 cycle subdivisions + /// is selected, as an eight-bit pattern over the primes of Channel 1, the + /// content axis—the byte in which, over the course of a human life, + /// something actually happens. + #[must_use = "Channel 1's address answered and ignored — the cycle axis named, no column entered; the only byte of the grid that ever changes, unread."] + pub const fn cycle(&self) -> u8 { + self.cycle_idx + } +} + +/// Renders the coordinate as `(cosmic, cycle)`, two decimal bytes in +/// parentheses, in the order the axes are declared: Channel 2 first, then +/// Channel 1, topology before content, as everywhere in this crate. The +/// presentation layer may dress this up; the core library states the address +/// and nothing more. +impl fmt::Display for GridCoord { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "({}, {})", self.cosmic_idx, self.cycle_idx) + } +} + +/// A bitmask encoding which of the 15 primes are active in a temporal +/// subdivision—which is to say, the observer, in the sense the workspace +/// README gives that word in sections 1.4 and 5.1 and the Loic Public +/// License in Section 6: not a filter applied to pre-existing subdivisions +/// but the thing that constitutes them, the question without which there is +/// no answer. +/// +/// The Loic temporal lattice is governed by 15 primes—7 cosmic and 8 +/// cycle—whose various combinations produce 32,768 distinct temporal +/// resolutions. A `Mask` encodes a specific combination as a 15-bit unsigned +/// integer carried in a `u16`, where each bit corresponds to one prime: +/// +/// | Bits 0–6 | Cosmic primes: Andyte, Xoryte, Oryte, Noryte, Xnoryte, Notyte, Nandyte | +/// | Bits 7–14 | Cycle primes: Dyad, Pentad, Heptad, Hendecad, Sigma, Tau, Phi, Psi | +/// +/// A set bit indicates that the corresponding prime divides the +/// subdivision's divisor. The product of all active primes yields the +/// divisor; the parent constant divided by the divisor yields the +/// subdivision's duration, its *part size*, the grain at which that observer +/// perceives time. Bits 0–6 are Channel 2, the cosmic axis, topology, the +/// "that"; bits 7–14 are Channel 1, the cycle axis, content, the "what." +/// The channels are never swapped, and a reader who finds the numbering +/// counter-intuitive is referred to the workspace README, section 4.3, +/// where the two are defined, and section 1.3, where the calendar is shown +/// to count from the second. +/// +/// The mask with all bits clear (0x0000) represents the undivided whole—no +/// primes active, divisor = 1, duration = full constant: the Whisper, the +/// bottom of the lattice, the question that asks only whether anything is +/// there. The mask with all bits set (0x7FFF) represents the maximally +/// divided state—all primes active, the divisor the product of both +/// constants, and the part size on each channel exactly 1 Planck time, the +/// irreducible quantum below which no observer may descend. Between the two +/// lie 32,766 other observers, every one of them first-class, none of them +/// a month. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub struct Mask { + /// The raw 15-bit mask: bits 0–6 for cosmic primes, bits 7–14 for cycle + /// primes, bit 15 forever clear, since every constructor either refuses + /// it or masks it off and no operation on a valid mask can set it. + bits: u16, +} + +impl Mask { + /// Constructs a mask from raw bits, verifying that no phantom prime has + /// been smuggled into the upper bit. + /// + /// Only the lower 15 bits are meaningful. Bit 15 (the sign bit of a + /// signed 16-bit interpretation, or simply the 16th bit in unsigned + /// territory) must be zero, for there is no 16th prime—the universe's + /// factorization stops at 15, seven from one constant and eight from + /// the other, and no amount of setting a bit will conjure an eighth + /// cosmic prime out of a span that has exactly seven. + /// + /// # Errors + /// + /// Returns `LoicError::InvalidMask` when `bits > 0x7FFF`. The 16th bit + /// names no prime; the universe's lattice is constructed from exactly 15 + /// atoms, and the constructor refuses to grant existence to a + /// hypothetical sixteenth merely because the bit happened to be set. The + /// error carries the bits as offered, so that the caller may see the + /// offending bit in hexadecimal and reflect upon it. + pub fn new(bits: u16) -> LoicResult { + if bits > 0x7FFF { + return Err(LoicError::InvalidMask(bits)); + } + Ok(Self { bits }) + } + + /// The empty mask: no primes active, divisor = 1, the undivided whole. + /// + /// This is the bottom element of the lattice—the state of minimal + /// resolution, where the entire cosmic span or cycle is treated as a + /// single indivisible unit and the only thing an observation can report + /// is that the instant exists. The Loic Public License, Section 6, calls + /// this the Whisper and insists that it is not nothing; it is everything, + /// undifferentiated. `whisper()` is the same mask under that name. + #[must_use = "The undivided whole, summoned by name and walked away from — a refusal so total it observes nothing at all, and then declines even that."] + pub const fn empty() -> Self { + Self { bits: 0 } + } + + /// The full cosmic mask: all 7 cosmic primes active (bits 0–6 set), the + /// top of Channel 2 with Channel 1 untouched. Its cosmic divisor is the + /// Cosmic Span itself, and its part size on that channel is one Planck + /// time: the finest question topology can be asked. + #[must_use = "Seven cosmic primes engaged in maximum Channel 2 commitment — to discard the configuration is to assemble the orchestra, tune it, and leave."] + pub const fn full_cosmic() -> Self { + Self { bits: 0x7F } + } + + /// The full cycle mask: all 8 cycle primes active (bits 7–14 set), the + /// top of Channel 1 with Channel 2 untouched. Its cycle divisor is the + /// Cycle constant itself, and its part size on that channel is one Planck + /// time: the finest question content can be asked. + #[must_use = "Eight cycle primes summoned to maximum rhythm — assembling them and discarding the assembly is a refusal of one's own request, delivered to oneself."] + pub const fn full_cycle() -> Self { + Self { bits: 0x7F80 } + } + + /// The full mask: all 15 primes active, the maximally subdivided state, + /// the top element of the lattice. It is a mixed mask, and so must be + /// presented to `observe_dual()`; there is no single number that answers + /// the finest question on both channels at once. + #[must_use = "All fifteen primes drawn into total resolution — a configuration this exhaustive deserves to be deployed somewhere, not collected and dropped like a coat."] + pub const fn full() -> Self { + Self { bits: 0x7FFF } + } + + /// Extracts the cosmic component: the lower 7 bits, representing which + /// cosmic primes participate in this subdivision, as a bare byte with + /// its top bit necessarily clear. This is the Channel 2 address of the + /// observer, the seven-bit half of a `GridCoord`, and the number whose + /// bits `cosmic_divisor()` multiplies into a product. + #[must_use = "The Channel 2 byte distilled and discarded: topology offered without a question to receive it, seven bits of the 'that' with no 'what' attached."] + pub const fn cosmic_bits(&self) -> u8 { + (self.bits & 0x7F) as u8 + } + + /// Extracts the cycle component: bits 7–14, shifted down by seven to form + /// a standalone 8-bit mask of cycle prime participation, the Channel 1 + /// address of the observer and the eight-bit half of a `GridCoord`. The + /// shift is the entire difference between a cycle bit's position in a + /// mask and its position in this byte; the primes are in the same order + /// on both sides of it. + #[must_use = "The Channel 1 byte distilled and discarded: rhythm offered without an ear to take it, eight bits of content shifted down for nobody."] + pub const fn cycle_bits(&self) -> u8 { + ((self.bits >> 7) & 0xFF) as u8 + } + + /// The raw 15-bit value, carried in sixteen, for those who prefer their + /// primes undecomposed and their addresses hexadecimal. Bit 15 is always + /// clear in the value this method returns; the constructor saw to that. + #[must_use = "The mask's raw 16-bit truth, summoned for inspection — read it, or do not request the inspection; a question asked of the observer is still a question."] + pub const fn bits(&self) -> u16 { + self.bits + } + + /// Counts the active primes—the Hamming weight of the mask, the number of + /// ones in fifteen bits, computed by the processor's own population-count + /// instruction where it has one and by a handful of shifts where it does + /// not. + /// + /// This count determines the subdivision's depth in the lattice: 0 at the + /// bottom (no primes), 15 at the top (all primes), with each intermediate + /// level adding one more prime to the factorization and one more + /// dimension to the question. `resolution()` is this number under the + /// name the framework prefers. + #[must_use = "The Hamming weight retrieved and forgotten — the lattice depth answered, no descent or ascent attempted, the ladder counted and not climbed."] + pub const fn popcount(&self) -> u32 { + self.bits.count_ones() + } + + /// Interrogates a specific bit position to determine whether that prime + /// participates in this subdivision—whether the observer has, in the + /// framing of the workspace README, section 5.1, engaged that relational + /// bond. + /// + /// Bit positions 0–6 correspond to cosmic primes (Andyte through + /// Nandyte); positions 7–14 correspond to cycle primes (Dyad through + /// Psi). A position of 15 or more names no prime and the answer is + /// `false`, without ceremony and without a panic: a prime that does not + /// exist is, for the purposes of this question, a prime that is not + /// engaged, and `activate` and `deactivate` rely on exactly that reading. + #[must_use = "A prime's participation interrogated and unheeded — the bit was queried for a reason; honour the reason, or spare the bit the question."] + pub const fn has_prime(&self, bit: u8) -> bool { + bit < 15 && (self.bits & (1 << bit)) != 0 + } + + /// Activates an additional prime, ascending one level in the lattice to + /// the parent that differs from this mask in exactly that bit—a finer + /// observer, with a larger divisor and a smaller grain, asking one more + /// question than this one did. + /// + /// # Returns + /// + /// `Some` of the ascended mask, or `None` if the prime is already active + /// (one cannot activate what is already active—a tautology the type + /// system regrettably cannot enforce at compile time, and so enforces at + /// runtime by declining) or if the bit position exceeds 14, there being + /// no fifteenth level to ascend to through a sixteenth prime. The + /// original is untouched either way; masks are values, and a value does + /// not change because a copy of it was asked to. + #[must_use = "An ascent through the Hasse diagram computed and discarded — one prime joined the configuration, then nobody arrived to receive it, and the finer question went unasked."] + pub fn activate(&self, bit: u8) -> Option { + if bit >= 15 || self.has_prime(bit) { + None + } else { + Some(Self { + bits: self.bits | (1 << bit), + }) + } + } + + /// Deactivates a prime, descending one level in the lattice to the child + /// that differs from this mask in exactly that bit—a coarser observer, + /// with a smaller divisor and a larger grain, asking one question fewer. + /// + /// # Returns + /// + /// `Some` of the descended mask, or `None` if the prime is already + /// inactive—one cannot deactivate what was never engaged, a + /// philosophical impossibility mirrored here in the type system's + /// refusal to produce a result—or if the bit position exceeds 14, since + /// a prime that does not exist cannot have been engaged in the first + /// place and `has_prime` says as much. + #[must_use = "A descent through the Hasse diagram, charted and abandoned mid-step — the prime was disengaged in vain, and the coarser question dissolved unheard."] + pub fn deactivate(&self, bit: u8) -> Option { + if bit >= 15 || !self.has_prime(bit) { + None + } else { + Some(Self { + bits: self.bits & !(1 << bit), + }) + } + } + + /// Enumerates the lattice parents: all masks reachable by activating + /// exactly one additional prime, in bit order. These are the immediate + /// covers above this node in the Hasse diagram—each parent has one more + /// active prime, a larger divisor, a smaller part size, and therefore a + /// *finer* resolution than this mask: fifteen of them for the Whisper, + /// none for the full mask, and fifteen minus the popcount for everything + /// between. + /// + /// "Above" is meant in the lattice sense (subset partial order, where the + /// empty mask is the bottom and the full mask is the top); the resolution + /// number—the count of active primes—increases monotonically along the + /// parent direction, and so does the specificity of the question, which + /// is the same thing said in the framework's vocabulary. + /// + /// # Returns + /// + /// A freshly allocated `Vec` of the parents, in ascending bit order, + /// empty only for the full mask. The allocation is real and the caller is + /// paying for it. + #[must_use = "Up to fifteen ascending neighbors enumerated into a fresh Vec — the heap allocation is yours, please put at least one of the parents to use before the allocator takes it back."] + pub fn parents(&self) -> Vec { + (0..15u8) + .filter(|&bit| !self.has_prime(bit)) + .map(|bit| Self { + bits: self.bits | (1 << bit), + }) + .collect() + } + + /// Enumerates the lattice children: all masks reachable by deactivating + /// exactly one prime, in bit order. These are the immediate covers below + /// this node in the Hasse diagram—each child has one fewer active prime, + /// a smaller divisor, a larger part size, and therefore a *coarser* + /// resolution than this mask: as many of them as the mask has primes. + /// + /// The empty mask (the Whisper) sits at the bottom of every descending + /// chain; it has no children, since there is no question coarser than + /// "is anything there." The full mask, conversely, has no parents. + /// Between them every chain from bottom to top has exactly fifteen steps, + /// and every step is one prime. + /// + /// # Returns + /// + /// A freshly allocated `Vec` of the children, in ascending bit order, + /// empty only for the Whisper. + #[must_use = "The descending covers tabulated into a fresh Vec — discarding it forfeits the allocation and the descent in equal measure, and neither was free."] + pub fn children(&self) -> Vec { + (0..15u8) + .filter(|&bit| self.has_prime(bit)) + .map(|bit| Self { + bits: self.bits & !(1 << bit), + }) + .collect() + } + + /// Names the mask: the names of its active primes, cosmic before cycle + /// and each channel in prime order, joined by the multiplication sign + /// that is also the arithmetic, since the divisor is their product—or + /// `Whisper` when no prime is active and the question asked is of the + /// undivided whole, which has a name of its own and no factors to list. + /// + /// The oracle prints this in its slot machine and the observatory in its + /// wheels. Both read it from here, and both reach `prime_name` through + /// it, so the two front-ends cannot disagree about what a mask is + /// called—which is the kind of disagreement that would otherwise arise on + /// a Tuesday, unobserved, and persist, the way a bond persists after the + /// content that crossed it has been forgotten. + /// + /// # Returns + /// + /// An owned `String`, freshly assembled from static names, with between + /// zero and fourteen multiplication signs in it: the full mask's label + /// has exactly fourteen, one fewer than its primes, and the test suite + /// counts them. + #[must_use = "A mask named and the name discarded — fifteen primes introduced by name to an empty room, the multiplication signs between them multiplying nothing for anyone."] + pub fn label(&self) -> String { + let names: Vec<&str> = (0..15u8) + .filter(|&bit| self.has_prime(bit)) + .map(prime_name) + .collect(); + if names.is_empty() { + "Whisper".to_owned() + } else { + names.join(" × ") + } + } + + // ── Channel decomposition ──────────────────────────────────────────────── + // + // Two projections, one per channel, each a single bitwise AND. They are + // the reason a mixed mask can be observed at all: `observe_dual` splits + // the observer here and asks each half its own question. + + /// Distils the Channel 2 (cosmic) component: the sub-mask retaining only + /// the topological primes (bits 0–6), the other eight bits cleared. + /// Channel 2 encodes the structural "that" of the observation—the bare + /// dimensional skeleton from which meaning has not yet been permitted to + /// hang, the record that a bond exists rather than what crossed it, per + /// the workspace README, sections 1.3 and 4.3. + /// + /// The complement of `channel_1()` within the mask. Together they + /// partition the mask's prime constituency into two non-overlapping + /// allegiances, and a mask is single-channel exactly when one of the two + /// projections is the Whisper. + #[must_use = "The cosmic projection isolated for inspection — Channel 2 distilled deserves to be observed, not retained then unread; topology unasked is topology unconstituted."] + pub fn channel_2(&self) -> Self { + Self { + bits: self.bits & 0x007F, + } + } + + /// Distils the Channel 1 (cycle) component: the sub-mask retaining only + /// the rhythmic primes (bits 7–14), the seven cosmic bits cleared. + /// Channel 1 encodes the temporal "what" of the observation—the + /// content-laden oscillations that give the cosmic skeleton something to + /// wear, the letters rather than the handshake, the part of the Whisper + /// that was lost. + /// + /// The complement of `channel_2()` within the mask. A mask's channel + /// decomposition is lossless: `channel_1() | channel_2()` reconstitutes + /// the original, bit for bit, and the test suite checks that it does. + #[must_use = "The cycle projection isolated for inspection — Channel 1 distilled deserves to be observed, not retained then unread; content unasked is content that never happened."] + pub fn channel_1(&self) -> Self { + Self { + bits: self.bits & 0x7F80, + } + } + + // ── Divisors ───────────────────────────────────────────────────────────── + // + // The arithmetic behind the observer: the product of the active primes + // is the number the parent constant is divided by, and the quotient is + // the grain. Three products, all in U512, because the largest of them is + // the Cosmic Span itself and the Cosmic Span does not fit in a signed + // word. + + /// Computes the product of all active cosmic primes (the Channel 2 + /// component), by up to seven 512-bit multiplications performed on + /// demand and never cached, since a mask is two bytes and a cache would + /// be sixty-four. + /// + /// This is the divisor that the Loic Calendar uses to subdivide the + /// cosmic span when only the topological channel is engaged. An empty + /// cosmic mask returns `U512_ONE`—the identity, the undivided whole, the + /// denominator that changes nothing and asks for no gratitude in return. + /// + /// # Returns + /// + /// A `U512`, because the product of all 7 cosmic primes equals + /// `COSMIC_SPAN` itself (~6.7×10¹⁵³), which exceeds `I512::MAX`, and a + /// return type that could not hold the full cosmic mask's divisor would + /// be a return type that lied about one observer in a hundred and + /// twenty-eight. Any partial cosmic mask produces a value safely within + /// `U512`, and indeed within `I512`; only the full one needs the extra + /// bit. + #[must_use = "A 7-prime product computed in U512 — the multiplications have already happened; declining the result spends the cycles for nothing and leaves the span undivided by a number nobody read."] + pub fn cosmic_divisor(&self) -> U512 { + let mut product = U512_ONE; + for i in 0..7u8 { + if self.has_prime(i) { + // COSMIC_PRIMES are positive I512 values with their top bit + // clear; cast_unsigned() reinterprets each bit pattern as the + // same numeric value in U512, a reinterpretation the + // processor performs by doing nothing at all. + product *= COSMIC_PRIMES[i as usize].cast_unsigned(); + } + } + product + } + + /// Computes the product of all active cycle primes (the Channel 1 + /// component), by up to eight 512-bit multiplications, the loop stepping + /// over the seven cosmic bits to reach them. + /// + /// This is the divisor applied to `PLANCK_PER_CYCLE` when subdividing + /// along the rhythmic axis. An empty cycle mask returns `U512_ONE`, + /// indicating the full cycle is treated as a single indivisible unit—a + /// monocycle, if you will, though no one will. + /// + /// # Returns + /// + /// A `U512`, for symmetry with `cosmic_divisor()` and `divisor()`: every + /// cycle divisor is a product of positive primes, never negative, and + /// matching the cosmic side spares the rest of the lattice machinery a + /// constant rain of `cast_unsigned()` calls. The value itself fits + /// comfortably within `I512::MAX`—the full cycle divisor is the Cycle + /// constant, fifty-four digits against a signed word's hundred and + /// fifty-four—so the unsigned typing is for compositional convenience, + /// not magnitude necessity. + #[must_use = "An 8-prime product rendered in U512 — the integer's expense was paid; collect the value or the cycles were wasted, and the cycle went undivided."] + pub fn cycle_divisor(&self) -> U512 { + let mut product = U512_ONE; + for i in 7..15u8 { + if self.has_prime(i) { + product *= CYCLE_PRIMES[(i - 7) as usize].cast_unsigned(); + } + } + product + } + + /// Computes the product of ALL active primes across both channels: the + /// cosmic divisor times the cycle divisor, one more 512-bit multiply on + /// top of the fifteen the two halves may already have performed. + /// + /// The combined divisor governs how any quantity is subdivided when this + /// mask is deployed as an observer configuration. Note that the lattice's + /// two axes are subdivided *separately*—`observe_dual()` divides the span + /// by the cosmic divisor and the cycle by the cycle divisor, and never + /// multiplies the two—so this product is a number about the observer, + /// not a denominator any observation uses. + /// + /// # Returns + /// + /// A `U512`, because the cosmic component alone can reach `COSMIC_SPAN` + /// (~6.7×10¹⁵³), which exceeds `I512::MAX`. The universe's factorization + /// does not constrain itself to fit your signed integer, and this crate + /// does not ask it to. + /// + /// # Panics + /// + /// The true product does not always fit in an unsigned 512-bit word + /// either: the span alone lies just above 2⁵¹¹, so any mask engaging all + /// seven cosmic primes together with even the Dyad asks for a number + /// above 2⁵¹², and the full mask's product runs to some two hundred and + /// eight digits. For such masks the multiplication overflows, and `bnum` + /// answers overflow as the primitives do: with a panic in a debug build, + /// and by wrapping in release. The calendar has no wider word to offer; + /// a caller who needs both divisors of such a mask should take them one + /// channel at a time, which is how the lattice uses them anyway. + #[must_use = "The combined 15-prime product, as expensive to compute as it is to ignore — at least one of those costs should buy you something, and only one of them can."] + pub fn divisor(&self) -> U512 { + self.cosmic_divisor() * self.cycle_divisor() + } + + // ── Resolution ─────────────────────────────────────────────────────────── + // + // One number, two names. `popcount` is what the processor calls it; + // `resolution` is what the workspace README calls it, and the README's + // name is the one that explains why the number matters. + + /// Interrogates the observational specificity of this mask—the number of + /// active primes whose simultaneous engagement constitutes the question + /// this observer poses to the temporal substrate. + /// + /// In the parlance of Relational Quantum Mechanics, as the workspace + /// README applies it in sections 1.4 and 5.1, resolution is not a + /// property of the instant being observed but of the observation itself. + /// Zero active primes yields bare topological registration—the Whisper + /// itself, the irreducible acknowledgment that an event occurred, devoid + /// of all contextual elaboration, and also, per section 7.3, the state a + /// system's relational channel collapses to when it breaks down. Fifteen + /// active primes yields maximum decompression: every prime dimension + /// engaged, every structural and rhythmic axis simultaneously + /// interrogated. The relationship between the specificity of a question + /// and the granularity of its answer is, we note, not unique to this + /// calendar. + /// + /// Numerically, this is the Hamming weight of the 15-bit mask—a fact so + /// unremarkable that the documentation declines to lead with it, and + /// that `popcount()` already states for readers who prefer the + /// processor's vocabulary. + /// + /// # Returns + /// + /// An integer from 0 to 15, where each unit represents one additional + /// dimension of observational commitment. + #[must_use = "The observer's depth answered. To request the resolution and discard it is to ask the universe a question and walk away mid-reply, which the universe notices."] + pub const fn resolution(&self) -> u32 { + self.popcount() + } + + // ── Named single-prime constructors ────────────────────────────────────── + // + // Cosmic primes (Channel 2, bits 0–6) are named after logic gates, in + // truth-table order, which is also magnitude order. Cycle primes + // (Channel 1, bits 7–14) are named after their mathematical character, + // in magnitude order. Each constructor activates exactly one prime and + // is `const`, so that a single-prime observer may be named in a static + // table without any runtime arriving to build it. Fifteen atoms of the + // lattice; every other observer is a join of these. + + /// The Andyte mask: Channel 2, bit 0. Cosmic prime 16,631, the smallest + /// of the seven and the coarsest cosmic question there is—a partition of + /// the span nearly 10⁹⁹ years wide. + /// AND gate: 0001—the gate that requires all inputs, tolerates no + /// absence, and outputs nothing until everything it asked for has + /// arrived. + #[must_use = "Andyte awaits engagement — the AND gate requires inputs, not indifference, and yours is the input it was waiting on."] + pub const fn andyte() -> Self { + Self { bits: 1 << 0 } + } + + /// The Xoryte mask: Channel 2, bit 1. Cosmic prime 57,251. + /// XOR gate: 0110—the gate of difference, activated only by + /// disagreement, silent whenever its inputs agree with one another. + #[must_use = "Xoryte was summoned for difference — let it disagree with at least one observation before being discarded, or it will have agreed with nothing."] + pub const fn xoryte() -> Self { + Self { bits: 1 << 1 } + } + + /// The Oryte mask: Channel 2, bit 2. Cosmic prime 21,325,891. + /// OR gate: 0111—the gate that accepts any signal, judgement suspended, + /// content with whichever input troubles to show up. + #[must_use = "Oryte accepts any signal — surely it accepts being read once it has been constructed; it has never refused anything else."] + pub const fn oryte() -> Self { + Self { bits: 1 << 2 } + } + + /// The Noryte mask: Channel 2, bit 3. Cosmic prime 3,014,283,645,143, + /// thirteen digits, the last of the seven that a `u64` could have held. + /// NOR gate: 1000—the gate that speaks only when all inputs fall silent, + /// and is, with NAND, one of the two gates from which every other can be + /// assembled. + #[must_use = "Noryte speaks only when all inputs fall silent — letting it fall silent itself defeats the joke, and the joke was the point."] + pub const fn noryte() -> Self { + Self { bits: 1 << 3 } + } + + /// The Xnoryte mask: Channel 2, bit 4. Cosmic prime ~1.28×10²⁶, + /// twenty-seven digits, the first of the seven too large for a `u64`. + /// XNOR gate: 1001—the gate of agreement, activated only by consensus, + /// the exact inverse of Xoryte and equally uninterested in compromise. + #[must_use = "Xnoryte awaits consensus — let your code consent to use it before discarding the agreement it was built to detect."] + pub const fn xnoryte() -> Self { + Self { bits: 1 << 4 } + } + + /// The Notyte mask: Channel 2, bit 5. Cosmic prime ~2.99×10²⁶, + /// twenty-seven digits, a near neighbour of Xnoryte in magnitude and its + /// opposite in temperament. + /// NOT gate: 1100—the gate of inversion, the simplest refusal, the one + /// gate with a single input and a single thing to say about it. + #[must_use = "Notyte awaits inversion — to discard it is to refuse to refuse, which is, after all, NOT NOT, which is to say nothing at all."] + pub const fn notyte() -> Self { + Self { bits: 1 << 5 } + } + + /// The Nandyte mask: Channel 2, bit 6. Cosmic prime ~2.86×10⁷², + /// seventy-three digits, the largest atom of the lattice and the finest + /// cosmic question—which is still a partition four thousand billion + /// billion billion years wide. + /// NAND gate: 1110—the universal gate, the one from which all others can + /// be built, and therefore the one prime in whose name the whole Boolean + /// algebra is implicitly present. + #[must_use = "Nandyte is the universal gate — squandering it is squandering the entire algebra in miniature, every other gate included by construction."] + pub const fn nandyte() -> Self { + Self { bits: 1 << 6 } + } + + /// The Dyad mask: Channel 1, bit 7. Cycle prime 2, the first bit past the + /// channel boundary and the smallest prime there is. + /// The binary split—the first and most consequential division, the one + /// that halves the 894-year cycle and whose parity bit is the cheapest + /// proof the test suite has that the grid projection reads the cycle + /// axis at all. + #[must_use = "Dyad summoned and abandoned mid-bisection — the first division of the cycle, refused before it could divide anything, which for a two is a particular indignity."] + pub const fn dyad() -> Self { + Self { bits: 1 << 7 } + } + + /// The Pentad mask: Channel 1, bit 8. Cycle prime 5. + /// The decimal bridge—where binary meets the human penchant for base + /// ten, five being the factor that, with two, makes ten, and so the + /// prime by which every decimal digit of every reliquary in this crate + /// is secretly indebted to the cycle. + #[must_use = "Pentad bridges binary and decimal — five subdivisions await tenancy, and the bridge is open in both directions, though not, apparently, to you."] + pub const fn pentad() -> Self { + Self { bits: 1 << 8 } + } + + /// The Heptad mask: Channel 1, bit 9. Cycle prime 7. + /// The week—seven days, for reasons the calendar declines to adjudicate, + /// having no days and therefore no weeks and therefore no stake in the + /// matter; a Heptad partition of the cycle is some 127.72 years, which + /// is not a week by any measure but is a seventh, and a seventh is what + /// the prime provides. + #[must_use = "Heptad subdivides the cycle into seven — a unit our species has built civilisations around; please at least bind it to a name before letting it go."] + pub const fn heptad() -> Self { + Self { bits: 1 << 9 } + } + + /// The Hendecad mask: Channel 1, bit 10. Cycle prime 11. + /// The prime of primes—the fifth prime, suspicious in its smallness, and + /// the largest of the four familiar ones; with Dyad and Heptad it is one + /// of the three cycle primes that divide the epoch's offset from Unix + /// time, which is the whole reason the offset is the number it is. + #[must_use = "Hendecad — eleven subdivisions, suspicious in their smallness; they extend the courtesy of existing for you, please reciprocate by reading at least one."] + pub const fn hendecad() -> Self { + Self { bits: 1 << 10 } + } + + /// The Sigma mask: Channel 1, bit 11. Cycle prime 683. + /// The first stranger—emerged from the collision of H₀, α, and π and has + /// no significance outside this context, which is the context it is in, + /// so the observation is less damning than it sounds. + #[must_use = "Sigma — the first stranger, emerged from the collision of H₀, α, and π. Strangers should not be dismissed without a hearing, and this one has travelled."] + pub const fn sigma() -> Self { + Self { bits: 1 << 11 } + } + + /// The Tau mask: Channel 1, bit 12. Cycle prime 2,887. + /// The second stranger—larger than Sigma, equally uninvited, and, like + /// Sigma, a number that would have been unremarkable in any other + /// setting and is here a load-bearing axis of time. + #[must_use = "Tau — the second stranger, larger than Sigma and equally uninvited. You did invite this one, deliberately, by name; please follow through, as one does with guests."] + pub const fn tau() -> Self { + Self { bits: 1 << 12 } + } + + /// The Phi mask: Channel 1, bit 13. Cycle prime ~4.28×10²¹. + /// The cosmic grain—a 22-digit prime that appeared unbidden from the + /// floor function of an irrational expression and stayed, too large for + /// a `u64` and too specific to be anything but what the arithmetic + /// produced. + #[must_use = "Phi — the 22-digit cosmic grain, returned for use; it crossed considerable irrationality to reach you, please don't drop it on the doorstep."] + pub const fn phi() -> Self { + Self { bits: 1 << 13 } + } + + /// The Psi mask: Channel 1, bit 14. Cycle prime ~8.06×10²². + /// The final factor—the largest cycle prime, the outermost rhythm, the + /// last bit of the lattice, and the prime whose partition of the cycle + /// is the finest a single cycle prime can make it: some 6.5 × 10³⁰ + /// Planck times, about a third of a picosecond, which is the sharpest + /// single-prime question on the content axis and finer than the kernel's + /// nanosecond by three orders of magnitude, so that which Psi tick you + /// occupy is a matter the entropy decides and the clock cannot. + #[must_use = "Psi — the 23-digit final factor, the outermost rhythm; a vast number diminished only by neglect, do not be the agent of its diminution."] + pub const fn psi() -> Self { + Self { bits: 1 << 14 } + } + + // ── Lattice traversal helpers ───────────────────────────────────────────── + // + // How far apart two observers are, and whether one is a refinement of + // the other. The Hasse diagram of a fifteen-bit Boolean lattice has + // 32,768 nodes and 245,760 edges; these three functions walk none of + // them and answer by bit arithmetic instead. + + /// Measures the Hamming distance to another mask: the count of prime + /// dimensions that differ between the two observer configurations, the + /// popcount of their exclusive-or, and the length of the shortest path + /// between them along the edges of the Hasse diagram. + /// + /// Distance zero means identical observers—the same primes active, the + /// same resolution, the same everything. Distance 15 means maximally + /// opposed observers, separated by all 15 prime dimensions, each the + /// complement of the other. Distance anything-in-between means partial + /// overlap—observers who agree on some primes and disagree on others, + /// which is most of them, as it is most of anyone. Two single-prime + /// masks are always at distance two, and the test suite checks Andyte + /// against Dyad to make sure. + #[must_use = "Hamming distance is a small number, but it is still a number; please do not collect it for the sake of having collected it — two observers were compared, and nobody learned how far apart they stand."] + pub fn distance(&self, other: &Self) -> u32 { + (self.bits ^ other.bits).count_ones() + } + + /// Adjudicates whether this mask is a sub-mask of `other`: every prime + /// active here is also active in `other`. Equivalently, `self`'s bit + /// pattern is a subset of `other`'s, which a single AND and a comparison + /// establish without enumerating anything. + /// + /// In lattice parlance, this is the ≤ relation: `self` occupies a + /// position below or equal to `other` in the Hasse diagram, a coarser + /// or identical question. A mask is always below itself. The empty mask + /// is below everything, and the full mask below nothing but itself. + /// This is the relation `PartialOrd` exposes as `<=`, and it is partial: + /// most pairs of masks are neither below nor above one another. + #[must_use = "The ≤ relation has been adjudicated; ignoring its verdict is judicial contempt, and the court was convened at your request."] + pub fn is_below(&self, other: &Self) -> bool { + (self.bits & other.bits) == self.bits + } + + /// Adjudicates whether this mask is a super-mask of `other`: every prime + /// active in `other` is also active here. Equivalently, `other`'s bits + /// are a subset of `self`'s, and the implementation says exactly that, + /// by asking `other` whether it is below. + /// + /// In lattice parlance, this is the ≥ relation: a finer or identical + /// question. The full mask is above everything. A mask is always above + /// itself. The Whisper is above nothing but itself, which is the + /// lattice's way of saying that no question is coarser than none. + #[must_use = "The ≥ relation adjudicated, returned, and ignored — the same offense as discarding `is_below`, in mirror image, and no less contemptuous for the reflection."] + pub fn is_above(&self, other: &Self) -> bool { + other.is_below(self) + } + + // ── Lattice operations ──────────────────────────────────────────────────── + // + // A Boolean lattice has a join, a meet, and a complement; with those + // three it is a Boolean algebra, and a fifteen-bit integer under OR, AND + // and NOT is the canonical example of one. The Hasse traversals above + // walk the lattice; these three operate on it, in one instruction each. + + /// Composes the join of two observers: their least upper bound in the + /// lattice, the smallest mask that engages every prime either of them + /// engages—which in a Boolean lattice is the bitwise OR, and in the RQM + /// framing of the workspace README, section 1.4, is the question that + /// asks everything both observers asked and nothing more. + /// + /// The join of any mask with the Whisper is itself. The join of any mask + /// with its complement is the full mask. The join of a mask with itself + /// is itself. The join is commutative, associative, and idempotent, + /// three properties the calendar mentions because it has them and most + /// things do not. `a | b` is this operation with the operator spelling. + #[must_use = "The least upper bound of two observers, computed and discarded — the union of two questions, asked of no one, which is one fewer than a question requires."] + pub const fn join(&self, other: &Self) -> Self { + Self { + bits: self.bits | other.bits, + } + } + + /// Composes the meet of two observers: their greatest lower bound, the + /// largest mask that engages only primes both of them engage—the bitwise + /// AND, or, in the framing this crate prefers, the part of the question + /// the two observers actually agree to ask. + /// + /// Two masks that share no prime meet at the Whisper: the only question + /// they have in common is whether anything is there at all. This is not + /// a degenerate case. It is the most common one, and it is the case the + /// workspace README, section 7.3, describes as the whole of what a + /// system in breakdown can still say to the outside. `a & b` is this + /// operation with the operator spelling. + #[must_use = "The greatest lower bound of two observers, computed and discarded — the common ground located, then vacated, as though it had never been surveyed."] + pub const fn meet(&self, other: &Self) -> Self { + Self { + bits: self.bits & other.bits, + } + } + + /// Composes the complement of an observer: every prime this mask + /// declined to engage, and none that it did. The complement of a + /// question is not its negation. It is every other question. + /// + /// `m.join(&m.complement())` is the full mask and + /// `m.meet(&m.complement())` is the Whisper, for every `m`—the two + /// identities that make a lattice Boolean, and both are exercised by the + /// test suite on a single-prime mask, which is the case in which they are + /// least obvious. Bit 15, which names no prime, is masked off; the + /// complement of a valid mask is always a valid mask, and the + /// constructor's vigilance is not required. `!a` is this operation with + /// the operator spelling, and `!!a` is `a`, as one would hope. + #[must_use = "Every question you did not ask, enumerated and discarded — the complement was computed for someone; be that someone, or admit you never wanted the other questions."] + pub const fn complement(&self) -> Self { + Self { + bits: !self.bits & 0x7FFF, + } + } + + // ── Whisper alias ───────────────────────────────────────────────────────── + // + // The bottom of the lattice under the name the framework gives it. + + /// The Whisper configuration: zero primes active, bare topological + /// registration, the minimum-resolution observer state, the mask + /// through which an observation reports only that the instant exists + /// and how far it is from Creation. + /// + /// The Whisper is the calendar's own epoch event—the first ARPANET + /// packet—encoded as an observer configuration. It is a Channel 2 event, + /// per the workspace README, section 1.3: pure structure, no content, + /// the irreducible acknowledgment that something happened, with all + /// elaboration deferred to observers who engage more primes. The letters + /// were lost; the bond was established; this mask is the bond. + /// + /// Identical to `empty()`, offered under this name for contexts where + /// the RQM framing is more illuminating than the lattice framing, and + /// because a calendar that counts from the Whisper ought to be able to + /// say the word. + #[must_use = "The Whisper, summoned by name and not received — fitting, perhaps, for an event called a whisper, but unbecoming of code that requested it and then did not listen."] + pub const fn whisper() -> Self { + Self::empty() + } + + // ── Entropy default ────────────────────────────────────────────────────── + // + // The one constructor that can fail on purpose. The workspace README, + // section 7.3, calls the failure resolution collapse; the Loic Public + // License, Section 6, calls it permitted and, with probability + // approximately 25%, catastrophic. Both are describing this function. + + /// Solicits the universe for an observer configuration when the caller + /// has declined to provide one—an act of ontological negligence whose + /// consequences are, by design, not uniformly survivable. The workspace + /// README, section 1.4, holds that the observer participates in + /// constituting the answer; a caller who will not say which observer + /// they are has delegated that participation to the kernel's entropy + /// pool, and the pool is under no obligation to frame a question the + /// lattice can hold. + /// + /// Nine bits of entropy, drawn fresh from the kernel's pool for this + /// purpose, determine the mask: + /// - **Bit 0** selects the lattice pool: 0 = cycle (256 subdivisions), + /// 1 = cosmic (128 subdivisions). + /// - **Bits 1–8** select the subdivision index within that pool, and + /// become, bit for bit, the primes of the mask: the index *is* the + /// address, in the same bit order a `GridCoord` uses. + /// + /// If the cosmic pool is selected and the index exceeds 127 (the cosmic + /// lattice has only 128 members, indexed 0–127, but 8 bits address 256), + /// the observation is *undefined*. The mask cannot be constructed. The + /// question was not merely unframed—it was malformed at a level the + /// lattice cannot absorb, an eighth cosmic prime demanded of a span that + /// has seven. This occurs with probability 128/512 = 25%, and the test + /// suite draws twenty thousand times to confirm that it does. The seven + /// remaining bits of the two bytes drawn are discarded unread, which is + /// the universe declining to answer a question that was slightly too + /// wide. + /// + /// # Returns + /// + /// `Ok(Mask)` for the 75% of entropy configurations that produce a valid + /// single-channel mask—never a mixed one, since each pool populates one + /// channel and leaves the other at the Whisper. + /// `Err(LoicError::InvalidMask)` for the 25% that select a cosmic index + /// beyond the lattice boundary—a boundary the caller could have avoided + /// by specifying which question to ask. + /// + /// The error is not a crash. It is a diagnosis. What the caller does with + /// it—panic, display resolution collapse, spawn topological solitons in + /// the process table in the manner of section 4.5—is a matter for the + /// application layer and its conscience. The library merely reports that + /// Channel 2 has collapsed to resolution zero while the caller's Channel + /// 1 is presumably still producing, which is the diagnostic signature of + /// breakdown per section 7.1, and leaves the rest to the front-ends. + /// + /// # Errors + /// + /// Returns `LoicError::InvalidMask(0x8000 | index)` with probability 25% + /// when the cosmic pool is selected (bit 0 == 1) and the entropy-drawn + /// index exceeds 127. The carried `u16` reuses bit 15—the same bit that + /// no valid mask is permitted to set—as a signal flag, with the lower 8 + /// bits encoding the offending index, which is therefore always at least + /// 128. Visualisation layers rely on this contract to render the + /// question's malformation as a topological scar, and the test suite + /// checks both halves of it on every collapse it provokes. + /// + /// # Panics + /// + /// Panics if the operating system's entropy pool is unavailable—a + /// condition `getrandom` reports as a hard failure. On Linux this would + /// require `getrandom(2)`, `/dev/urandom`, and every fallback the + /// `getrandom` crate knows to be inoperative simultaneously, a + /// configuration in which the calendar is the least of your problems and + /// the panic message is the most helpful thing on the machine. + pub fn entropy_default() -> LoicResult { + let mut buf = [0u8; 2]; + getrandom::fill(&mut buf).expect("the kernel's entropy pool declined to answer"); + let bits = u16::from_le_bytes(buf); + + // Bit 0: pool selection. 0 = cycle, 1 = cosmic. One bit decides + // which channel the question is asked on; the other channel stays + // at the Whisper, which is why the result is never mixed. + let pool = bits & 1; + // Bits 1–8: subdivision index (0–255), the next byte up. Bits 9–15 + // are drawn and never read. + let index = ((bits >> 1) & 0xFF) as u8; + + if pool == 0 { + // Cycle pool: the index selects one of 256 cycle masks (8 bits, + // 8 primes, a bijection). Each bit of the index activates the + // corresponding cycle prime once shifted past the seven cosmic + // bits. This pool cannot collapse; the byte and the axis are + // the same width. + Ok(Self { + bits: u16::from(index) << 7, + }) + } else if index < 128 { + // Cosmic pool, valid index: selects one of 128 cosmic masks (7 + // bits, 7 primes), the index landing directly on bits 0–6. + Ok(Self { + bits: u16::from(index), + }) + } else { + // Cosmic pool, index >= 128: an undefined observation. The eighth + // bit of the index names a cosmic prime the span does not have, + // and it is carried out, flagged with bit 15, as the scar. + Err(LoicError::InvalidMask(0x8000 | u16::from(index))) + } + } + + // ── Entropy floor ───────────────────────────────────────────────────────── + // + // The grain of the observer, stated as a count of Planck times: the + // width of the gap the workspace README, section 1.4, calls load-bearing. + + /// Measures the number of Planck times inaccessible below this mask's + /// resolution: the causally-active gap that no observer at this + /// configuration can reach, measure, or hold accountable, and that + /// continues, unobserved, to shape everything the next observation will + /// find. + /// + /// The entropy floor is the grain size of the observation—the floor is + /// not empty space, it is load-bearing, in exactly the sense the + /// workspace README gives that phrase in section 1.4: what the + /// substrate generates and the observer cannot access is where causality + /// lives. Everything the observer cannot see continues to exist and + /// continues to matter; it simply declines to appear in the subdivision + /// result, and this method reports how much of it there is. + /// + /// - For a cosmic-bearing mask: `COSMIC_SPAN / cosmic_divisor` (the size + /// of one cosmic partition at this Channel 2 resolution). + /// - For a cycle-only mask: `PLANCK_PER_CYCLE / cycle_divisor` (the size + /// of one cycle partition at this Channel 1 resolution). + /// - For the empty mask: `COSMIC_SPAN` (the entire representable timeline + /// is gap—the observer has registered nothing, and so nothing is + /// accessible, and the floor is the whole of time). + /// + /// In every case the value is the `part_size` that `observe()` would + /// report for the same channel, since the floor and the grain are one + /// number seen from two sides. + /// + /// ## Mixed masks + /// + /// For a mask engaging both channels (`cosmic_bits != 0` AND + /// `cycle_bits != 0`), this function returns the *cosmic floor only*. + /// The cycle floor is silently discarded. This is consistent with the + /// philosophy that Channel 2 (topology) is the dominant grain when both + /// are present—the structural register precedes the rhythmic one, the + /// "that" before the "what"—and also reflects the fact that any single + /// `U512` return must commit to one number. Callers that require both + /// floors should engage the channels separately + /// (`mask.channel_1().entropy_floor()` and + /// `mask.channel_2().entropy_floor()`) or work through `observe_dual()`, + /// which reports both grains as part sizes. + /// + /// # Returns + /// + /// A `U512`, because cosmic-scale floors exceed `I512::MAX` for + /// low-resolution cosmic masks, and for the Whisper the floor is the + /// Cosmic Span itself, which exceeds it by definition. + #[must_use = "The grain size of the unobserved, computed in U512; ignoring it does not make the floor disappear, it merely makes you ignorant of it, which is the floor's preferred arrangement."] + pub fn entropy_floor(&self) -> U512 { + let c2 = self.channel_2(); + let c1 = self.channel_1(); + if c2.bits != 0 { + COSMIC_SPAN / c2.cosmic_divisor() + } else if c1.bits != 0 { + // PLANCK_PER_CYCLE is a positive I512; cast_unsigned() reinterprets + // it as the same U512 value, bit for bit and free of charge, and + // the cycle divisor already lives in U512, so the whole quotient + // stays unsigned and no sign is ever asked to mean anything. + PLANCK_PER_CYCLE.cast_unsigned() / c1.cycle_divisor() + } else { + COSMIC_SPAN + } + } + + // ── Observation ────────────────────────────────────────────────────────── + // + // The second of the two calls the workspace README, section 5.1, says + // the mask-as-observer relationship reduces to. `now()` is the collapse; + // this is the question. + + /// Observes a `LoicInstant` through this mask, collapsing the + /// sub-resolution superposition into a `SubdivisionResult` that tells + /// you which tick you are in and how far into it—two 512-bit divisions + /// and a remainder, which is all a clock has ever been. + /// + /// This method is the RQM heart of the lattice, per the workspace + /// README, sections 1.4 and 5.1: the `Mask` is the observer, the instant + /// is the system, and the `SubdivisionResult` is what the interaction + /// produces. Properties of neither object alone—only the coupling yields + /// the answer, and a different mask presented with the same instant + /// yields a different answer that is no less true. The instant does not + /// know which tick it is in until it is asked through which primes. + /// + /// # Channel semantics + /// + /// - **Empty mask** (the Whisper): `position = 0`, + /// `offset = cosmic_time`, `part_size = COSMIC_SPAN`. Bare + /// topological registration—the observation records that the instant + /// exists, within the undivided whole, and how far from Creation it + /// lies. Matches `entropy_floor()` for the same case. + /// - **Cosmic-only** (Channel 2): subdivides `COSMIC_SPAN` by + /// `cosmic_divisor`. `position` = which cosmic partition, `offset` = + /// Planck times into that partition. For every instant anyone will + /// observe, the position is zero; the partitions are that wide. + /// - **Cycle-only** (Channel 1): subdivides `PLANCK_PER_CYCLE` by + /// `cycle_divisor`, after first reducing the cosmic time modulo the + /// cycle. `position` = which cycle partition, `offset` = Planck times + /// into that partition. + /// - **Mixed**: returns `LoicError::MixedMask`—use `observe_dual()` + /// instead, which conducts both observations and returns both results, + /// since there is no single quotient that answers two questions. + /// + /// In every successful case `position × part_size + offset` reconstructs + /// the time that was divided, cosmic or cycle, exactly; the test suite + /// checks the identity on both channels and at Annihilation. + /// + /// # Errors + /// + /// Returns `LoicError::MixedMask`, carrying the mask's bits, if the mask + /// spans both channels. The error is a redirection, not a rebuke: the + /// question was two questions, and there is a method for that. + pub fn observe(&self, instant: &LoicInstant) -> LoicResult { + let c2 = self.channel_2(); + let c1 = self.channel_1(); + if c2.bits != 0 && c1.bits != 0 { + return Err(LoicError::MixedMask(self.bits)); + } + // All subdivision arithmetic happens in U512 — see SubdivisionResult's + // field documentation for why the sign bit is not to be trusted with + // the Cosmic Span. cosmic_time() already returns U512, and is always + // non-negative for a valid instant, since nothing precedes Creation. + let cosmic_time = instant.cosmic_time(); + if c2.bits != 0 { + // Cosmic-only: subdivide COSMIC_SPAN by cosmic_divisor. The + // quotient is the tick, the remainder the distance into it; the + // two divisions are the price of asking. + let part_size = COSMIC_SPAN / c2.cosmic_divisor(); + let position = cosmic_time / part_size; + let offset = cosmic_time % part_size; + Ok(SubdivisionResult::new(position, offset, part_size)) + } else if c1.bits != 0 { + // Cycle-only: subdivide PLANCK_PER_CYCLE by cycle_divisor, but + // first fold the cosmic time into the current cycle, because the + // content axis repeats every 894 years and the question is where + // within this turn of it we are, not how many turns there have + // been. PLANCK_PER_CYCLE is a positive I512; cast_unsigned + // preserves its numeric value as U512 for compatibility with + // cosmic_time. + let pcycle = PLANCK_PER_CYCLE.cast_unsigned(); + let part_size = pcycle / c1.cycle_divisor(); + let cycle_time = cosmic_time % pcycle; + let position = cycle_time / part_size; + let offset = cycle_time % part_size; + Ok(SubdivisionResult::new(position, offset, part_size)) + } else { + // Empty mask: bare topological registration. The "undivided + // whole" sentinel is COSMIC_SPAN itself, the U512 value that + // exactly represents the entire representable timeline, and the + // offset is the cosmic time entire: no division was performed, + // because no question was asked that a division could answer. + Ok(SubdivisionResult::new(U512_ZERO, cosmic_time, COSMIC_SPAN)) + } + } + + /// Observes a `LoicInstant` through both channels simultaneously, + /// producing a `DualObservation` that holds both the cosmic (Channel 2) + /// and cycle (Channel 1) subdivision results, each computed as though + /// the other did not exist. + /// + /// This method is the appropriate entry point for mixed masks—masks that + /// engage primes in both channels and therefore cannot be reduced to a + /// single-channel observation without discarding information. It accepts + /// single-channel masks too, and even the Whisper, reporting whichever + /// channel is unengaged through the Whisper's own answer: position zero, + /// the cosmic time as offset, the Cosmic Span as part size, nothing + /// subdivided—the same registration for an empty cycle projection as + /// for an empty cosmic one, since an unasked question has one answer. + /// + /// Internally, this calls `channel_2().observe()` and + /// `channel_1().observe()`. Each observation is independent; neither + /// channel is aware of the other's result. This is not a limitation but + /// the point: in the Loic Calendar, topology (Channel 2) and content + /// (Channel 1) do not interfere with each other. They cohabit; they do + /// not converse. The workspace README, section 4.3, is where the two + /// channels are pulled apart, and this method keeps them so. + /// + /// # Panics + /// + /// Cannot panic. The method invokes `observe()` twice—once on + /// `channel_2()` and once on `channel_1()`—and unwraps each result. Both + /// calls are constitutionally incapable of returning `MixedMask`, since + /// each operand has been pre-projected onto a single channel by a + /// bitwise AND that cannot leave bits on the other side. The `expect` is + /// a notarized guarantee, not a genuine fallibility, and clippy is + /// welcome to its disagreement. + #[must_use = "Two SubdivisionResults assembled across both channels — a dual observation collapses two superpositions; do not throw both away in a single move, when one would already have been a waste."] + pub fn observe_dual(&self, instant: &LoicInstant) -> DualObservation { + let ch2_result = self + .channel_2() + .observe(instant) + .expect("channel_2 is a single-channel projection and cannot be mixed"); + let ch1_result = self + .channel_1() + .observe(instant) + .expect("channel_1 is a single-channel projection and cannot be mixed"); + DualObservation { + channel_2: ch2_result, + channel_1: ch1_result, + } + } +} + +/// The result of a dual-channel observation: two `SubdivisionResult`s, one +/// per channel, produced by presenting a mask—mixed or otherwise—to +/// `observe_dual()`. +/// +/// A `DualObservation` does not synthesize its two channels. Channel 2 +/// (topology) and Channel 1 (content) are reported separately, because they +/// measure different spans (`COSMIC_SPAN` vs `PLANCK_PER_CYCLE`) and cannot +/// be meaningfully combined into a single number without losing the +/// information that distinguishes them—which is, per the workspace README, +/// section 4.3, exactly the information a black hole is careful to keep +/// apart, and the calendar sees no reason to be less careful than a black +/// hole. +/// +/// The consumer is expected to inspect both fields and decide what, if +/// anything, to do with the resulting pair of positions and offsets. The +/// calendar provides the decomposition; the interpretation is, as always, +/// your problem. The fields are public because there is nothing to protect: +/// each is a finished observation, and the pair is only a pair. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DualObservation { + /// The Channel 2 (cosmic / topological) subdivision result: the "that," + /// listed first because the structural register precedes the rhythmic + /// one everywhere in this crate. + pub channel_2: SubdivisionResult, + /// The Channel 1 (cycle / rhythmic) subdivision result: the "what," the + /// one whose position actually changes within a human lifetime. + pub channel_1: SubdivisionResult, +} + +/// Renders the mask as its raw bits in hexadecimal, zero-padded to four +/// digits with the `0x` prefix—`0x0000` for the Whisper, `0x7fff` for the +/// full mask—which is the form the error messages use and the form the +/// Loic Public License, Section 6, accepts as an answer to "what gate is +/// it." The names are available from `label()`; this is the address. +impl fmt::Display for Mask { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:#06x}", self.bits) + } +} + +/// The subset partial order on masks—and it is *partial*, which is the +/// entire point of implementing it. +/// +/// `a < b` when every prime `a` engages, `b` engages too, and `b` engages at +/// least one more: `a` is a coarser observer, strictly below `b` in the +/// Hasse diagram, a question that `b` asks and then some. Two masks that +/// share no subset relationship—Andyte and Dyad, say, or any pair that each +/// engage a prime the other does not—are *incomparable*, and `partial_cmp` +/// says so by returning `None`. Rust's `PartialOrd` was designed for exactly +/// this situation and is almost never used for it; most implementors reach +/// for it because `Ord` was too much paperwork, and the floating-point types, +/// which need it only because they contain a value that is not equal to +/// itself, have given the trait a reputation it does not deserve. Here the +/// partiality is the mathematics. There is no total order on observers. +/// Some questions are simply not more or less than other questions, and +/// the type system is permitted to say so. +/// +/// Consequently the comparison operators behave as the lattice does: `<` +/// and `>` are the strict subset relations, `<=` and `>=` the reflexive +/// ones, and for incomparable masks every one of them is `false`—as is +/// `==`, since they are not equal either—which is a thing `bool` can express +/// and the reader is invited to sit with. The test suite sits with it on +/// Andyte and Dyad, and confirms all five. +impl PartialOrd for Mask { + fn partial_cmp(&self, other: &Self) -> Option { + if self.bits == other.bits { + Some(Ordering::Equal) + } else if self.is_below(other) { + Some(Ordering::Less) + } else if self.is_above(other) { + Some(Ordering::Greater) + } else { + None + } + } +} + +/// `a | b` is the join: the least upper bound, the union of two questions. +/// The operator is offered because a lattice whose join cannot be written +/// with the symbol every programmer already uses for it would be needlessly +/// withholding, and because the join of two fifteen-bit observers *is* the +/// bitwise OR of their bits, so the operator is not an analogy but the +/// arithmetic. It delegates to [`Mask::join`] and adds nothing of its own. +impl BitOr for Mask { + type Output = Self; + fn bitor(self, rhs: Self) -> Self::Output { + self.join(&rhs) + } +} + +/// `a & b` is the meet: the greatest lower bound, the part of two questions +/// that both observers agreed to ask, which for most pairs is the Whisper. +/// See [`Mask::meet`]; the operator delegates to it, and the bitwise AND of +/// the bits is, again, not a metaphor for the meet but the meet itself. +impl BitAnd for Mask { + type Output = Self; + fn bitand(self, rhs: Self) -> Self::Output { + self.meet(&rhs) + } +} + +/// `!a` is the complement: every question `a` did not ask. See +/// [`Mask::complement`]. `!Mask::full()` is the Whisper; `!Mask::whisper()` +/// is everything; `!!a` is `a`, as it should be and, in a fifteen-bit +/// lattice with the sixteenth bit masked off on every application, actually +/// is—the involution holds because the mask-off is idempotent, and the test +/// suite applies it twice to a single prime to be sure. +impl Not for Mask { + type Output = Self; + fn not(self) -> Self::Output { + self.complement() + } +} + +/// The result of subdividing a temporal quantity at a given resolution: the +/// answer an observer receives, three unsigned 512-bit integers that between +/// them say which tick, how far into it, and how wide a tick is. +/// +/// When an instant's Planck count is divided by a subdivision's part size +/// (the duration of one "tick" at that resolution), the quotient is the +/// position (which tick are we in?) and the remainder is the offset (how +/// far into that tick?). This decomposition is the fundamental operation of +/// temporal measurement at any resolution, and it is the whole of what a +/// clock does: a clock with a face divides the day by twelve and reports +/// the quotient with a hand. +/// +/// Consider: at the resolution defined by the Pentad×Heptad subdivision +/// (divisor = 35, cycle axis), the cycle is divided into 35 equal parts of +/// some 25.5 years each. If the current cycle offset places us at position +/// 29 with some remainder, then we are in the 29th tick of 35, counting +/// from zero, and the offset tells us precisely—to the Planck time—where +/// within that tick. +/// +/// This is what clocks do. This is what calendars do. We merely generalize +/// it to all 32,768 possible resolutions simultaneously, decline to +/// privilege any of them, and refuse to round. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SubdivisionResult { + /// Which tick of the subdivision we occupy (0-indexed). + /// For a subdivision with divisor D, position ∈ [0, D-1] for all + /// interior instants. The single boundary case where `position == D` is + /// `ANNIHILATION` observed through any non-empty cosmic mask: at that + /// instant `cosmic_time == COSMIC_SPAN`, and integer division by + /// `part_size = COSMIC_SPAN / D` yields exactly `D`, with nothing left + /// over. This mirrors the `offset == part_size` boundary case for the + /// empty mask—the representable-time edge produces reflexive equalities + /// that cleaner interior arithmetic does not, and the test suite visits + /// the edge to confirm both. `U512` rather than `I512` because the full + /// cosmic divisor reaches `COSMIC_SPAN` itself (~6.7×10¹⁵³), which + /// exceeds `I512::MAX`. + position: U512, + /// The Planck-time offset within the current tick. + /// Strictly less than `part_size` for all interior instants. The single + /// exception is `ANNIHILATION` itself with the empty (Whisper) mask, at + /// which `offset == part_size == COSMIC_SPAN`—the boundary case where + /// "you are 100% of the way through the undivided whole" is the only + /// honest answer, and the reflexive equality is a feature of the + /// representable-time edge rather than a violation of the lattice + /// structure. `U512` to remain consistent with `position` and + /// `part_size`, and because for the Whisper the offset is the cosmic + /// time itself, which a signed word cannot hold near Annihilation. + offset: U512, + /// The duration of one tick at this resolution, in Planck times. + /// Equal to `parent_constant` / divisor: the grain, the entropy floor, + /// the width of everything the observer cannot resolve. `U512` because + /// for the empty (Whisper) mask the conceptual part size is + /// `COSMIC_SPAN`, exceeding `I512::MAX`. + part_size: U512, +} + +impl SubdivisionResult { + /// Constructs a subdivision result from its constituent components, + /// wrapping three integers in the semantic garments of an observation. + /// + /// No validation is performed—the caller is trusted to provide values + /// that satisfy the invariant `offset < part_size`, which holds + /// everywhere except at the one boundary the field documentation + /// confesses to. This trust is extended because subdivision results are + /// typically produced by integer division, which inherently satisfies + /// these constraints, and because a result that lied about its own tick + /// would deceive nobody but the caller who assembled it. + #[must_use = "A SubdivisionResult constructed and discarded — a tick computed and forgotten before it could be inhabited, three integers dressed for an observation that never happened."] + pub fn new(position: U512, offset: U512, part_size: U512) -> Self { + Self { + position, + offset, + part_size, + } + } + + /// Divulges the position within the subdivision: which tick, counting + /// from zero, as the quotient of the observed time by the grain. + /// + /// For a cycle subdivision with divisor 35 (Pentad×Heptad), this value + /// ranges from 0 to 34—answering the question "which of the 35 equal + /// parts of the cycle are we currently traversing?" For any cosmic + /// subdivision, and for every instant before the last star has been + /// dark longer than it shone, it is zero, and the question was worth + /// asking anyway. Returned by reference, since sixty-four bytes are + /// sixty-four bytes and the caller may only want to look. + #[must_use = "The current tick, named and ignored — the calendar told you which one you're in; you should know, and you have just declined to."] + pub fn position(&self) -> &U512 { + &self.position + } + + /// Divulges the Planck-time offset within the current tick: the + /// remainder, the part of the answer the resolution could not swallow. + /// + /// This is the remainder after dividing the instant by the part size— + /// the irreducible residue of precision that the subdivision's + /// resolution cannot capture, and the number that is still exact to the + /// Planck time no matter how coarse the observer. It is always + /// non-negative, and strictly less than `part_size` except at the single + /// boundary instant `ANNIHILATION` observed through the empty mask, + /// where `offset == part_size == COSMIC_SPAN`. See the field doc on + /// `offset` for the rationale. + #[must_use = "The intra-tick remainder retrieved and forgotten — the irreducible residue of precision deserves at least a glance, having survived the division for your sake."] + pub fn offset(&self) -> &U512 { + &self.offset + } + + /// Divulges the duration of a single tick at this resolution, in Planck + /// times: the grain of the observer, the entropy floor beneath the + /// answer. + /// + /// This value is the temporal "grain" of the subdivision, computed at + /// observation time as `parent_constant / divisor`—where the parent + /// constant is `COSMIC_SPAN` for cosmic-channel observations and + /// `PLANCK_PER_CYCLE` for cycle-channel observations. Finer subdivisions + /// have smaller part sizes; coarser subdivisions have larger ones. The + /// undivided whole (the Whisper mask) has a part size equal to the full + /// constant; the maximally divided state—every prime in the engaged + /// channel active—has a part size of exactly 1 Planck time, the + /// irreducible quantum below which no observer may further descend, and + /// at which the offset is always zero because there is nowhere within a + /// single Planck time to be. + #[must_use = "The grain at this resolution, summoned and ignored — the calendar told you how big a tick is; please listen, the floor is load-bearing."] + pub fn part_size(&self) -> &U512 { + &self.part_size + } +} + +// ╔═══════════════════════════════════════════════════════════════════════════╗ +// ║ LOIC DURATION ║ +// ║ ║ +// ║ The Measurement of Temporal Extent, Untethered ║ +// ║ ║ +// ║ A duration is time without place—an interval floating free of epochs, ║ +// ║ anchored to no moment, measuring only the span between hypothetical ║ +// ║ events. It is the answer to "how long" without answering "when." ║ +// ║ It is never short of itself. See seconds_to_planck for the ceiling. ║ +// ╚═══════════════════════════════════════════════════════════════════════════╝ + +/// A span of time measured in Planck intervals, detached from any particular +/// epoch: a magnitude and a direction, and nothing else. +/// +/// ## The Philosophy of Duration +/// +/// If `LoicInstant` represents a point—a specific location on the finite but +/// unreasonably long timeline between Creation and Annihilation—then +/// `LoicDuration` represents a vector: a magnitude with direction (positive +/// toward the future, negative toward the past) but no origin. A duration of +/// one second is one second regardless of whether it elapses in the +/// Cretaceous Period or the heat death of the universe, and regardless of +/// which of the 32,768 observers is watching it elapse: durations are the +/// one thing in this crate that no mask constitutes, because a duration is a +/// count of Planck times and Planck times are what every mask is made of. +/// +/// ## Representation +/// +/// Durations are stored as 512-bit signed integers counting Planck times. +/// This allows durations ranging from approximately -10^103 to +10^103 +/// years—sufficient to measure intervals from "less than a proton's +/// lifetime" to "longer than the universe will exist in any recognizable +/// form," and one Planck time is the resolution throughout, which is not a +/// thing a floating-point type could say about any interval at all. +/// +/// The sign indicates temporal direction: +/// - **Positive**: toward the future (the heat death awaits) +/// - **Negative**: toward the past (Creation beckons) +/// - **Zero**: the eternal now, where nothing changes because no time passes +/// +/// ## A Note on Floating-Point Conversion +/// +/// This struct provides an `as_seconds_f64()` method. Do not call it. It +/// exists only to document its own prohibition—a monument to the heresy of +/// lossy conversion, a trap for the unwary, a test of faith. It is +/// deprecated, so that the compiler objects first, and it will panic, so +/// that the runtime objects to whoever silenced the compiler. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct LoicDuration { + /// The raw count of Planck times constituting this duration. Positive + /// values indicate forward (future-ward) durations; negative values + /// indicate backward (past-ward) durations; zero indicates that the + /// question "how long" has been answered with "not at all." + planck: I512, +} + +impl LoicDuration { + /// Constructs a duration from raw Planck times—the fundamental unit of + /// temporal extent, the only unit this crate regards as native. + /// + /// This constructor accepts a 512-bit signed integer and wraps it in the + /// semantic garments of a duration. No validation occurs; all `I512` + /// values are valid durations, for who are we to say that a duration of + /// -10^100 Planck times is somehow illegitimate? It is merely longer + /// than the universe has been, pointed the wrong way, and the type is + /// content to hold it. + /// + /// Available in const contexts, since wrapping an integer in a struct + /// requires no runtime ceremony. The compile-time constructor permits + /// durations to be inscribed into static tables and other + /// const-evaluated data without resorting to `LazyLock`, which this + /// crate reserves for the one fact only the kernel can supply. + #[must_use = "A LoicDuration constructed and never measured — a span without a span-er, an interval between two events neither of which was consulted."] + pub const fn from_planck(planck: I512) -> Self { + Self { planck } + } + + /// The zero duration: no time passes, nothing changes, entropy stands + /// still—which, per the workspace README, section 2.2, would mean the + /// decompression had paused, and it has not. + /// + /// This is the identity element under duration addition—adding zero + /// duration to any instant yields that same instant, a mathematical + /// tautology that nonetheless requires explicit representation in our + /// type system, since the type system does not know a tautology when it + /// sees one and must be handed the element by name. + #[must_use = "Zero duration summoned and ignored — the eternal now wasted on a discarded variable, which is at least a fitting fate for it."] + pub const fn zero() -> Self { + Self { planck: I512_ZERO } + } + + /// Constructs a duration spanning N Earth days—N spans of 86,400 SI + /// seconds, that is, the TAI day of the Loic Public License, Section 16, + /// which has never heard of a leap second and never will. + /// + /// One day equals 86,400 seconds, a figure inherited from the Babylonians + /// who divided the day into 24 hours of 60 minutes of 60 seconds each. + /// This works out to approximately 1.602 × 10^48 Planck times per day—a + /// number that would make a Babylonian astronomer's head explode, which + /// the calendar notes with regret, since they were careful people. + /// + /// The count is widened to `i128` before the multiplication by 86,400, + /// so no `i64` count, however deranged, can overflow on its way to the + /// 512-bit conversion; the conversion itself rounds up, so that N days + /// is never a Planck time short of N days. + #[must_use = "N days reckoned in 512-bit Planck precision — surely the result is worth at least a binding, after the Babylonians went to all that trouble."] + pub fn days(count: i64) -> Self { + Self { + planck: seconds_to_planck(i128::from(count) * i128::from(SECONDS_PER_DAY)), + } + } + + /// Constructs a duration spanning N hours, each of 3,600 SI seconds. + /// + /// One hour equals 3,600 seconds, or approximately 6.68 × 10^46 Planck + /// times. The hour is an arbitrary division of the day, yet it persists + /// because human schedules evolved around it, and inertia governs + /// culture as surely as it governs physics—more surely, in fact, since + /// physics at least permits a change of reference frame. The count is + /// widened to `i128` before the multiplication, as `days` widens its + /// own, and the ceiling conversion applies. + #[must_use = "N hours converted to ~6.7×10⁴⁶ Planck times each — the multiplication has been performed; please use the result, or the hour was idle."] + pub fn hours(count: i64) -> Self { + Self { + planck: seconds_to_planck(i128::from(count) * 3_600), + } + } + + /// Constructs a duration spanning N minutes, each of 60 SI seconds. + /// + /// One minute equals 60 seconds, or approximately 1.113 × 10^45 Planck + /// times. The word "minute" derives from the Latin "pars minuta prima" + /// (first small part), referring to the first division of the hour into + /// sixtieths—a terminology that made more sense when people actually + /// thought in sexagesimal, and that the "second" (pars minuta secunda, + /// the second small part) carries to this day without anyone noticing. + /// The count is widened to `i128` before the multiplication, and the + /// ceiling conversion applies. + #[must_use = "N minutes rendered as ~1.1×10⁴⁵ Planck times each — the math is exact; the result is yours; please collect it before the next minute makes it stale."] + pub fn minutes(count: i64) -> Self { + Self { + planck: seconds_to_planck(i128::from(count) * 60), + } + } + + /// Constructs a duration spanning N seconds, the SI base unit and the + /// unit in which every other constructor is secretly denominated. + /// + /// The second is the SI base unit of time, defined as 9,192,631,770 + /// periods of the radiation corresponding to the transition between the + /// two hyperfine levels of the ground state of the caesium-133 atom at + /// rest at absolute zero—the one relation, per the workspace README, + /// section 1.2, that this calendar chose to enter in preference to every + /// relation mediated by a planet or a parliament. In Planck times, this + /// works out to approximately 1.855 × 10^43. + /// + /// We do not ask you to contemplate what "9.192 billion oscillations of a + /// caesium atom" means. We merely store the result with perfect + /// fidelity—which is to say, as the smallest whole number of Planck + /// times that is not shorter than N seconds. See `seconds_to_planck`, in + /// the implementation, for why "not shorter" is the operative phrase, and + /// why the alternative would make one second round-trip to zero. + #[must_use = "N seconds rendered as ~1.9×10⁴³ Planck times each — the SI base unit deserves at least a let-binding; the caesium atom oscillated nine billion times for this."] + pub fn seconds(count: i64) -> Self { + Self { + planck: seconds_to_planck(i128::from(count)), + } + } + + /// Retrieves the raw Planck count—the unvarnished truth of temporal + /// extent, the number every other method on this type is a courtesy + /// around. + /// + /// This returns a reference to the internal 512-bit integer, allowing + /// inspection without the overhead of cloning 64 bytes of temporal data, + /// though the type is `Copy` and the caller may dereference at leisure. + /// The value may be positive, negative, or zero, with meanings as + /// documented in the struct-level commentary above, and it is exact: no + /// Planck time has been rounded away between the constructor and here. + #[must_use = "The unvarnished Planck count of this duration, returned by reference for your inspection — please inspect it; it has nothing to hide and sixty-four bytes to show."] + pub const fn planck(&self) -> &I512 { + &self.planck + } + + /// Converts to whole seconds via rational arithmetic, truncating toward + /// zero, by a quotient–remainder split that never lets an intermediate + /// product outgrow the 512-bit word. + /// + /// This method performs the conversion: seconds = planck × (5.391247 × + /// 10^-44) using exact integer multiplication and division. The result + /// is truncated, not rounded, because rounding would require choosing a + /// direction, and who are we to impose such subjective judgments upon + /// mathematics? Truncation toward zero is symmetric in sign, so a + /// duration and its negation report negated seconds, and the test suite + /// checks this at the extremes of the representable range against an + /// independent 1024-bit computation that never needs the split. + /// + /// Note that for durations less than one second in magnitude, this + /// returns zero, in either direction. The sub-second Planck times are + /// not lost—they were never in the result to begin with. If you need + /// them, use `.planck()` and perform your own arithmetic, exactly, as + /// this crate does. Every constructor round-trips through this method + /// without loss: `seconds(n).as_whole_seconds()` is `n` for every `n`, + /// which is the property the ceiling in `seconds_to_planck` exists to + /// guarantee. + #[must_use = "Whole seconds extracted via quotient-remainder rational arithmetic — truncation already cost precision; throwing the result away costs the rest, and the rest was the point."] + pub fn as_whole_seconds(&self) -> I512 { + // seconds = planck × numerator / denominator = planck × 5391247 / 10^50 + // + // The naive formulation `self.planck * NUM / DENOM` overflows I512 + // for `planck > I512::MAX / NUM ≈ 1.24×10¹⁴⁷`, which is reachable + // within representable Loic time (annihilation is at ~6.7×10¹⁵³), so + // a naive duration of the span's length would wrap rather than + // convert, and a wrapped duration is a lie with a unit attached. + // We split via quotient-remainder to avoid the intermediate overflow: + // planck × NUM / DENOM + // = (q × DENOM + r) × NUM / DENOM where q = planck/DENOM, r = planck%DENOM + // = q × NUM + (r × NUM) / DENOM + // Both q×NUM and r×NUM stay within I512 for any representable instant: + // q ≤ I512::MAX / DENOM ≈ 6.7×10¹⁰³, so q×NUM ≤ ~3.6×10¹¹⁰ + // r < DENOM = 10⁵⁰, so r×NUM ≤ ~5.4×10⁵⁶ + // Two divisions and two multiplications, all at 512 bits; this is + // not a hot path, and exactness is the only budget it has. + let num = PLANCK_NUMERATOR_I512; + let denom = PLANCK_DENOMINATOR; + let q = self.planck / denom; + let r = self.planck % denom; + q * num + (r * num) / denom + } + + /// Attempts to convert this duration to floating-point seconds, and + /// fails, on purpose, every time. + /// + /// # ⚠️ THE HERESY OF FLOATING-POINT ⚠️ + /// + /// This method exists as a monument to human weakness—a temptation + /// placed here by the calendar's architects to test the faith of its + /// users. It compiles. It has a sensible signature. It looks like it + /// should work. + /// + /// It does not. + /// + /// IEEE 754 binary floating-point arithmetic is fundamentally + /// incompatible with the Loic Calendar's commitment to exactitude. A + /// 64-bit float provides merely ~15 decimal digits of precision. A + /// Planck-time count requires up to 154 digits. The loss would be + /// catastrophic—not in the floating-point sense of "catastrophic + /// cancellation," but in the spiritual sense of betraying everything we + /// stand for, and in the specific sense the workspace README gives the + /// word in section 1.1: an approximation delivered with the confidence + /// of an exact value is a lie, and the Loic Public License, Section 1, + /// names the practice apostasy. + /// + /// # Panics + /// + /// Always. Unconditionally. Without mercy or exception, and without + /// examining its argument beyond formatting it into the sermon. + /// + /// The panic message will explain your error and suggest alternatives. + /// Consider them. Reflect upon them. Use `.planck()` or + /// `.as_whole_seconds()`. Return to the path of integer righteousness. + /// + /// # Deprecation + /// + /// The method is additionally marked deprecated, so that the compiler + /// raises the objection before the runtime has to. The warning is the + /// heresy being detected at the earliest possible moment; the panic + /// remains for those who silence warnings, a population the calendar + /// regards with the same affection it reserves for floating-point, and + /// the test suite silences the warning exactly once, to confirm that the + /// panic is still there behind it. + #[deprecated( + since = "1.0.0", + note = "IEEE 754 is heresy and this method exists only to panic. Use .planck() or .as_whole_seconds(). The compiler is warning you so that the runtime does not have to." + )] + #[must_use = "If by some heresy this f64 returned instead of panicking, you must still not use it. The attribute is theatrical; the prohibition is sincere, and the sermon is on its way."] + pub fn as_seconds_f64(&self) -> f64 { + panic!( + "HERESY DETECTED\n\n\ + You have attempted to convert a LoicDuration to floating-point.\n\n\ + IEEE 754 is an abomination. Its sins include:\n\ + • Silent precision loss\n\ + • The seductive lie that 0.1 + 0.2 equals 0.3\n\ + • The quiet tragedy of catastrophic cancellation\n\ + • The existence of negative zero, as though absence had polarity\n\n\ + This duration contains {} Planck times of exactitude.\n\ + You proposed to represent it with ~15 decimal digits of approximation.\n\n\ + The Loic Calendar does not compromise. Neither should you.\n\n\ + Alternatives:\n\ + • .planck() - The true value, in full\n\ + • .as_whole_seconds() - Integer seconds, honestly truncated\n\ + • Reflection upon what led you here", + self.planck + ); + } + + /// Adjudicates whether this duration is exactly zero—the temporal + /// nullity, the absence of extent, the moment without before or after, + /// the degenerate case where "how long?" is met with "not at all" and + /// the asker is left to contemplate whether the question was meaningful + /// in the first place. + /// + /// A zero duration is not the same as a zero instant. An instant is a + /// point on the timeline; a zero instant denotes The Whisper itself. A + /// duration is a magnitude with sign; a zero duration denotes no + /// magnitude in either direction. They share a numeric representation + /// (`planck == 0`) and nothing else of consequence, which is why they + /// are two types and not one. + /// + /// # Returns + /// + /// `true` if `self.planck == 0`. `false` for any non-zero Planck count, + /// regardless of sign—an exquisitely brief femtosecond and a duration + /// spanning the entire cosmological span are equally non-zero by this + /// reckoning. The function passes no judgment on magnitude, and a single + /// Planck time, the smallest non-zero duration there is, is as non-zero + /// as any. + #[must_use = "The temporal nullity adjudicated. The verdict was not pronounced for the void to absorb it, though the void is the subject of the verdict."] + pub fn is_zero(&self) -> bool { + self.planck == I512_ZERO + } + + /// Adjudicates whether this duration points pastward (toward Creation), + /// which is to say whether its Planck count is strictly negative. + /// + /// A negative duration represents time flowing backward—not in the + /// physical sense (for the arrow of time is relentless, and the Loic + /// Public License, Section 11, makes no warranty that it will not + /// reverse, but has never had to honour the clause), but in the + /// arithmetic sense of subtracting from an instant rather than adding to + /// it. Zero is not negative; the eternal now points nowhere. + #[must_use = "The pastward inclination adjudicated, returned, and ignored — the verdict still stands; please at least branch on it, since the branch was the reason to ask."] + pub fn is_negative(&self) -> bool { + self.planck < I512_ZERO + } + + /// Computes the absolute value of this duration—its magnitude without + /// direction, the vector reduced to its length. + /// + /// The philosophical equivalent of asking "how much time?" without + /// asking "in which direction?" Useful when you care about the span but + /// not the temporal orientation, which is most of the time, since most + /// callers already know which way they are facing. + /// + /// # Panics + /// + /// Panics if `self.planck == I512::MIN`. The two's-complement + /// representation has no positive counterpart for `MIN`—there is one + /// more negative number than positive, and `-MIN` overflows. + /// `LoicDuration::from_planck(I512::MIN)` is constructable (durations + /// have no inherent bounds, unlike `LoicInstant`), so the edge is + /// reachable via direct construction; `difference()` reaches it only for + /// a pair of instants exactly 2⁵¹¹ Planck times apart, which requires one + /// of them to lie within an age of the universe of Annihilation, and the + /// constructors `seconds`/`minutes`/`hours`/`days` cannot reach it at + /// all, since an `i64` count of days falls some eighty-six orders of + /// magnitude short. The panic is the calendar's most honest possible response + /// to a magnitude it can name and cannot hold. + #[must_use = "Magnitude without direction, returned by value — 'how much time?' is a question worth answering into a binding, not the void, which has all the time it needs."] + pub fn abs(&self) -> Self { + Self { + planck: self.planck.checked_abs().expect( + "LoicDuration::abs overflow: -I512::MIN is not representable, there being one \ + more negative number than positive in two's complement, and this duration is \ + it. The magnitude exists; the word to hold it does not.", + ), + } + } +} + +/// Debug formatting for `LoicDuration`: reveals the inner Planck count as a +/// decimal string inside a named struct, since debuggers may struggle to +/// interpret 512 bits of raw temporal data and a human reading eight +/// hexadecimal limbs would struggle more. +impl fmt::Debug for LoicDuration { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("LoicDuration") + .field("planck", &self.planck.to_string()) + .finish() + } +} + +/// Display formatting for `LoicDuration`: renders as "{N} Planck times", a +/// human-readable proclamation of temporal extent in the only unit the +/// calendar considers canonical, per the Loic Public License, Section 16. +/// Seconds are available from `as_whole_seconds()`; hours are not available +/// from anywhere, and are not going to be. +impl fmt::Display for LoicDuration { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} Planck times", self.planck) + } +} + +/// Addition of durations: the concatenation of temporal spans. +/// +/// Given durations D₁ and D₂, their sum D₁ + D₂ represents "first D₁, then +/// D₂"—or equivalently, "the total span if both were laid end to end." This +/// operation is commutative (D₁ + D₂ = D₂ + D₁) and associative, and it is +/// performed at 512 bits without a bounds check, since durations have no +/// bounds; a sum that outgrows the word behaves as `bnum` arithmetic does on +/// overflow, panicking in a debug build and wrapping in release, and the +/// operands required to provoke that are some ninety orders of magnitude +/// longer than the universe has existed. +impl Add for LoicDuration { + type Output = Self; + fn add(self, rhs: Self) -> Self::Output { + Self { + planck: self.planck + rhs.planck, + } + } +} + +/// Subtraction of durations: the difference of temporal spans. +/// +/// D₁ - D₂ yields the duration that, when added to D₂, produces D₁. Useful +/// for answering questions like "how much longer is this duration than that +/// one?" with exact Planck-time precision, and subject to the same remarks +/// on overflow as addition, for the same reason. +impl Sub for LoicDuration { + type Output = Self; + fn sub(self, rhs: Self) -> Self::Output { + Self { + planck: self.planck - rhs.planck, + } + } +} + +/// Negation of duration: temporal reversal. +/// +/// If a positive duration represents "this much time into the future," its +/// negation represents "this much time into the past." The magnitude +/// remains unchanged; only the direction reverses. The one duration that +/// cannot be reversed is `I512::MIN`, whose negation does not exist in two's +/// complement, and which `abs` documents at greater length; every duration +/// a constructor produces reverses exactly, and the test suite checks that +/// `seconds(-n)` and `-seconds(n)` are the same duration. +impl Neg for LoicDuration { + type Output = Self; + fn neg(self) -> Self::Output { + Self { + planck: -self.planck, + } + } +} + +/// Partial ordering: delegates to the total ordering, since all durations +/// are comparable—a signed integer has no value that is unequal to itself, +/// which is more than the floating-point types can say and the reason they +/// are stuck with this trait alone. +impl PartialOrd for LoicDuration { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +/// Total ordering of durations: earlier (more negative) comes before later +/// (more positive), by comparison of the Planck counts and nothing else. +/// +/// This ordering is consistent with the intuition that "shorter durations +/// are less than longer durations" when both are positive, and "more +/// past-ward durations are less than more future-ward durations" when +/// considering signed values. It is total in the strict sense: any two +/// durations are less, equal, or greater, and the type system is permitted +/// to promise it, which it could not for masks and does not pretend to. +impl Ord for LoicDuration { + fn cmp(&self, other: &Self) -> Ordering { + self.planck.cmp(&other.planck) + } +} + +// ╔═══════════════════════════════════════════════════════════════════════════╗ +// ║ LOIC INSTANT ║ +// ║ ║ +// ║ The Fundamental Quantum of Loic Time ║ +// ║ ║ +// ║ A precise moment in the continuum between Creation and Annihilation, ║ +// ║ measured as a 512-bit signed integer counting Planck times since The ║ +// ║ Whisper—the first ARPANET transmission at 06:30:41 UTC on 1969-10-30. ║ +// ║ The count is exact. The sub-nanosecond digits are an observation. ║ +// ╚═══════════════════════════════════════════════════════════════════════════╝ + +/// A precise moment in the temporal continuum, measured as Planck times +/// since The Whisper, in a signed 512-bit integer that has never met a +/// rounding error and does not intend to. +/// +/// ## The Nature of an Instant +/// +/// An instant is a point—infinitely thin, dimensionless in temporal extent, +/// representing a specific location on the timeline stretching from +/// Creation (the Big Bang, ~13.8 billion years ago) to Annihilation (the +/// maximum representable moment, ~10¹⁰³ years hence). Unlike a duration, +/// which measures *how much* time, an instant specifies *when*—though the +/// workspace README, section 1.3, would add that "when" is a gradient with +/// physical thickness, and that the sub-nanosecond digits of every instant +/// this crate manufactures are where that thickness lives. +/// +/// ## The Epoch: The Whisper +/// +/// The calendar's epoch—Planck time zero—coincides exactly with The Whisper: +/// 06:30:41 UTC on October 30, 1969, the moment a UCLA researcher attempted +/// to transmit "LOGIN" to Stanford and the receiving system crashed after +/// "LO" had arrived. Every Planck count this library emits is measured +/// against that single instant of incomplete authentication. Moments +/// preceding it bear negative values; moments succeeding it bear positive +/// ones; The Whisper itself is the irreducible zero from which all temporal +/// accounting proceeds, and the Loic Public License, Section 7, forbids +/// relocating it for any purpose whatsoever. +/// +/// The bridge to Unix time is mediated by `LOIC_TO_UNIX_OFFSET_SECONDS` +/// (5,419,722—squarefree, three cycle primes), which encodes the offset +/// from the Unix epoch to The Whisper on the `CLOCK_TAI` scale. +/// +/// ## Precision and Bounds +/// +/// The 512-bit signed integer representation permits values from +/// approximately -2^511 to +2^511, corresponding to roughly ±1.1 × 10¹⁰³ +/// years from The Whisper. This exceeds the lifetime of the universe by many +/// orders of magnitude, ensuring that the Loic Calendar will not require a +/// Y2K-style remediation until long after the last black hole has +/// evaporated, at which point, per the workspace README, section 4.7, there +/// will be nobody left to observe the remediation anyway. +/// +/// `CREATION_PLANCK` and `ANNIHILATION_PLANCK` bound the valid range, which +/// is the negative half up to the age of the universe and the positive half +/// entire. Attempting to construct an instant outside this range produces +/// an Underflow or Overflow error, respectively; the calendar does not +/// represent what physics does not describe. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct LoicInstant { + /// The raw Planck time count since The Whisper (1969-10-30 06:30:41 + /// UTC). Negative values represent moments before the epoch; positive + /// values, after; and every value that came out of `now()` carries + /// thirty-four low digits that were an observation rather than a + /// measurement, which the type does not distinguish and the arithmetic + /// need not. + planck: I512, +} + +impl LoicInstant { + // ╭───────────────────────────────────────────────────────────────────────╮ + // │ C O N S T R U C T O R S │ + // │ │ + // │ The sacred rites of instant creation: from raw Planck times, from │ + // │ the void of the epoch, or from the entropic dance of quantum noise. │ + // │ Only the last is an observation. The others are assertions. │ + // ╰───────────────────────────────────────────────────────────────────────╯ + + /// Constructs a `LoicInstant` from raw Planck times, with cosmological + /// bounds checking: two comparisons against the edges of time, and + /// admission to existence if both are passed. + /// + /// This is the canonical constructor for instants from numeric data. It + /// validates that the provided Planck count falls within the bounds of + /// representable time: + /// - Values below `CREATION_PLANCK` produce `LoicError::Underflow` + /// - Values above `ANNIHILATION_PLANCK` produce `LoicError::Overflow` + /// - Values within bounds produce `Ok(LoicInstant)` + /// + /// The upper check can never fail in practice, since no `I512` exceeds + /// `I512::MAX` and Annihilation is `I512::MAX`; it is performed anyway, + /// because the calendar states its boundaries in full and does not rely + /// on the width of a word to enforce a cosmological claim. + /// + /// # Arguments + /// + /// * `planck` - A 512-bit signed integer representing Planck times since + /// the Loic epoch, negative for moments before the Whisper. + /// + /// # Returns + /// + /// `Ok(LoicInstant)` if the value is within bounds, or an appropriate + /// `LoicError` otherwise, carrying the rejected coordinate as a decimal + /// string for the caller's contemplation. + /// + /// # Errors + /// + /// - `LoicError::Underflow` when `planck < CREATION_PLANCK`—the moment + /// lies in the pre-cosmological void where time itself was not yet + /// defined and the calendar refuses to fabricate a coordinate the + /// universe never furnished. + /// - `LoicError::Overflow` when `planck > ANNIHILATION_PLANCK`—the + /// moment exceeds the upper edge of `I512`, beyond which our + /// representation simply ends. Time may continue; our integers shall + /// not, and the Loic Public License, Section 11, has already declined + /// to warrant that time will. + pub fn from_planck(planck: I512) -> LoicResult { + // Boundary enforcement: reject moments before time itself began, on + // the grounds that there was nothing there to be a moment of. + if planck < CREATION_PLANCK { + return Err(LoicError::Underflow(planck.to_string())); + } + // Boundary enforcement: reject moments after representable time + // ends. No I512 can fail this; the check is a statement of policy. + if planck > ANNIHILATION_PLANCK { + return Err(LoicError::Overflow(planck.to_string())); + } + // The moment is valid; admit it to existence, which for a moment is + // the same as admitting it to the type. + Ok(Self { planck }) + } + + /// Constructs a `LoicInstant` from raw Planck times, trusting the + /// caller's judgment and performing no check of any kind. + /// + /// This constructor bypasses bounds checking for performance-critical + /// scenarios where the caller can guarantee the value falls within + /// `[CREATION, ANNIHILATION]`. If this guarantee is violated, subsequent + /// operations may produce nonsensical results, but no undefined behavior + /// will occur (we're in safe Rust, after all, and a wrong number is not + /// the same as an unsound one). + /// + /// Specifically: the `U512`-returning accessors `cosmic_time()`, + /// `terminal_time()`, and `progress()` continue to return values across + /// the entire `I512` input domain—they cannot panic, since their + /// subtraction wraps by design—but for inputs outside + /// `[CREATION, ANNIHILATION]` those returned magnitudes have no physical + /// meaning: a pre-Creation instant's "cosmic time" is a large positive + /// number that answers no question anyone asked. Other operations + /// (`add_duration`, `sub_duration`) still bounds-check at their + /// boundaries and will surface errors, so an invalid instant cannot be + /// laundered into a valid one by arithmetic. + /// + /// # When to Use + /// + /// - Internal calculations where bounds are mathematically guaranteed + /// - Deserialization of known-valid data + /// - Performance-critical loops where bounds were checked externally + /// - The test suite, which uses it to stand one Planck time before the + /// Whisper without ceremony + /// + /// # When NOT to Use + /// + /// - User input + /// - Untrusted data sources + /// - Any situation where you're even slightly uncertain about the bounds + /// + /// When in doubt, use `from_planck()`. The bounds check is two 512-bit + /// comparisons, which is cheap; your sanity is not, and the calendar + /// declines to price it. + #[must_use = "A LoicInstant constructed without bounds checking is still an instant — discarding it is still a wasted observation, with the additional indignity of having skipped the verification for nothing."] + pub const fn from_planck_unchecked(planck: I512) -> Self { + Self { planck } + } + + /// The Loic epoch: Planck time zero, the origin of our temporal + /// coordinate system, and the one instant that can be summoned at + /// compile time because it requires no clock to locate. + /// + /// This instant *is* The Whisper—1969-10-30 06:30:41 UTC, the moment a + /// crash at the receiving host interrupted the first ARPANET transmission + /// after two of five intended characters had crossed four hundred miles + /// of leased telephone line. The calendar does not pretend that some + /// more dignified moment underlies the epoch; it takes "LO" and the + /// subsequent crash as the foundational event from which all temporal + /// coordinates are reckoned, because, per the workspace README, section + /// 1.3, the bond held even though the content did not, and the bond is + /// what the calendar counts from. + /// + /// The epoch serves as the reference point for all Planck time + /// calculations. Instants before this moment have negative Planck + /// values; instants after have positive values. The epoch itself has + /// Planck value exactly zero—the one coordinate in the calendar with no + /// entropy in it at all, since nothing was observed to produce it. + #[must_use = "The Whisper itself, summoned and discarded — a crash immortalised, then forgotten again, which is at least consistent with how the first one was treated."] + pub const fn epoch() -> Self { + Self { planck: I512_ZERO } + } + + /// Procures the present temporal coordinate within the Loic framework, + /// transmuting the ineffable flux of universal chronological progression + /// into a concrete manifestation of Planck-scale precision, by the + /// synthesis of one atomic measurement and one act of entropy. + /// + /// ## The Metaphysics of Now + /// + /// "Now" is a slippery concept. In physics, the present moment is + /// infinitely thin—a boundary between past and future with no + /// duration—or, per the workspace README, section 1.3, a gradient with + /// physical thickness, bounded above by the speed of light and below by + /// the rendering edge of wave-function collapse. Yet we must represent + /// it somehow, and we do so by combining two sources of temporal + /// information: + /// + /// 1. **Atomic Time (`CLOCK_TAI`)**: The Linux kernel provides + /// International Atomic Time with nanosecond resolution. This forms + /// the "classical" component of our measurement, deterministic and + /// reproducible (assuming synchronized atomic clocks), and it is read + /// through the vDSO in about twenty-two nanoseconds, which is the + /// floor beneath everything else this function costs. + /// + /// 2. **Quantum Entropy**: The sub-nanosecond component—approximately + /// 10^34 Planck times per nanosecond—cannot be measured classically. + /// It is drawn from a generator that each thread seeds once from the + /// kernel's entropy pool and that every observation stirs with the + /// nanosecond it was made in—the machine's own timing jitter under + /// load—and the result is treated as a quantum observation that + /// collapses the sub-nanosecond superposition into a definite state. + /// See `sub_ns_entropy` for what that provenance does and does not + /// claim; the short form is that it claims exactly what the kernel's + /// own generator could. + /// + /// Each call to `now()` is a new observation. Each observation is + /// unique. The universe does not repeat itself, and neither does this + /// function—and the observations nobody reads still stir the generator, + /// so that, in the sense the workspace README gives the phrase in + /// section 1.4, the unobserved states are load-bearing here too. + /// + /// ## Platform Requirements + /// + /// This function requires: + /// - Linux (for `CLOCK_TAI`) + /// - A kernel entropy pool (for `getrandom()`, which seeds each thread's + /// generator on that thread's first observation) + /// - A time daemon that has told the kernel the TAI−UTC offset: chrony + /// with a leap-second table, or ntpd with a leap file; not + /// systemd-timesyncd, which cannot + /// + /// ## Cost + /// + /// About fifty nanoseconds on the reference machine, single-threaded, in + /// release: some twenty-two for the clock, twelve for the conversion, + /// twelve for the entropy. Nothing in this function divides anything + /// wider than an `i128`, multiplies anything wider than two limbs by + /// two, or asks the kernel for entropy more than once per thread. The + /// observatory calls this from one thread per logical CPU as fast as it + /// can, and every nanosecond here is paid sixteen times over. + /// + /// # Panics + /// + /// Panics if `CLOCK_TAI` is unavailable (unlikely on any Linux of the + /// kernel generation the calendar requires), if the kernel's entropy + /// pool cannot furnish this thread's seed (extremely unlikely), or—on + /// the first observation of the process only—if the kernel confesses, + /// via `adjtimex(2)`, that its TAI offset is zero and `CLOCK_TAI` has + /// therefore been `CLOCK_REALTIME` all along. See [`kernel_tai_offset`] + /// for the interrogation and its cure, and [`TAI_HERESY`] for the sermon. + /// The calendar would rather not run than run thirty-seven seconds wrong + /// on purpose while claiming Planck precision, which the workspace + /// README, section 1.1, defines as lying. + #[cfg(target_os = "linux")] + #[must_use = "A LoicInstant constructed and discarded is a quantum observation collapsed without being read — and `now()` is the freshest such observation we offer."] + pub fn now() -> Self { + use libc::{CLOCK_TAI, clock_gettime, timespec}; + + // Phase 0: Verify, once per process, that the kernel is not lying + // about TAI. After the first call this is a single atomic load, which + // is the cheapest form of vigilance available and the only one the + // budget permits. + LazyLock::force(&KERNEL_TAI_VERIFIED); + + // Phase 1: Classical measurement via atomic time. The struct is + // zeroed so that a kernel which wrote nothing would at least have + // written nothing into a known place. + let mut ts = timespec { + tv_sec: 0, + tv_nsec: 0, + }; + + // SAFETY: clock_gettime with CLOCK_TAI is safe on Linux 3.10+. The + // timespec struct is properly initialized and the pointer is valid + // for the duration of the call, which is the only duration the + // kernel needs it for. `&raw mut ts` produces the *mut timespec + // without traversing a (briefly held) `&mut` reference — the FFI + // call only needs the address, never an aliasing-aware borrow. + let result = unsafe { clock_gettime(CLOCK_TAI, &raw mut ts) }; + + // Handle the unlikely case of CLOCK_TAI unavailability: a kernel + // that answered the question by declining it. The oracle's panic + // hook prints only this payload, so it is written to be read. + assert_eq!( + result, 0, + "CLOCK_TAI unavailable.\n\n\ + The Loic Calendar requires CLOCK_TAI, and CLOCK_TAI requires:\n\ + • a Linux kernel of 3.10 or later, and\n\ + • a time daemon maintaining the TAI-UTC offset.\n\n\ + Your system appears to be Linux and yet declined to furnish atomic\n\ + time when asked for it by name. Consider updating your kernel, your\n\ + time daemon's configuration, or your expectations of the platform." + ); + + // Nanoseconds since The Whisper, accumulated in i128. `tv_sec` is an + // i64, and its product with 10⁹ would overflow i64 in April of the + // year 2262 — a boundary that lesser timestamps have quietly accepted + // and that this calendar declines to inherit. i128 holds the full + // i64 range of seconds with sixty-four bits to spare, and the offset + // to the Whisper is added here, once, before any conversion. + let loic_ns = i128::from(ts.tv_sec) * 1_000_000_000 + + i128::from(ts.tv_nsec) + + i128::from(LOIC_TO_UNIX_OFFSET_NS); + + // Convert nanoseconds to Planck times via exact rational arithmetic, + // without a 512-bit division — see `ns_to_planck` for the identity + // that makes the division unnecessary and the proof that enforces it. + let measured_planck = ns_to_planck(loic_ns); + + // Phase 2: Quantum observation for sub-nanosecond precision — see + // `sub_ns_entropy` for the sampling discipline. The nanosecond just + // read stirs the generator: this collapse is tied to this read, and + // to the physical circumstances under which the read occurred. + let sub_ns_planck = sub_ns_entropy(stir_of(loic_ns)); + + // No bounds check: current time is approximately 10^52 Planck times + // from epoch (~53 decimal digits), well within the ~10^154 range of + // representable values, and the kernel's clock cannot reach either + // edge before the i64 seconds field runs out. The sum cannot + // overflow, and the two comparisons a check would cost are spent + // elsewhere. + Self { + planck: measured_planck + sub_ns_planck, + } + } + + /// Computes the shortened timestamp: the full Planck count divided by + /// 10²³, by one 512-bit division that truncates toward zero and keeps + /// no remainder. + /// + /// This operation produces a value suitable for use as a temporal + /// identifier—a "LOID" in the parlance of the identifier crate, which + /// is a thin wrapper around this method and `now()`. The full + /// Planck timestamp, with its ~19 deterministic digits and ~34 entropy + /// digits (totaling ~53 digits), is truncated by removing the lowest 23 + /// decimal orders of magnitude via integer division. + /// + /// The result retains approximately 11 digits of quantum entropy from + /// the original ~34, sufficient to distinguish simultaneous observations + /// while remaining compact enough for practical use as an identifier. + /// The 19 deterministic digits survive intact—they encode which + /// nanosecond you are in—and the result is still an `I512`, which is + /// still your problem. + /// + /// ## On the Ordering of Operations + /// + /// The full entropy MUST be generated first (via `now()`), and ONLY THEN + /// truncated. One does not generate 11 digits of entropy directly—one + /// generates 34 and discards 23. The distinction matters because the + /// entropy is drawn uniformly over the whole sub-nanosecond range, at a + /// fixed granularity of one Planck time, and truncating post-hoc + /// preserves the statistical properties of the original quantum + /// observation; a generator asked for eleven digits directly would be + /// answering a different question, about a coarser superposition that + /// the calendar does not recognise. + /// + /// # Panics + /// + /// Cannot panic for any valid `LoicInstant`, nor indeed for any `I512`: + /// division by a positive power of ten is the one operation in this + /// workspace that has never had an opinion. + #[must_use = "The 11-digit LOID derived from the full Planck stamp — truncation has already discarded 23 digits of entropy; please at least keep the survivors, they were chosen by the universe."] + pub fn shortened(&self) -> I512 { + self.planck / TEN_TO_23 + } + + // ╭───────────────────────────────────────────────────────────────────────╮ + // │ A C C E S S O R S │ + // │ │ + // │ Methods for interrogating an instant about its temporal coordinates, │ + // │ in various reference frames and unit systems. None of them consults │ + // │ a mask; these are the properties an instant has before any question. │ + // ╰───────────────────────────────────────────────────────────────────────╯ + + /// Retrieves the raw Planck time value—the instant's fundamental + /// representation, the integer beneath every other number this type can + /// produce. + /// + /// This is the whisper time: Planck times since the Loic epoch, negative + /// before it and positive after. The name "planck" emphasizes the unit; + /// the name "`whisper_time`" emphasizes the reference frame. They return + /// the same value, by reference, since the type is sixty-four bytes and + /// the caller may only want to look at them. + #[must_use = "The instant's raw I512 truth, returned by reference — a quantum observation collapsed without being read, which is the definition of a wasted collapse."] + pub const fn planck(&self) -> &I512 { + &self.planck + } + + /// Retrieves the whisper time: Planck times since The Whisper's epoch, + /// under the name that says what the zero is rather than what the unit + /// is. + /// + /// This is semantically identical to `planck()` but emphasizes the epoch + /// reference. Whisper time zero is The Whisper itself—the instant at + /// which "LO" reached Stanford and the receiving system stopped + /// responding, the bond established and the content lost, from which, + /// per the workspace README, section 1.3, the calendar counts. + #[must_use = "Whisper time reflects the same I512 as `planck()` under a different name — declining to read it costs you the observation, regardless of which name you used to ask."] + pub const fn whisper_time(&self) -> &I512 { + &self.planck + } + + /// Computes the cosmic time: Planck times since Creation (the Big Bang), + /// by a single wrapping subtraction whose wrapping is the whole point. + /// + /// Cosmic time measures "how old is the universe at this instant?" For + /// any instant within the valid range, this value is non-negative + /// (Creation being the earliest valid moment). At Creation itself, + /// cosmic time equals zero. For instants near The Whisper—anywhere in + /// the human-perceptible window of contemporary use—cosmic time is + /// approximately 8.08 × 10⁶⁰ Planck times: the age of the universe at + /// the moment of the first ARPANET transmission, plus or minus a few + /// decades of vanishing significance. This is the number every cosmic + /// observation divides, and the number the cycle time is reduced from. + /// + /// The computation is: `cosmic_time` = planck - `CREATION_PLANCK`. Since + /// `CREATION_PLANCK` is negative, the true difference is always + /// non-negative for any valid instant. + /// + /// # Why we return U512 + /// + /// At the upper end of the valid range—instants within roughly + /// `|CREATION_PLANCK|` Planck times of `ANNIHILATION_PLANCK` (a window + /// the width of the entire age of the universe so far, ~1.4×10¹⁰ + /// years)—the true difference `planck - CREATION_PLANCK` exceeds + /// `I512::MAX`, even though it remains comfortably within the 512-bit + /// *unsigned* range. A signed return type would force a panic across an + /// entire age-of-universe-wide slice of representable time for no + /// mathematical reason, which would be the calendar failing at exactly + /// the moment the last observers, per the workspace README, section + /// 4.7, were still around to notice. + /// + /// Returning `U512` and computing via two's-complement wrapping + /// subtraction sidesteps the problem entirely: for any pair of `I512` + /// values whose true difference fits in `[0, 2^512)`, the wrapping + /// difference of their bit patterns equals the true difference exactly, + /// which is the one genuinely beautiful property of two's complement and + /// the reason it won. `TOTAL_SPAN < 2^512` is the upper bound here, so + /// the result is always faithful regardless of the sign of `planck`, and + /// the test suite confirms it one Planck time before the Whisper, where + /// a signed difference would already have wrapped. + #[must_use = "The age of the universe at this instant, computed in U512 and dropped on the floor — the Big Bang was consulted for nothing, and it had waited a long time to be asked."] + pub fn cosmic_time(&self) -> U512 { + self.planck + .cast_unsigned() + .wrapping_sub(CREATION_PLANCK.cast_unsigned()) + } + + /// Computes the terminal time: Planck times until Annihilation, the + /// distance from this instant to the edge of the integers. + /// + /// Terminal time measures "how much representable time remains?" At + /// Annihilation (`I512::MAX` Planck times), terminal time equals zero. At + /// Creation, terminal time equals `TOTAL_SPAN`. For any instant between, + /// terminal time is positive, and the sum of terminal time and cosmic + /// time is the span itself, which the test suite checks at the epoch. + /// + /// The computation is: `terminal_time` = `ANNIHILATION_PLANCK` - planck. + /// + /// # Why we return U512 + /// + /// Same reasoning as `cosmic_time()`—and for `terminal_time()` the + /// problem is far worse with a signed return type: the difference + /// `I512::MAX - planck` overflows `I512` for *every* pre-Whisper instant + /// (i.e. any `planck < 0`), which is the whole of the valid range below + /// zero—roughly 13.8 billion years of representable history, all of + /// pre-Whisper time including the entire prior cosmos. A signed return + /// would panic on every routine query about ancient time, which is most + /// of the time there has been. + /// + /// `U512` with `wrapping_sub` returns the correct value across the whole + /// valid input domain because `TOTAL_SPAN < 2^512` and the wrapping + /// difference of the operands' bit patterns equals the true difference + /// exactly under that bound. + #[must_use = "Planck times until Annihilation, computed in U512 — the calendar told you how long is left; please do not spend it on nothing, there is less of it every observation."] + pub fn terminal_time(&self) -> U512 { + ANNIHILATION_PLANCK + .cast_unsigned() + .wrapping_sub(self.planck.cast_unsigned()) + } + + /// Computes progress through time as an exact ratio: a numerator and a + /// denominator, both integers, neither divided by the other, because + /// the only type that could hold the quotient is the one the Loic Public + /// License, Section 1, forbids. + /// + /// Returns `(cosmic_time, total_span)`—both `U512`. The ratio + /// `cosmic_time / total_span` gives the fractional progress through all + /// representable time. At Creation, this is `0 / total_span = 0`. At + /// Annihilation, it is exactly 1, the one instant at which numerator and + /// denominator coincide. At the present moment, this ratio is + /// approximately 10⁻⁹³—we are very early in the cosmic timeline, and the + /// Loic Public License, Section 10, lists contemplating this fraction + /// among the permitted uses, with the advice not to rush. + /// + /// Both values are `U512`: `total_span` is inherently unsigned and + /// exceeds `I512::MAX`, and `cosmic_time` matches it for arithmetic + /// compatibility (see `cosmic_time()` for the rationale). What the caller + /// does with a 154-digit fraction is the caller's affair; the + /// presentation layer renders it in whatever way it can bear. + #[must_use = "Cosmic progress as an exact (numerator, denominator) ratio — both U512, both expensive, both yours; please don't drop both at once, the universe is only 10⁻⁹³ of the way through."] + pub fn progress(&self) -> (U512, U512) { + (self.cosmic_time(), TOTAL_SPAN) + } + + /// Locates this instant in the 128×256 temporal grid via the parity-bit + /// method, producing a `GridCoord` that encodes which of the 32,768 + /// lattice cells the instant currently inhabits—fifteen parities, each + /// bought with two 512-bit divisions, plus one remainder to fold the + /// cosmic time into the current cycle. + /// + /// ## Method: Parity Projection + /// + /// For each of the 7 cosmic primes, the cosmic span is divided by that + /// prime to yield a "partition size." The parity of + /// `(cosmic_time / partition_size)` sets one bit of the 7-bit cosmic + /// index. Likewise for each of the 8 cycle primes against + /// `PLANCK_PER_CYCLE`, applied to the cosmic time reduced modulo the + /// cycle. The parity is read from the lowest bit of the quotient by a + /// bitwise AND, because `% 2` on a 512-bit integer is a 512-bit + /// division wearing a small number as a disguise. + /// + /// This approach is necessitated by the squarefree structure of the + /// constants: since `COSMIC_SPAN = product of all 7 cosmic primes`, + /// dividing by the full product yields 1, making naive equal-division + /// indexing degenerate. The parity projection instead tracks which half + /// of each prime's partition the instant occupies, encoding a unique + /// 7-bit identifier that evolves slowly over cosmological timescales + /// (the smallest cosmic partition is `COSMIC_SPAN / Nandyte` ≈ 2.3 × 10⁸¹ + /// Planck times ≈ 4.0 × 10³⁰ years; every instant yet observed, and + /// every instant that will be observed before the last star has been + /// dark for longer than it ever shone, occupies `cosmic_idx` = 0. Seven + /// bits of the grid are reserved for a value that will not change while + /// anyone is around to read it. We allocated them anyway. They are the + /// calendar's, not yours). At Creation every parity is even and both + /// indices are zero; at the half-cycle the Dyad bit flips, which is the + /// cheapest proof the test suite has that the cycle axis is being read. + /// + /// Cycle bits vary meaningfully over the ~894-year cycle period and are + /// the primary source of temporal variation for any observation within + /// a human lifespan: the Psi bit turns over every third of a picosecond, + /// the Dyad bit every 447 years, and the six between at every scale + /// from picoseconds to centuries. + /// + /// ## Relationship to `Mask::observe()` + /// + /// `grid_coord()` and `Mask::observe()` answer different questions + /// through different formulas, and conflating them is a category error + /// this comment exists to forestall. + /// + /// - `observe(instant)` returns the *full quotient* of `cosmic_time` + /// over a subdivision derived from the mask's active primes—a number + /// that can span the entire range up to `cosmic_divisor - 1`. + /// - `grid_coord()` returns *parity bits*: one bit per prime axis, + /// indicating which half of that prime's partition the instant + /// occupies. The result is always 0–127 (cosmic) or 0–255 (cycle), + /// regardless of how large the instant's actual cosmic time is. + /// + /// Both are valid coordinate systems on the lattice; they are not + /// interchangeable. Use `grid_coord()` when you need the discrete cell + /// address. Use `observe()` when you need the position-within-subdivision + /// for a specific mask, which is to say when you have a question rather + /// than a map. + /// + /// # Panics + /// + /// Cannot panic. The terminal `GridCoord::new` call would only fail if + /// `cosmic_idx` exceeded 127, but parity-projection over 7 cosmic primes + /// produces a 7-bit value bounded by 127 by construction; likewise the + /// cycle index is the result of OR-ing 8 single bits and therefore + /// inherently confined to `[0, 255]`—exactly the `u8` range. The + /// `expect` documents the invariant; clippy is free to remain + /// unconvinced. + #[must_use = "Thirty-one 512-bit divisions spent locating this instant in the grid, and the address thrown away — the lattice was consulted at considerable expense for nothing."] + pub fn grid_coord(&self) -> GridCoord { + // cosmic_time() returns U512 — see its docstring for why. All + // arithmetic here lives in U512 to avoid the I512::MAX boundary, and + // to keep the sign bit out of a computation that has no use for it. + let cosmic_time = self.cosmic_time(); + + let mut cosmic_idx: u8 = 0; + for (i, prime) in COSMIC_PRIMES.iter().enumerate() { + let part = COSMIC_SPAN / prime.cast_unsigned(); + let position = cosmic_time / part; + // Parity = lowest bit; bitwise AND avoids the 512-bit division + // that `% 2` would otherwise compile to, and this loop has spent + // two of those per prime already. + if position & U512_ONE == U512_ONE { + cosmic_idx |= 1u8 << i; + } + } + + let pcycle = PLANCK_PER_CYCLE.cast_unsigned(); + let cycle_time = cosmic_time % pcycle; + let mut cycle_idx: u8 = 0; + for (j, prime) in CYCLE_PRIMES.iter().enumerate() { + let part = pcycle / prime.cast_unsigned(); + let position = cycle_time / part; + if position & U512_ONE == U512_ONE { + cycle_idx |= 1u8 << j; + } + } + + GridCoord::new(cosmic_idx, cycle_idx) + .expect("parity projection yields seven bits and eight bits, never more") + } + + // ╭───────────────────────────────────────────────────────────────────────╮ + // │ A R I T H M E T I C │ + // │ │ + // │ Operations for navigating through time: adding and subtracting │ + // │ durations, computing the span between instants. Every one of them │ + // │ checks its arithmetic, because a wrapped instant is a lie with a │ + // │ unit attached, and this crate does not tell those. │ + // ╰───────────────────────────────────────────────────────────────────────╯ + + /// Adds a duration to this instant, yielding a new instant further in + /// time—or earlier, if the duration points that way—subject to the + /// same cosmological bounds as any other constructor. + /// + /// If the duration is positive, the result is in the future relative to + /// `self`. If negative, the result is in the past. The operation may fail + /// if the result would exceed Annihilation or precede Creation, and it + /// checks the raw 512-bit addition before it checks the cosmology, so + /// that no intermediate can wrap on its way to being rejected. + /// + /// # Errors + /// + /// Returns `LoicError::Overflow` or `LoicError::Underflow` if the result + /// is outside the representable range + /// [`CREATION_PLANCK`, `ANNIHILATION_PLANCK`]—or, in the case that the + /// raw sum outgrows the `I512` entirely, the same error with a message + /// that says so, chosen by the sign of the duration: a positive duration + /// that overflows was headed for Annihilation, a negative one for + /// Creation, and the error names the edge it was headed for. + pub fn add_duration(&self, duration: &LoicDuration) -> LoicResult { + // checked_add catches the case where the raw I512 sum overflows the + // 512-bit range entirely — `from_planck()`'s bounds check operates on + // a finite I512 and would never run if the addition itself panicked, + // or would run on a wrapped value if it wrapped, which is worse. + // Translate the overflow into the canonical Overflow/Underflow error + // according to which direction the duration was pointing. + let sum = self.planck.checked_add(*duration.planck()).ok_or_else(|| { + if duration.planck() > &I512_ZERO { + LoicError::Overflow(format!( + "{} + {} exceeds I512", + self.planck, + duration.planck() + )) + } else { + LoicError::Underflow(format!( + "{} + {} underflows I512", + self.planck, + duration.planck() + )) + } + })?; + Self::from_planck(sum) + } + + /// Subtracts a duration from this instant, yielding a new instant + /// earlier in time—or later, if the duration was negative—under the + /// same bounds and the same checks as addition. + /// + /// This is equivalent to `add_duration(-duration)` but avoids the + /// negation, which matters for exactly one duration: `I512::MIN` has no + /// negation in two's complement, and subtracting it directly is the only + /// way to add its magnitude without first asking for a number that does + /// not exist. If the duration is positive, the result is in the past + /// relative to `self`. + /// + /// # Errors + /// + /// Returns `LoicError::Overflow` or `LoicError::Underflow` if the result + /// is outside the representable range, or if the raw 512-bit difference + /// outgrows the word before the range can be consulted; a positive + /// duration that overflows was headed for Creation, a negative one for + /// Annihilation, and the error names the edge. + pub fn sub_duration(&self, duration: &LoicDuration) -> LoicResult { + // checked_sub for the same reason as add_duration's checked_add: + // intercept I512 overflow before it becomes a panic or, worse, a + // silently wrapped coordinate wearing a valid instant's type. + let diff = self.planck.checked_sub(*duration.planck()).ok_or_else(|| { + if duration.planck() > &I512_ZERO { + LoicError::Underflow(format!( + "{} - {} underflows I512", + self.planck, + duration.planck() + )) + } else { + LoicError::Overflow(format!( + "{} - {} exceeds I512", + self.planck, + duration.planck() + )) + } + })?; + Self::from_planck(diff) + } + + /// Computes the signed duration from another instant to this one: the + /// vector that, added to `other`, arrives at `self`. + /// + /// Returns `self - other` as a `LoicDuration`. Positive if `self` is + /// after `other`, negative otherwise, zero if they are the same instant, + /// and exact to the Planck time in every case, since two integers were + /// subtracted and nothing else happened. + /// + /// # Panics + /// + /// Panics if the true difference exceeds the `I512` range. Since two + /// valid instants span `[CREATION, ANNIHILATION]` and the duration's + /// internal representation is `I512`, any pair whose absolute spread + /// exceeds `I512::MAX` is unrepresentable—the span between Creation and + /// Annihilation is one age of the universe wider than a signed word. The + /// unrepresentable region begins at pairs separated by more than + /// ~`I512::MAX` Planck times—which requires one operand near `CREATION` + /// and the other near `ANNIHILATION`. In practice no realistic pair of + /// observations will reach this; differences within the + /// cosmic-time-of-now scale (10⁶⁰ Planck times) are 93 orders of + /// magnitude clear, and the Loic Public License, Section 11, has in any + /// case declined to warrant the far operand's existence. + /// + /// Detection is by `checked_sub`. The raw subtraction would wrap + /// silently in release builds, and a duration that is wrong by 2⁵¹² + /// Planck times is not a duration. It is a lie with a unit attached, and + /// the calendar would sooner stop than tell one. + #[must_use = "The signed duration between two instants — a vector pointing from one moment to another; throwing it away leaves both moments unconnected, which is the opposite of what a calendar is for."] + pub fn difference(&self, other: &Self) -> LoicDuration { + let diff = self.planck.checked_sub(other.planck).expect( + "LoicInstant::difference overflow: the spread between these instants \ + exceeds what a signed 512-bit integer can express. One operand lies \ + near CREATION and the other near ANNIHILATION, and the span between \ + them is one age of the universe wider than a signed word. Durations \ + are I512 by the calendar's design; this difference is not one, and \ + the calendar declines to return a wrapped number in its place.", + ); + LoicDuration::from_planck(diff) + } +} + +/// Debug formatting: reveals the raw Planck value and the shortened +/// timestamp, both as decimal strings, furnishing developers with the +/// full-precision truth and its abbreviated alias side by side, so that a +/// glance at a debugger shows both the nanosecond and the entropy beneath +/// it. +impl fmt::Debug for LoicInstant { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("LoicInstant") + .field("planck", &self.planck.to_string()) + .field("shortened", &self.shortened().to_string()) + .finish() + } +} + +/// Display formatting: renders the instant as its raw Planck time value, a +/// decimal integer of up to a hundred and fifty-four digits with no unit, +/// no separator, and no apology. +/// +/// The lattice framework delegates all human-readable formatting to the +/// presentation layer (the oracle, the observatory). The core library +/// traffics only in integers—the unvarnished Planck count, free of +/// calendrical interpretation—and this impl is the same integer `FromStr` +/// reads back, so that an instant printed and parsed is the instant. +impl fmt::Display for LoicInstant { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.planck) + } +} + +/// Partial ordering: delegates to the total ordering since all instants are +/// comparable. Time is linear (in our representation); every instant has a +/// definite relationship to every other instant, which the workspace README, +/// section 1.3, would qualify with a remark about reference frames, and +/// which the calendar, having chosen the atom's frame, does not. +impl PartialOrd for LoicInstant { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +/// Total ordering: earlier instants are less than later instants. This is +/// the natural ordering of time, from Creation toward Annihilation, and it +/// is the ordering of the underlying integers and nothing more subtle: the +/// arrow of entropy, which the Loic Public License, Section 11, declines to +/// warrant, is warranted here at least as far as the comparison goes. +impl Ord for LoicInstant { + fn cmp(&self, other: &Self) -> Ordering { + self.planck.cmp(&other.planck) + } +} + +/// Adding a duration to an instant: temporal navigation into the future (or +/// past, if the duration is negative), with the `+` operator. +/// +/// The result is `LoicResult` because the operation may push the instant +/// outside the representable range, triggering Overflow or Underflow errors, +/// and an operator that could fail and pretended otherwise would be +/// floating-point's kind of operator. It delegates to `add_duration`. +impl Add for LoicInstant { + type Output = LoicResult; + fn add(self, rhs: LoicDuration) -> Self::Output { + self.add_duration(&rhs) + } +} + +/// Subtracting a duration from an instant: temporal navigation into the +/// past (or future, if the duration is negative), with the `-` operator. +/// +/// Semantically equivalent to adding the negated duration; provided for +/// syntactic convenience, and implemented without the negation, by +/// delegation to `sub_duration`. The result is a `LoicResult` for the same +/// reason addition's is. +impl Sub for LoicInstant { + type Output = LoicResult; + fn sub(self, rhs: LoicDuration) -> Self::Output { + self.sub_duration(&rhs) + } +} + +/// Subtracting one instant from another: computing the signed duration +/// between them, with the `-` operator, by delegation to `difference`. +/// +/// Panics if the spread exceeds `I512::MAX`. See `difference()` for the +/// full reasoning—practical consequence: never panics for any pair of +/// instants inside a cosmologically reasonable window, where "reasonable" +/// extends to within an age of the universe of either edge of time. +impl Sub for LoicInstant { + type Output = LoicDuration; + fn sub(self, rhs: LoicInstant) -> Self::Output { + self.difference(&rhs) + } +} + +/// Serde serialization: encodes the instant as its Planck time string +/// representation, and only that. +/// +/// The Planck time is serialized as a decimal string to preserve all 512 +/// bits of precision. JSON numbers (IEEE 754 doubles) would lose precision +/// catastrophically—fifty-three bits of mantissa against five hundred and +/// twelve of integer, an insult the Loic Public License, Section 2, +/// condemns by name—and strings are exact. A serializer that cannot carry +/// a string is a serializer this calendar has no business with. +#[cfg(feature = "serde")] +impl Serialize for LoicInstant { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(&self.planck.to_string()) + } +} + +/// Serde deserialization: decodes a Planck time string into an instant, +/// through the same bounds check every other constructor applies. +/// +/// Expects a decimal string representation of a 512-bit signed integer. +/// Applies bounds checking to ensure the value falls within +/// `[CREATION, ANNIHILATION]`, and reports both a malformed string and an +/// out-of-range coordinate as a deserialization error, since neither is an +/// instant and the deserializer was asked for one. +#[cfg(feature = "serde")] +impl<'de> Deserialize<'de> for LoicInstant { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + let planck = I512::from_str(&s).map_err(serde::de::Error::custom)?; + Self::from_planck(planck).map_err(serde::de::Error::custom) + } +} + +/// Parses an instant from its decimal Planck-time string representation: +/// an optional minus sign, then digits, then the bounds check. +/// +/// The calendar eschews calendrical format parsing—that baroque machinery of +/// month names and colon-delimited time components belongs to other +/// calendars, and to the presentation layer of this one should it ever +/// develop the urge. The core library accepts only the raw truth: a decimal +/// integer representing Planck times since the Loic epoch. A string that is +/// not that yields `LoicError::ParseError`, and a string that is that but +/// names a moment outside representable time yields the corresponding +/// Underflow or Overflow, exactly as `from_planck` would. +/// +/// # Examples +/// +/// ``` +/// use std::str::FromStr; +/// use loic::LoicInstant; +/// let instant = LoicInstant::from_str("0").unwrap(); // the epoch +/// ``` +impl FromStr for LoicInstant { + type Err = LoicError; + + fn from_str(s: &str) -> Result { + let planck = I512::from_str(s).map_err(|_| { + LoicError::ParseError(format!( + "Invalid Planck time: '{s}'. Expected a decimal integer." + )) + })?; + Self::from_planck(planck) + } +} + +// ╔═══════════════════════════════════════════════════════════════════════════╗ +// ║ PUBLIC COSMOLOGICAL CONSTANTS ║ +// ║ ║ +// ║ Accessor Functions for the Bounds of Time ║ +// ║ ║ +// ║ These functions expose the computed cosmological constants to library ║ +// ║ users who wish to interrogate the fundamental limits of the Loic ║ +// ║ Calendar's temporal domain. Each returns a reference into the binary's ║ +// ║ read-only data, where the compiler left the number before the process ║ +// ║ began; nothing is computed, and nothing can be changed. ║ +// ╚═══════════════════════════════════════════════════════════════════════════╝ + +/// Retrieves `CREATION_PLANCK`: the earliest representable moment (the Big +/// Bang), as a reference to the sixty-four bytes the compiler folded it +/// into. +/// +/// This is the lower bound of valid Planck times, approximately +/// -8.08 × 10⁶⁰: the age of the universe of the workspace README, section +/// 2.1, converted to Planck times and pointed backward from the Whisper. +/// Instants before this value trigger `LoicError::Underflow`, for time +/// itself did not exist before Creation—at least, not in any form our +/// physics can describe, and the calendar declines to describe what +/// physics cannot. +#[must_use = "The earliest representable moment, returned by reference — to fetch the Big Bang's coordinate and discard it is a particular kind of arrogance, and not the interesting kind."] +pub const fn creation_planck() -> &'static I512 { + &CREATION_PLANCK +} + +/// Retrieves `ANNIHILATION_PLANCK`: the latest representable moment +/// (2⁵¹¹ - 1), by reference, from wherever the linker put it. +/// +/// This is the upper bound of valid Planck times, equal to `I512::MAX`. +/// Instants beyond this value would overflow our signed 512-bit +/// representation. In physical terms, this corresponds to roughly +/// 1.1 × 10¹⁰³ years from the epoch—long after the heat death of the +/// universe, after proton decay is a distant memory, after the last white +/// dwarf has evaporated, and some three orders of magnitude after the last +/// black hole has finished doing the same, which per the workspace README, +/// section 4.7, makes it three orders of magnitude after the last +/// observation there will be. The test suite confirms that this accessor +/// returns `I512::MAX`, which is the one fact about the end of time the +/// calendar can check. +#[must_use = "The latest representable moment, returned by reference — fetching the heat-death coordinate and discarding it does not delay the heat death; it merely wastes the static reference."] +pub const fn annihilation_planck() -> &'static I512 { + &ANNIHILATION_PLANCK +} + +/// Retrieves `TOTAL_SPAN`: the full range from Creation to Annihilation, +/// by reference, in the one width that holds it. +/// +/// This is `ANNIHILATION_PLANCK` - `CREATION_PLANCK`, stored as a `U512` +/// because the difference exceeds `I512::MAX` by exactly the age of the +/// universe. This value serves as the denominator for progress +/// calculations: progress = `cosmic_time` / `total_span`. It is also, to +/// the digit, the Cosmic Span whose seven prime factors generate Channel 2, +/// and the compiler has refused to build any binary in which the two +/// disagree. +/// +/// The total span is a number of a hundred and fifty-four digits, +/// approximately 6.7 × 10¹⁵³ Planck times, a number so large that even +/// attempting to contemplate it invites madness, which the Loic Public +/// License, Section 10, nonetheless lists among the permitted uses. +#[must_use = "The full Creation-to-Annihilation span, returned by reference — to summon a 154-digit number and walk away from it is to inflict madness on no one, which was not the arrangement."] +pub const fn total_span() -> &'static U512 { + &TOTAL_SPAN +} + +// ╔═══════════════════════════════════════════════════════════════════════════╗ +// ║ THE HOT PATH ║ +// ║ ║ +// ║ A handful of private functions. `now()` calls the first few of them ║ +// ║ tens of millions of times a second across the observatory's threads, ║ +// ║ and none divides anything wider than a primitive integer. This is not ║ +// ║ an accident. It is the budget: fifty nanoseconds, of which the kernel ║ +// ║ takes twenty-two before the calendar has done anything at all. ║ +// ╚═══════════════════════════════════════════════════════════════════════════╝ + +/// Converts a signed count of nanoseconds since The Whisper into Planck +/// times, exactly, without dividing anything wider than an `i128` or +/// multiplying anything wider than two limbs by two—the arithmetic that +/// makes the hot path affordable, written out by hand so that it can be +/// read. +/// +/// The rational conversion is `ns × 10⁴¹ / 5,391,247`. Write 10⁴¹ as +/// `q × 5,391,247 + r`, with `q` = [`SUB_NS_RANGE`] (whole Planck times per +/// nanosecond) and `r` = [`PLANCK_PER_NS_REMAINDER`]. Then +/// +/// ```text +/// ⌊ns × 10⁴¹ / 5,391,247⌋ = ns × q + ⌊ns × r / 5,391,247⌋ +/// ``` +/// +/// because `ns × q` is already an integer and the leftover fraction has +/// magnitude strictly below one, so it cannot carry into the whole part +/// and cannot be lost from it. The first term is the product of the +/// magnitude of `ns`, at most two 64-bit limbs, by `q`, exactly two +/// ([`SUB_NS_RANGE_U128`]), written out as schoolbook multiplication into +/// four of an `I512`'s eight limbs with the sign restored afterwards; a +/// general 512-by-512 multiply would perform sixty-four limb products to +/// reach the same four, sixty of them multiplying zeros. The second term +/// lives entirely inside `i128`: `|ns × r| < 2¹¹⁶` for any `tv_sec` an +/// `i64` can express, since `|ns| < 2⁹⁴` and `r < 2²³`, and the division +/// is a primitive one, which the processor performs in a handful of cycles +/// rather than the hundred-odd nanoseconds a 512-bit divider would take. +/// Truncation toward zero in both terms agrees with truncation of the whole +/// for either sign of `ns`, which `test_ns_conversion_matches_reference` +/// checks against the direct formula across the sign boundary, the current +/// epoch, and the ends of the `i64` range, and along a geometric sweep of +/// twenty-odd orders of magnitude in both directions. The identity itself +/// is enforced at compile time by [`_NS_RATIO_IS_EXACT`], and the limb count +/// by [`_SUB_NS_RANGE_FITS_U128`]; neither can be violated in a binary that +/// exists. +/// +/// On the reference machine this costs about twelve nanoseconds, against +/// thirty-seven for the general multiply it declines to perform. The +/// observatory, which asks tens of millions of times a second from every +/// logical CPU it can find, notices the difference as a matter of +/// observations per second and of package power. +#[inline] +#[allow( + clippy::cast_possible_truncation, + reason = "each cast keeps the low limb, the carry the high; the truncation is the arithmetic" +)] +fn ns_to_planck(ns: i128) -> I512 { + let a = ns.unsigned_abs(); + let a = [a as u64, (a >> 64) as u64]; + let b = [SUB_NS_RANGE_U128 as u64, (SUB_NS_RANGE_U128 >> 64) as u64]; + let mut limbs = [0u64; 8]; + for (i, &ai) in a.iter().enumerate() { + let mut carry = 0u128; + for (j, &bj) in b.iter().enumerate() { + let t = u128::from(limbs[i + j]) + u128::from(ai) * u128::from(bj) + carry; + limbs[i + j] = t as u64; + carry = t >> 64; + } + limbs[i + 2] = carry as u64; + } + let whole = i512_from_limbs(limbs); + let whole = if ns < 0 { -whole } else { whole }; + let residue = (ns * i128::from(PLANCK_PER_NS_REMAINDER)) / i128::from(PLANCK_TIME_NUMERATOR); + whole + residue.as_::() +} + +/// Assembles eight little-endian 64-bit limbs into a non-negative `I512`, +/// by laying them end to end as sixty-four bytes and reinterpreting the +/// result as signed. The top bit of the top limb must be clear, which every +/// caller's arithmetic guarantees by construction, since none of them +/// multiplies anything near 2⁵¹¹: the largest product the hot path forms is +/// two limbs by two, which fills four and leaves the upper four, and the +/// sign bit with them, at zero. +#[inline] +fn i512_from_limbs(limbs: [u64; 8]) -> I512 { + let mut bytes = [0u8; 64]; + for (chunk, limb) in bytes.chunks_exact_mut(8).zip(limbs.iter()) { + chunk.copy_from_slice(&limb.to_le_bytes()); + } + U512::from_le_bytes(bytes).cast_signed() +} + +/// Selects the word a nanosecond count stirs the entropy generator with: its +/// low 64 bits, sign bits and all, taken as a bit pattern rather than a +/// number. The high bits are the date, which does not jitter; the low ones, +/// under load, are set by cache misses, interrupt arrival, the boost clock's +/// thermal transitions and the oscillator's phase noise, and that is what is +/// wanted—the machine's own trembling, folded into the state that will +/// decide the next collapse. `const`, because taking the low word of an +/// integer is a thing the compiler may do whenever it likes. +#[inline] +#[allow( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "the stir wants exactly the low 64 bits, sign and all; truncation is the selection" +)] +const fn stir_of(ns: i128) -> u64 { + ns as u64 +} + +thread_local! { + /// This thread's entropy generator: the four words of xoshiro256++, all + /// zero until the thread's first observation seeds them from the + /// kernel's pool, and thereafter stirred by every observation the thread + /// makes, read or unread. One generator per thread, so that sixteen + /// observers spinning on sixteen logical CPUs never contend for a lock + /// or share a cache line; a `Cell`, because the thread that owns it is + /// the only thread that will ever touch it, and a `Cell` costs nothing + /// to prove that. + static SUB_NS_GENERATOR: Cell<[u64; 4]> = const { Cell::new([0; 4]) }; +} + +/// Draws four words from the kernel's entropy pool, for a thread that is +/// about to observe for the first time—the one `getrandom` call in a +/// thread's life, after which the generator expands the seed itself. The +/// all-zero state is the one state the generator cannot leave, since every +/// operation in it maps zero to zero, so it is the one seed that is drawn +/// again; the odds of drawing it are one in 2²⁵⁶, and the loop is there for +/// the principle rather than the probability. +/// +/// # Panics +/// +/// Panics if the kernel's entropy pool is unavailable, which `getrandom` +/// reports as a hard failure and this crate treats as one; and, with the +/// same message a mathematician would use for a contradiction, if +/// `chunks_exact(8)` ever yields a chunk of any length but eight, which it +/// cannot. +fn seed_from_kernel() -> [u64; 4] { + loop { + let mut bytes = [0u8; 32]; + getrandom::fill(&mut bytes) + .expect("Quantum observation failed: the kernel's entropy pool would not seed it"); + let mut state = [0u64; 4]; + for (word, chunk) in state.iter_mut().zip(bytes.chunks_exact(8)) { + *word = u64::from_le_bytes(chunk.try_into().expect("a chunk of exactly eight bytes")); + } + if state != [0; 4] { + return state; + } + } +} + +/// Performs one step of xoshiro256++ (Blackman and Vigna, 2018): the next 64 +/// bits, and the state advanced. Ten lines of rotations, shifts and +/// exclusive-ors, written here rather than imported, because ten lines do +/// not justify a dependency and this crate keeps its arithmetic where it can +/// be read. The output is the scrambled sum of the first and last words; the +/// state update is a linear map over the two-element field, which is what +/// makes the all-zero state a fixed point and the seed loop above +/// necessary. Two steps furnish the 128 bits each observation draws. +#[inline] +fn xoshiro_next(s: &mut [u64; 4]) -> u64 { + let result = s[0].wrapping_add(s[3]).rotate_left(23).wrapping_add(s[0]); + let t = s[1] << 17; + s[2] ^= s[0]; + s[3] ^= s[1]; + s[1] ^= s[2]; + s[0] ^= s[3]; + s[2] ^= t; + s[3] = s[3].rotate_left(45); + result +} + +/// Draws the sub-nanosecond Planck offset, uniformly on `[0, SUB_NS_RANGE)`, +/// by rejection sampling on 114 bits from this thread's generator—the +/// collapse, in the vocabulary of the workspace README, section 5.1, of the +/// roughly 10³⁴ Planck-scale coordinates inside one nanosecond into the one +/// coordinate this observation occupies. +/// +/// The generator's state begins as four words drawn from the kernel's +/// entropy pool the first time the thread observes, and every observation +/// stirs one word with `stir`—the low 64 bits of the nanosecond the clock +/// reported, whose lowest bits under load are set by cache misses, +/// interrupt arrival, the boost clock's thermal transitions and the +/// oscillator's phase noise—so that the state absorbs the machine's own +/// trembling as it goes, including from the observations nobody reads. The +/// observatory's observer threads discard every instant they make; their +/// generators remember every one. +/// +/// What this claims about provenance is exactly what the kernel's own +/// generator could claim: the bits are the deterministic expansion of a +/// seed that bottoms out in physical noise, with more physical noise folded +/// in along the way. It is not provably quantum. It is not disprovably +/// quantum either, which is the standard the workspace README holds itself +/// to (section 0), and the stirring ties each collapse to the physical +/// circumstances of the read that caused it, which is what section 1.3 says +/// an observation is: an interaction, not a lookup. +/// +/// [`SUB_NS_RANGE`] ≈ 1.855 × 10³⁴ lies between 2¹¹³ and 2¹¹⁴. Two words of +/// the generator furnish 128 bits; the top fourteen are masked off, leaving +/// a uniform draw on `[0, 2¹¹⁴)`, of which the range accepts 89.3%. A +/// rejected draw is simply drawn again—1.12 draws per observation on +/// average—and no modulo reduction is ever performed, so there is no modulo +/// bias to correct and no 512-bit division on the hottest path in the +/// crate. Uniformity here is not approximated. It is the acceptance +/// criterion, and `test_sub_ns_entropy_is_uniform` measures it, a hundred +/// thousand draws into sixteen buckets, while +/// `test_sub_ns_entropy_is_in_range` confirms that no draw ever escapes the +/// nanosecond. +/// +/// Each accepted candidate is one collapse of the ~10³⁴-way superposition +/// inside a single nanosecond. The rejected ones are not observations. They +/// are the universe declining to answer a question that was slightly too +/// wide, and being asked again more carefully. +/// +/// On the reference machine this costs about a dozen nanoseconds, most of +/// it the thread-local access. A keyed stream cipher in its place—the +/// respectable alternative, and a cryptographic one—costs forty-six on the +/// same machine, and cryptographic strength is not a property a +/// sub-nanosecond coordinate has any use for: nobody is attacking the +/// thirty-fourth digit of the time. +/// +/// # Panics +/// +/// Panics if the kernel's entropy pool is unavailable when a thread first +/// needs its seed—a condition `getrandom` reports as a hard failure, and one +/// under which the calendar is the least of the machine's problems. After +/// the seed, this function cannot panic; there is nothing left in it that +/// can fail. +#[inline] +fn sub_ns_entropy(stir: u64) -> I512 { + SUB_NS_GENERATOR.with(|cell| { + let mut state = cell.get(); + if state == [0; 4] { + state = seed_from_kernel(); + } + state[1] ^= stir; + let candidate = loop { + // 128 bits drawn, 114 kept: the top fourteen bits of the high + // word would carry the candidate past 2^114, where nothing is + // accepted, so they are masked off before the comparison rather + // than rejected by it, which would cost some eighteen thousand + // draws per acceptance instead of one and a bit. + let high = xoshiro_next(&mut state) & ((1u64 << 50) - 1); + let low = xoshiro_next(&mut state); + let candidate = (u128::from(high) << 64) | u128::from(low); + if candidate < SUB_NS_RANGE_U128 { + break candidate; + } + // Otherwise the candidate lies in [SUB_NS_RANGE, 2^114); resample. + // No reduction, no bias: the question is asked again, not + // answered approximately. + }; + cell.set(state); + candidate.as_::() + }) +} + +/// Converts a signed count of seconds into the smallest whole number of +/// Planck times that is *not shorter* than it—the ceiling of the exact +/// rational, taken by magnitude and signed afterwards. +/// +/// One second is not a whole number of Planck times; it is 10⁵⁰ / 5,391,247 +/// of them, and that ratio has a fractional part, as any ratio of a power +/// of ten to a number that is not two or five or their product must. Any +/// integer representation of "one second" is therefore either a fraction +/// of a Planck time short or a fraction of a Planck time long, and the +/// calendar must choose. It chooses long. The alternative—the floor—would +/// make `seconds(1)` one Planck time shy of a second, and +/// `as_whole_seconds`, truncating toward zero on the way back, would report +/// it as zero seconds: a result that would be correct, documented, and +/// absurd. A duration of one second contains one second. It is not +/// permitted to be one Planck time short of itself, and the Loic Public +/// License, Section 1, would regard a second that was as a lie of exactly +/// the kind it forbids. +/// +/// The count is multiplied by 10⁵⁰ first, then divided by 5,391,247 with +/// the ceiling, so the result overshoots the true duration by strictly less +/// than one Planck time—no matter how large the count—and +/// `as_whole_seconds` recovers exactly `n` for every `n`. +/// `test_duration_constructors_round_trip` checks the round trip for +/// counts from one second to `i64::MAX`, and checks the overshoot directly: +/// `planck × 5,391,247 − n × 10⁵⁰` lies in `[0, 5,391,247)`, which is the +/// ceiling stated as an inequality. The sign is handled by magnitude, so +/// that `seconds(−n)` is the exact negation of `seconds(n)` and a duration +/// pointed at the past is as long as the same duration pointed at the +/// future, which one would have hoped went without saying. +/// +/// The argument is `i128` so that `days`, `hours`, and `minutes` may +/// multiply their `i64` counts up to seconds without the intermediate +/// overflow that an `i64` product would hit at around 2.56 × 10¹⁵ hours; the +/// scaled magnitude, at most some 10⁸⁸, then fits an `I512` with sixty-five +/// digits to spare. This is not a hot path—no observer calls it—and it +/// spends a 512-bit multiply and a 512-bit division without apology. +fn seconds_to_planck(seconds: i128) -> I512 { + let scaled = seconds.unsigned_abs().as_::() * PLANCK_DENOMINATOR; + let quotient = scaled / PLANCK_NUMERATOR_I512; + // A multiplication and a subtraction recover the remainder more cheaply + // than a second 512-bit division would: the division is the expensive + // operation, and it has already been paid for once. + let remainder = scaled - quotient * PLANCK_NUMERATOR_I512; + let magnitude = if remainder == I512_ZERO { + quotient + } else { + quotient + I512_ONE + }; + if seconds < 0 { -magnitude } else { magnitude } +} + +// ╔═══════════════════════════════════════════════════════════════════════════╗ +// ║ KERNEL INTERROGATION ║ +// ║ ║ +// ║ The one question the calendar asks the kernel before it will ask it ║ +// ║ anything else: whether the clock it is about to read is the clock it ║ +// ║ claims to be. A kernel that answers zero is refused, in full, once. ║ +// ╚═══════════════════════════════════════════════════════════════════════════╝ + +/// Interrogates the kernel for its notion of the TAI−UTC offset, in seconds: +/// the number of leap seconds it believes have accumulated, and therefore +/// the number by which `CLOCK_TAI` differs from `CLOCK_REALTIME`—the lie +/// detector, applied to the one witness whose testimony the whole calendar +/// rests on. +/// +/// The kernel does not learn this number by itself. It is set, through +/// `adjtimex(2)`, by a time daemon that has read a leap-second table—chrony +/// with a `leapseclist` or `leapsectz` directive, ntpd with a `leapfile`—and +/// a machine whose daemon does neither reports zero here, at which point +/// `CLOCK_TAI` is `CLOCK_REALTIME` wearing a name tag. NTP packets do not +/// carry this value. They never have. A machine can be perfectly +/// synchronized to the nanosecond and still not know what TAI is, and most +/// of them are and do not; systemd-timesyncd, being an SNTP client, cannot +/// set it at all. The true value is thirty-seven—the ten UTC began with and +/// the twenty-seven leap seconds inserted since—and, per section 1.2 of the +/// workspace README, it may remain thirty-seven for the rest of the +/// calendar's life, or shift by one in either direction with consequences +/// for the epoch's factorization that the README declines to interpret. +/// +/// # Returns +/// +/// The kernel's `tai` field, in seconds, as the kernel holds it: zero on a +/// machine that has never been told, and whatever it was told otherwise. +/// The test suite requires only that the answer is not negative, since a +/// negative leap-second count would be news; whether it is honest is a +/// property of the machine, not of the crate. +/// +/// # Panics +/// +/// Panics if `adjtimex(2)` itself fails—which on Linux requires the syscall +/// to be absent, or the process to be sandboxed away from it—a machine on +/// which the calendar has larger disagreements to settle first, and says so. +#[must_use = "The kernel's leap-second count, retrieved and ignored — you asked how much it is lying by; at least read the answer, since the kernel troubled to give one."] +pub fn kernel_tai_offset() -> i32 { + // SAFETY: `timex` is plain old data with no invariants beyond "the bytes + // are a timex", which all-zero bytes satisfy. With `modes == 0` the + // call is the documented read-only form of adjtimex: the kernel fills the + // struct and modifies nothing — the calendar asks what the offset is and + // is careful never to be in a position to set it. `&raw mut` yields the + // pointer the FFI needs without constructing an aliasing-relevant + // reference. + let mut tx: libc::timex = unsafe { std::mem::zeroed() }; + let rc = unsafe { libc::adjtimex(&raw mut tx) }; + assert!( + rc >= 0, + "adjtimex(2) failed: the kernel declined to discuss the time at all, which is \ + a different refusal from lying about it and a rarer one. The Loic Calendar \ + cannot verify CLOCK_TAI on a system that will not answer questions about it, \ + and will not observe through a clock it cannot verify." + ); + tx.tai +} + +/// The sermon delivered to a kernel whose TAI offset is zero: the text of +/// the panic raised by the first observation of such a process, published +/// so that every front-end obliged to repeat it—the oracle on its standard +/// error, the observatory on its one and only frame—repeats it verbatim, +/// from this single source, with no opportunity to drift, in the way that a +/// liturgy is kept from drifting by being written down exactly once. +/// +/// It is addressed to whoever administers the machine, names the two daemons +/// that can effect the cure and the one that cannot, states the size of the +/// lie it declines to tell—thirty-seven seconds, the ten and the +/// twenty-seven—and cites the Loic Public License, Section 4, which is where +/// the position it takes was taken. It contains no formatting directives and +/// no runtime values; a kernel that does not know what TAI is has nothing +/// to contribute to it, and the text is a `const` rather than a function +/// because there is nothing for a function to compute. The oracle's panic +/// hook prints only the payload, so this reads as a sermon and not as a +/// stack trace, which is the intended register. +pub const TAI_HERESY: &str = "PLATFORM HERESY\n\n\ + Your kernel reports a TAI offset of 0.\n\ + CLOCK_TAI is therefore CLOCK_REALTIME wearing a name tag, and every\n\ + observation this calendar made would be wrong by thirty-seven seconds\n\ + — the ten UTC began with and every leap second since — while claiming\n\ + Planck precision. That is not imprecision. That is lying.\n\n\ + Nothing sets this offset by itself. Your time daemon must read a\n\ + leap-second table and tell the kernel:\n\ + \x20 • chrony: add `leapseclist /usr/share/zoneinfo/leap-seconds.list`\n\ + \x20 or `leapsectz right/UTC` to chrony.conf\n\ + \x20 • ntpd: add `leapfile /usr/share/zoneinfo/leap-seconds.list`\n\ + \x20 • systemd-timesyncd cannot. It is an SNTP client. It has never\n\ + \x20 heard of TAI and it is not going to start now.\n\n\ + Per the Loic Public License, Section 4: TAI is correct. Everything\n\ + else is a negotiation, and this one has not taken place."; + +/// One-shot verification, forced on the first observation of the process, +/// that the kernel's TAI offset is nonzero—that `CLOCK_TAI` is, in fact, +/// TAI, and not `CLOCK_REALTIME` answering to a name it has not earned. +/// +/// The check is a `LazyLock<()>`: the first call to `now()` pays for one +/// syscall, every subsequent call for one atomic load, which at about fifty +/// nanoseconds per observation is the only price the hot path could afford +/// for it. The calendar could re-interrogate the kernel on every +/// observation, but a kernel that knew the offset a nanosecond ago has not +/// forgotten it since, and the hot path is budgeted too tightly to spend a +/// syscall on paranoia. This is the one `LazyLock` in the crate, reserved, +/// as the crate reserves it, for a fact only the runtime can know; every +/// other constant was settled by the compiler. +/// +/// # Panics +/// +/// Panics, in the license's own voice, if the offset is zero: the message is +/// [`TAI_HERESY`], and it names the cure. The calendar would rather not run +/// at all than run thirty-seven seconds wrong while claiming Planck +/// precision, which is the one form of lying section 1.1 of the workspace +/// README defines—an approximation delivered with the confidence of an +/// exact value—and this crate is otherwise at pains to avoid. The sermon is +/// preached once per process, to whichever thread observes first; a process +/// that survives it and observes again, from any thread, is refused with +/// the standard library's notice that the verification was poisoned, which +/// is accurate, if less eloquent, and is why the observatory asks +/// `kernel_tai_offset` itself before it spawns a single observer. +static KERNEL_TAI_VERIFIED: LazyLock<()> = LazyLock::new(|| { + let tai = kernel_tai_offset(); + assert!(tai != 0, "{TAI_HERESY}"); +}); + +// ╔═══════════════════════════════════════════════════════════════════════════╗ +// ║ TESTS ║ +// ║ ║ +// ║ The Empirical Verification of Temporal Truth ║ +// ║ ║ +// ║ These tests ensure that the lattice types, instant arithmetic, and ║ +// ║ cosmological bounds behave as the calendar's covenant with itself ║ +// ║ demands. Each failure is a breach of that covenant; each pass is the ║ +// ║ runtime confirming, out of politeness, what the compiler already knew. ║ +// ╚═══════════════════════════════════════════════════════════════════════════╝ + +#[cfg(test)] +mod tests { + use super::*; + + /// A mask's label lists its active primes cosmic-first, each channel in + /// prime order, joined by ×; the empty mask is the Whisper; the full + /// mask has fourteen joins, one fewer than its primes. Every prime bit + /// names exactly one prime, and the four corners of the bit range are + /// checked by name so that a table shifted by one would be caught at + /// both ends. + #[test] + fn mask_labels_join_prime_names_in_bit_order() { + assert_eq!(Mask::whisper().label(), "Whisper"); + assert_eq!(Mask::new(0b1).unwrap().label(), "Andyte"); + let mixed = Mask::new((1 << 9) | (1 << 7) | 0b100).unwrap(); + assert_eq!(mixed.label(), "Oryte × Dyad × Heptad"); + assert_eq!(Mask::full().label().matches(" × ").count(), 14); + assert_eq!(prime_name(0), "Andyte"); + assert_eq!(prime_name(6), "Nandyte"); + assert_eq!(prime_name(7), "Dyad"); + assert_eq!(prime_name(14), "Psi"); + } + + /// The Whisper is Planck time zero. Nothing else about the calendar is + /// this simple, so it is checked first. + #[test] + fn test_epoch() { + let epoch = LoicInstant::epoch(); + assert_eq!(epoch.planck(), &I512_ZERO); + } + + /// Both edges of time are admissible instants, the Planck time before + /// Creation is not, and Annihilation is the largest signed 512-bit + /// integer there is. The upper edge has no "beyond" to test. + #[test] + fn test_cosmological_bounds() { + let creation = LoicInstant::from_planck(*creation_planck()); + assert!(creation.is_ok()); + + let annihilation = LoicInstant::from_planck(*annihilation_planck()); + assert!(annihilation.is_ok()); + + let before_creation = LoicInstant::from_planck(creation_planck() - I512_ONE); + assert!(matches!(before_creation, Err(LoicError::Underflow(_)))); + + assert_eq!(annihilation_planck(), &I512::MAX); + } + + /// At the epoch, the time since Creation and the time until + /// Annihilation sum to the span, as they must at every instant, and the + /// terminal time is Annihilation itself, since the epoch is zero. + #[test] + fn test_cosmic_terminal_time() { + let epoch = LoicInstant::epoch(); + + let cosmic = epoch.cosmic_time(); + assert!(cosmic > U512_ZERO); + + let terminal = epoch.terminal_time(); + // At the epoch, terminal_time equals ANNIHILATION_PLANCK exactly + // (since planck = 0 there). Compare via U512, the width the accessor + // speaks in. + assert_eq!(terminal, annihilation_planck().cast_unsigned()); + + let sum = cosmic + terminal; + assert_eq!(sum, *total_span()); + } + + /// Pre-Whisper instants must not panic in `terminal_time()` or + /// `cosmic_time()`: the `U512` wrapping-subtraction formulation has to + /// be correct across the whole representable timeline, including the + /// half of it that lies before the epoch, where a signed difference + /// would not fit. One Planck time before the Whisper is the nearest + /// such instant, and the one at which a signed formulation would first + /// have wrapped. + #[test] + fn test_pre_whisper_accessors() { + // One Planck before the epoch — clearly within valid range, and the + // first instant at which the sign bit is set. + let pre = LoicInstant::from_planck_unchecked(-I512_ONE); + let terminal = pre.terminal_time(); + // terminal at Whisper minus 1 = ANNIHILATION - (-1) = ANNIHILATION + 1, + // a value no I512 could return. + let expected = annihilation_planck().cast_unsigned() + U512_ONE; + assert_eq!(terminal, expected); + + let cosmic = pre.cosmic_time(); + // cosmic at Whisper - 1 = (Whisper - 1) - CREATION = -CREATION - 1, + // one Planck time short of the age of the universe at the epoch. + let expected_cosmic = (-*creation_planck()).cast_unsigned() - U512_ONE; + assert_eq!(cosmic, expected_cosmic); + + // And progress() must not panic across the same input, and must + // still report a fraction strictly below one. + let (num, den) = pre.progress(); + assert!(num < den); + } + + /// The floating-point conversion panics, always, with the sermon it + /// promises. The deprecation warning is silenced here and nowhere else, + /// because this is the one call site that wants the panic. + #[test] + #[should_panic(expected = "HERESY DETECTED")] + #[allow( + deprecated, + reason = "the heresy is invoked on purpose: the panic must stand behind the warning" + )] + fn test_float_heresy() { + let duration = LoicDuration::seconds(1); + let _ = duration.as_seconds_f64(); + } + + /// Parsing accepts a decimal integer with an optional sign and rejects + /// everything else with a parse error, not a panic. + #[test] + fn test_instant_from_str() { + let instant = LoicInstant::from_str("0").unwrap(); + assert_eq!(instant.planck(), &I512_ZERO); + + let negative = LoicInstant::from_str("-1000").unwrap(); + assert_eq!(negative.planck(), &(-1000).as_::()); + + let invalid = LoicInstant::from_str("not_a_number"); + assert!(matches!(invalid, Err(LoicError::ParseError(_)))); + } + + /// Shortening divides by 10²³ and nothing else: forty-two times that + /// power of ten shortens to forty-two, and the epoch shortens to itself. + #[test] + fn test_shortened_timestamp() { + let instant = LoicInstant::from_planck(TEN_TO_23 * (42).as_::()).unwrap(); + assert_eq!(instant.shortened(), (42).as_::()); + + let epoch = LoicInstant::epoch(); + assert_eq!(epoch.shortened(), I512_ZERO); + } + + /// The corners of the grid are addressable, and the 129th cosmic row is + /// not, because there is no such row. + #[test] + fn test_grid_coord_new() { + let coord = GridCoord::new(0, 0).unwrap(); + assert_eq!(coord.cosmic(), 0); + assert_eq!(coord.cycle(), 0); + + let coord = GridCoord::new(127, 255).unwrap(); + assert_eq!(coord.cosmic(), 127); + assert_eq!(coord.cycle(), 255); + + let invalid = GridCoord::new(128, 0); + assert!(matches!(invalid, Err(LoicError::InvalidCoordinate(_)))); + } + + /// Flattening and reconstituting a coordinate is the identity on a + /// sample of both axes including their edges, and the two corners map + /// to zero and 32,767, which pins the row-major orientation. + #[test] + fn test_grid_coord_flat_roundtrip() { + for cosmic in [0u8, 1, 63, 127] { + for cycle in [0u8, 1, 128, 255] { + let coord = GridCoord::new(cosmic, cycle).unwrap(); + let flat = coord.to_flat(); + let recovered = GridCoord::from_flat(flat).unwrap(); + assert_eq!(coord, recovered); + } + } + + assert_eq!(GridCoord::new(0, 0).unwrap().to_flat(), 0); + assert_eq!(GridCoord::new(127, 255).unwrap().to_flat(), 32767); + } + + /// The bottom and top of the lattice, and the top of each channel + /// separately, have the bits and the popcounts their names promise. + #[test] + fn test_mask_empty_and_full() { + let empty = Mask::empty(); + assert_eq!(empty.bits(), 0); + assert_eq!(empty.popcount(), 0); + + let full = Mask::full(); + assert_eq!(full.bits(), 0x7FFF); + assert_eq!(full.popcount(), 15); + + let cosmic = Mask::full_cosmic(); + assert_eq!(cosmic.cosmic_bits(), 0x7F); + assert_eq!(cosmic.cycle_bits(), 0); + + let cycle = Mask::full_cycle(); + assert_eq!(cycle.cosmic_bits(), 0); + assert_eq!(cycle.cycle_bits(), 0xFF); + } + + /// One step up the Hasse diagram and one step back down is the identity, + /// and the lattice declines to activate an active prime or deactivate an + /// inactive one. + #[test] + fn test_mask_activate_deactivate() { + let empty = Mask::empty(); + + let with_andyte = empty.activate(0).unwrap(); + assert!(with_andyte.has_prime(0)); + assert_eq!(with_andyte.popcount(), 1); + + let back = with_andyte.deactivate(0).unwrap(); + assert_eq!(back, empty); + + assert!(with_andyte.activate(0).is_none()); + assert!(empty.deactivate(0).is_none()); + } + + /// The Whisper has fifteen parents and no children, the full mask the + /// reverse, and a single prime has fourteen of one and one of the other: + /// the covers of a node number fifteen in total, always. + #[test] + fn test_mask_parents_children() { + let empty = Mask::empty(); + assert_eq!(empty.parents().len(), 15); + assert_eq!(empty.children().len(), 0); + + let full = Mask::full(); + assert_eq!(full.parents().len(), 0); + assert_eq!(full.children().len(), 15); + + let single = Mask::new(1).unwrap(); + assert_eq!(single.parents().len(), 14); + assert_eq!(single.children().len(), 1); + } + + /// Bit 15 is refused whether it arrives alone or with company, the + /// refusal carries the offending bits back, and the full fifteen-bit + /// mask is admitted. + #[test] + fn test_mask_invalid() { + assert!(matches!( + Mask::new(0x8000), + Err(LoicError::InvalidMask(0x8000)) + )); + assert!(matches!( + Mask::new(0xFFFF), + Err(LoicError::InvalidMask(0xFFFF)) + )); + assert!(Mask::new(0x7FFF).is_ok()); + } + + /// The folded constants exist, are positive, agree with one another + /// where they are supposed to, and multiply back into the numbers they + /// factor; the name tables have the right length and the right names at + /// both ends. + #[test] + fn test_constants_exist() { + assert!(PLANCK_PER_CYCLE > I512_ZERO); + assert!(COSMIC_SPAN > U512_ZERO); + // The two constants are constructed from independent paths + // (transcribed string vs. ANNIHILATION + |CREATION|) and are + // designed to coincide exactly. The compiler already refused to + // build without this; the runtime confirms it out of politeness, + // and so that the receipt appears in the test log as well as the + // build. + assert_eq!(COSMIC_SPAN, TOTAL_SPAN); + assert_eq!(COSMIC_PRIMES.len(), 7); + assert_eq!(CYCLE_PRIMES.len(), 8); + assert!(TEN_TO_23 > I512_ZERO); + // The product of the seven cosmic primes is the span itself; the + // product of the eight cycle primes is the cycle. Squarefree means + // the factorization is the number, and this is the one place the + // reliquaries of the primes are exercised at all: a mistyped digit + // in any of the fifteen would multiply to the wrong constant. + assert_eq!(Mask::full_cosmic().cosmic_divisor(), COSMIC_SPAN); + assert_eq!( + Mask::full_cycle().cycle_divisor(), + PLANCK_PER_CYCLE.cast_unsigned() + ); + + assert_eq!(COSMIC_PRIME_NAMES.len(), 7); + assert_eq!(COSMIC_PRIME_NAMES[0], "Andyte"); + assert_eq!(COSMIC_PRIME_NAMES[6], "Nandyte"); + + assert_eq!(CYCLE_PRIME_NAMES.len(), 8); + assert_eq!(CYCLE_PRIME_NAMES[0], "Dyad"); + assert_eq!(CYCLE_PRIME_NAMES[7], "Psi"); + } + + /// A subdivision result hands back the three integers it was given, in + /// the order it was given them: tick twenty-nine, a thousand Planck + /// times in, of a tick five thousand wide. + #[test] + fn test_subdivision_result() { + let result = SubdivisionResult::new( + (29u64).as_::(), + (1000u64).as_::(), + (5000u64).as_::(), + ); + assert_eq!(result.position(), &(29u64).as_::()); + assert_eq!(result.offset(), &(1000u64).as_::()); + assert_eq!(result.part_size(), &(5000u64).as_::()); + } + + /// Sixty seconds are a minute and sixty minutes an hour, to the Planck + /// time; zero is zero and not negative; a negated second is negative. + /// The sexagesimal ladder holds because each rung is built from the + /// same ceiling. + #[test] + fn test_duration_arithmetic() { + let d1 = LoicDuration::seconds(60); + let d2 = LoicDuration::minutes(1); + assert_eq!(d1.planck(), d2.planck()); + + let d3 = LoicDuration::hours(1); + let d4 = LoicDuration::minutes(60); + assert_eq!(d3.planck(), d4.planck()); + + let zero = LoicDuration::zero(); + assert!(zero.is_zero()); + assert!(!zero.is_negative()); + + let neg = -LoicDuration::seconds(1); + assert!(neg.is_negative()); + } + + /// One second forward from the Whisper, one second back, and the + /// difference between the two instants is the second that was added: + /// instant arithmetic is exact and reversible. + #[test] + fn test_instant_arithmetic() { + let epoch = LoicInstant::epoch(); + let one_sec = LoicDuration::seconds(1); + + let future = epoch.add_duration(&one_sec).unwrap(); + assert!(future.planck() > epoch.planck()); + + let back = future.sub_duration(&one_sec).unwrap(); + assert_eq!(back.planck(), epoch.planck()); + + let diff = future.difference(&epoch); + assert_eq!(diff.planck(), one_sec.planck()); + } + + /// The two channel projections partition the full mask's bits with + /// nothing shared and nothing lost, land on the right halves, and + /// reconstitute an arbitrary mixed mask when joined. + #[test] + fn test_mask_channel_split() { + let full = Mask::full(); + let c2 = full.channel_2(); + let c1 = full.channel_1(); + + // Channels partition the bits: their join is the whole, their meet + // is nothing. + assert_eq!(c2.bits() | c1.bits(), full.bits()); + assert_eq!(c2.bits() & c1.bits(), 0); + + // channel_2 has only cosmic bits (0-6), the low seven. + assert_eq!(c2.bits(), 0x007F); + // channel_1 has only cycle bits (7-14), the next eight. + assert_eq!(c1.bits(), 0x7F80); + + // Round-trip: channel_2 | channel_1 = original. + // The underscore splits the literal at the channel boundary + // (bit 7): 7 cycle bits on the left, 7 cosmic bits on the right. + // 4-bit grouping would obscure the channel decomposition the + // test is written to exercise, which is why the lint is set aside + // for this one literal and its twin below. + #[allow( + clippy::unreadable_literal, + reason = "the underscore marks the channel boundary at bit 7, not a group of four bits" + )] + let mixed = Mask::new(0b0000001_1010101).unwrap(); + let reconstructed = Mask::new(mixed.channel_2().bits() | mixed.channel_1().bits()).unwrap(); + assert_eq!(mixed.bits(), reconstructed.bits()); + } + + /// The Whisper divides by one on both channels and in total; a mixed + /// mask's divisor is the product of its two halves; a single prime's + /// divisor is that prime; and the full cosmic mask's divisor is the + /// Cosmic Span, which is the squarefree identity stated as a test. + #[test] + fn test_mask_divisors() { + // Empty mask: divisors are all ONE, the denominator that changes + // nothing. + let empty = Mask::empty(); + assert_eq!(empty.cosmic_divisor(), U512_ONE); + assert_eq!(empty.cycle_divisor(), U512_ONE); + assert_eq!(empty.divisor(), U512_ONE); + + // divisor() == cosmic_divisor() * cycle_divisor() (in U512), checked + // on a mask small enough for the product to fit. + // Same channel-split notation as `test_mask_channel_split`: + // dyad (bit 7) on the left of the underscore, andyte (bit 0) + // on the right. + #[allow( + clippy::unreadable_literal, + reason = "the underscore marks the channel boundary at bit 7, not a group of four bits" + )] + let mixed = Mask::new(0b0000001_0000001).unwrap(); // andyte + dyad, one per channel + assert_eq!( + mixed.divisor(), + mixed.cosmic_divisor() * mixed.cycle_divisor() + ); + + // Single cosmic prime: andyte (bit 0) = 16631, the smallest atom. + let andyte = Mask::andyte(); + assert_eq!(andyte.cosmic_divisor(), (16631u64).as_::()); + + // Single cycle prime: dyad (bit 7) = 2, the smallest prime there is. + let dyad = Mask::dyad(); + assert_eq!(dyad.cycle_divisor(), (2u64).as_::()); + + // Full cosmic mask: product of all 7 cosmic primes = COSMIC_SPAN, + // the squarefree identity, and the one divisor that needs the + // unsigned width. + let full_cosmic = Mask::full_cosmic(); + assert_eq!(full_cosmic.cosmic_divisor(), COSMIC_SPAN); + } + + /// Each named constructor sets the one bit its name promises, each has + /// resolution one, and the Whisper has none: fifteen atoms and the + /// bottom, accounted for by name. + #[test] + fn test_named_constructors() { + // Each named constructor activates exactly one bit at the right + // position, in gate order and then in magnitude order. + assert_eq!(Mask::andyte().bits(), 1 << 0); + assert_eq!(Mask::xoryte().bits(), 1 << 1); + assert_eq!(Mask::oryte().bits(), 1 << 2); + assert_eq!(Mask::noryte().bits(), 1 << 3); + assert_eq!(Mask::xnoryte().bits(), 1 << 4); + assert_eq!(Mask::notyte().bits(), 1 << 5); + assert_eq!(Mask::nandyte().bits(), 1 << 6); + + assert_eq!(Mask::dyad().bits(), 1 << 7); + assert_eq!(Mask::pentad().bits(), 1 << 8); + assert_eq!(Mask::heptad().bits(), 1 << 9); + assert_eq!(Mask::hendecad().bits(), 1 << 10); + assert_eq!(Mask::sigma().bits(), 1 << 11); + assert_eq!(Mask::tau().bits(), 1 << 12); + assert_eq!(Mask::phi().bits(), 1 << 13); + assert_eq!(Mask::psi().bits(), 1 << 14); + + // Each activates exactly one prime, and so sits on the first level + // above the Whisper. + for m in [ + Mask::andyte(), + Mask::xoryte(), + Mask::oryte(), + Mask::noryte(), + Mask::xnoryte(), + Mask::notyte(), + Mask::nandyte(), + Mask::dyad(), + Mask::pentad(), + Mask::heptad(), + Mask::hendecad(), + Mask::sigma(), + Mask::tau(), + Mask::phi(), + Mask::psi(), + ] { + assert_eq!(m.resolution(), 1); + } + + // Whisper = empty: the same mask under the framework's name. + assert_eq!(Mask::whisper().bits(), 0); + assert_eq!(Mask::whisper().resolution(), 0); + } + + /// Hamming distance is zero from a mask to itself, fifteen between the + /// bottom and the top in either direction, and two between any pair of + /// single primes; the subset relation is reflexive and not symmetric. + #[test] + fn test_mask_distance() { + let empty = Mask::empty(); + let full = Mask::full(); + + assert_eq!(empty.distance(&empty), 0); + assert_eq!(full.distance(&full), 0); + assert_eq!(empty.distance(&full), 15); + assert_eq!(full.distance(&empty), 15); + + // Single-bit masks differ by 2: one bit each, neither shared. + assert_eq!(Mask::andyte().distance(&Mask::dyad()), 2); + + // Subset relations: below, above, reflexive, and not the other way. + assert!(Mask::andyte().is_below(&Mask::full())); + assert!(Mask::full().is_above(&Mask::andyte())); + assert!(empty.is_below(&empty)); + assert!(full.is_above(&full)); + assert!(!Mask::andyte().is_above(&Mask::full())); + } + + /// A cosmic observation at the epoch satisfies the division identity — + /// tick times grain plus offset is the cosmic time — with a positive + /// grain and an offset inside it. + #[test] + fn test_observe_cosmic() { + let epoch = LoicInstant::epoch(); + let andyte_mask = Mask::andyte(); + let cosmic_time = epoch.cosmic_time(); + + let result = andyte_mask.observe(&epoch).unwrap(); + // Structural invariant: position * part_size + offset == cosmic_time, + // which is what a quotient and a remainder are for. + let reconstructed = result.position() * result.part_size() + result.offset(); + assert_eq!(reconstructed, cosmic_time); + // part_size = COSMIC_SPAN / 16631, which is positive and large — + // nearly 10⁹⁹ years of it. + assert!(*result.part_size() > U512_ZERO); + // offset is within [0, part_size), as every interior instant's is. + assert!(result.offset() < result.part_size()); + } + + /// A cycle observation at the epoch satisfies the same identity against + /// the cosmic time reduced modulo the cycle, which is the quantity the + /// content axis actually subdivides. + #[test] + fn test_observe_cycle() { + let epoch = LoicInstant::epoch(); + let dyad_mask = Mask::dyad(); + let cycle_time = epoch.cosmic_time() % PLANCK_PER_CYCLE.cast_unsigned(); + + let result = dyad_mask.observe(&epoch).unwrap(); + // Structural invariant: position * part_size + offset == cycle_time, + // the same identity on the other channel. + let reconstructed = result.position() * result.part_size() + result.offset(); + assert_eq!(reconstructed, cycle_time); + assert!(*result.part_size() > U512_ZERO); + assert!(result.offset() < result.part_size()); + } + + /// A mask with a prime on each side of bit 7 is two questions, and + /// `observe()` says so rather than guessing which one was meant. + #[test] + fn test_observe_mixed_returns_error() { + let epoch = LoicInstant::epoch(); + // Mixed mask: andyte (cosmic bit 0) + dyad (cycle bit 7), the + // smallest prime of each channel. + let mixed = Mask::new((1 << 0) | (1 << 7)).unwrap(); + assert!(matches!( + mixed.observe(&epoch), + Err(LoicError::MixedMask(_)) + )); + } + + /// The dual observation answers both questions, each with a positive + /// grain, and the cycle half's grain is exactly half a cycle, since the + /// only cycle prime engaged is two. + #[test] + fn test_observe_dual() { + let epoch = LoicInstant::epoch(); + let mixed = Mask::new((1 << 0) | (1 << 7)).unwrap(); // andyte + dyad, one per channel + let dual = mixed.observe_dual(&epoch); + + // Both channels produce valid subdivision results with a grain. + assert!(*dual.channel_2.part_size() > U512_ZERO); + assert!(*dual.channel_1.part_size() > U512_ZERO); + // channel_2 part_size = COSMIC_SPAN / andyte_prime, channel_1 = PLANCK_PER_CYCLE / 2; + // the cycle half is small enough to state exactly. + assert_eq!( + *dual.channel_1.part_size(), + PLANCK_PER_CYCLE.cast_unsigned() / (2u64).as_::(), + ); + } + + /// The epoch's grid address is a cell the lattice actually has. + #[test] + fn test_grid_coord_epoch() { + let epoch = LoicInstant::epoch(); + let coord = epoch.grid_coord(); + // grid_coord() should return a valid GridCoord (flat index in + // [0, 32767]); the constructor inside it already guarantees this, + // and the test says so out loud. + let flat = coord.to_flat(); + assert!(flat <= 32767); + } + + /// At Creation every quotient is zero and so every parity is even: the + /// origin of the grid is the origin of time. + #[test] + fn test_grid_coord_at_creation() { + // At CREATION (cosmic_time = 0), all parity bits are 0, on both axes. + let creation = LoicInstant::from_planck(CREATION_PLANCK).unwrap(); + let coord = creation.grid_coord(); + assert_eq!(coord.cosmic(), 0); + assert_eq!(coord.cycle(), 0); + } + + /// The Dyad parity bit must be clear one Planck before the half-cycle + /// and set at it: the cheapest possible proof that `grid_coord()` is + /// reading the cycle axis and not merely returning zeros, bought with a + /// single Planck time of difference. + #[test] + fn test_grid_coord_parity_flips_at_half_cycle() { + let half = PLANCK_PER_CYCLE / i64_to_i512(2); + let before = LoicInstant::from_planck(CREATION_PLANCK + half - I512_ONE).unwrap(); + let at = LoicInstant::from_planck(CREATION_PLANCK + half).unwrap(); + assert_eq!(before.grid_coord().cycle() & 1, 0); + assert_eq!(at.grid_coord().cycle() & 1, 1); + // Cosmic parity is untouched by anything a mere cycle can do; the + // narrowest cosmic partition is wider than the cycle by some + // twenty-eight orders of magnitude. + assert_eq!(at.grid_coord().cosmic(), 0); + } + + /// The first flat index past the lattice and the last one a `u16` can + /// hold are both refused, and the last valid index is the far corner. + #[test] + fn test_grid_coord_from_flat_bounds() { + assert!(matches!( + GridCoord::from_flat(32_768), + Err(LoicError::InvalidCoordinate(_)) + )); + assert!(matches!( + GridCoord::from_flat(0xFFFF), + Err(LoicError::InvalidCoordinate(_)) + )); + let last = GridCoord::from_flat(32_767).unwrap(); + assert_eq!((last.cosmic(), last.cycle()), (127, 255)); + } + + /// Roughly one entropy default in four must collapse, every collapse + /// must carry the bit-15 flag and an index of at least 128, and no + /// successful draw may ever produce a mixed mask. Twenty thousand trials + /// put the standard deviation of the collapse count near 0.3%; the + /// 20–30% window is therefore some sixteen sigma wide. If this fails, + /// the entropy source is broken, not unlucky, and the calendar's one + /// deliberate failure mode has failed to fail at the rate the workspace + /// README, section 7.3, and the license both promise. + #[test] + fn test_entropy_default_distribution() { + let trials: usize = 20_000; + let mut collapsed = 0usize; + for _ in 0..trials { + match Mask::entropy_default() { + Ok(m) => assert!( + m.cosmic_bits() == 0 || m.cycle_bits() == 0, + "entropy_default yielded a mixed mask, {m}, which no single pool can produce" + ), + Err(LoicError::InvalidMask(bits)) => { + assert_eq!(bits & 0x8000, 0x8000); + assert!((bits & 0xFF) >= 128); + collapsed += 1; + } + Err(other) => panic!("entropy_default failed some other way entirely: {other}"), + } + } + assert!( + collapsed * 100 >= trials * 20 && collapsed * 100 <= trials * 30, + "collapse rate {collapsed}/{trials} is outside the 20–30% window: broken, not unlucky" + ); + } + + /// The documented boundary cases at ANNIHILATION: the Whisper's offset + /// equals its part size, a cosmic mask's position equals its divisor + /// with nothing left over, and a cycle mask still satisfies the division + /// identity with its offset strictly inside the grain. The edge of time + /// is the one place the reflexive equalities appear, and the test goes + /// there to see them. + #[test] + fn test_observe_at_annihilation() { + let end = LoicInstant::from_planck(ANNIHILATION_PLANCK).unwrap(); + assert_eq!(end.cosmic_time(), COSMIC_SPAN); + assert_eq!(end.terminal_time(), U512_ZERO); + + let whisper = Mask::whisper().observe(&end).unwrap(); + assert_eq!(*whisper.position(), U512_ZERO); + assert_eq!(whisper.offset(), whisper.part_size()); + assert_eq!(*whisper.part_size(), COSMIC_SPAN); + + let andyte = Mask::andyte().observe(&end).unwrap(); + assert_eq!(*andyte.position(), Mask::andyte().cosmic_divisor()); + assert_eq!(*andyte.offset(), U512_ZERO); + + let heptad = Mask::heptad().observe(&end).unwrap(); + let cycle_time = COSMIC_SPAN % PLANCK_PER_CYCLE.cast_unsigned(); + assert_eq!( + heptad.position() * heptad.part_size() + heptad.offset(), + cycle_time + ); + assert!(heptad.offset() < heptad.part_size()); + } + + /// `as_whole_seconds` at the extremes, checked against an independent + /// `U1024` computation that never needs the quotient–remainder split, + /// because at twice the width the naive product simply fits. Two + /// routes, one answer, at the largest duration a signed word can hold. + #[test] + fn test_as_whole_seconds_at_extremes() { + let max = LoicDuration::from_planck(I512::MAX); + let expected = (I512::MAX.cast_unsigned().as_::() + * (PLANCK_TIME_NUMERATOR).as_::()) + / PLANCK_DENOMINATOR.cast_unsigned().as_::(); + assert_eq!( + max.as_whole_seconds().cast_unsigned().as_::(), + expected + ); + + // Truncation toward zero is symmetric: the past is as long as the + // future. + let neg = LoicDuration::from_planck(-I512::MAX); + assert_eq!(neg.as_whole_seconds(), -max.as_whole_seconds()); + + // One Planck short of a second is zero seconds, in both directions; + // this is the absurdity the ceiling in seconds_to_planck exists to + // keep away from seconds(1). + let almost = seconds_to_planck(1) - I512_ONE; + assert_eq!( + LoicDuration::from_planck(almost).as_whole_seconds(), + I512_ZERO + ); + assert_eq!( + LoicDuration::from_planck(-almost).as_whole_seconds(), + I512_ZERO + ); + } + + /// Every constructor must round-trip exactly through `as_whole_seconds`, + /// negation must be exact, and the overshoot must stay below one Planck + /// time—for counts from a single second to `i64::MAX` of them, and for + /// the sexagesimal ladder of minutes, hours and days, each rung of which + /// must agree with the one below it to the Planck time. + #[test] + fn test_duration_constructors_round_trip() { + for n in [ + 1i64, + 2, + 59, + 60, + 3_599, + 3_600, + 86_400, + 1_000_000_007, + i64::MAX, + ] { + assert_eq!( + LoicDuration::seconds(n).as_whole_seconds(), + n.as_::(), + "seconds({n}) did not round-trip through as_whole_seconds" + ); + assert_eq!( + LoicDuration::seconds(-n).as_whole_seconds(), + (-n).as_::(), + "seconds(-{n}) did not round-trip through as_whole_seconds" + ); + assert_eq!(LoicDuration::seconds(-n), -LoicDuration::seconds(n)); + } + assert_eq!( + LoicDuration::minutes(7).as_whole_seconds(), + (7 * 60).as_::() + ); + assert_eq!( + LoicDuration::hours(3).as_whole_seconds(), + (3 * 3_600).as_::() + ); + assert_eq!( + LoicDuration::days(2).as_whole_seconds(), + (2 * 86_400).as_::() + ); + assert_eq!(LoicDuration::days(1), LoicDuration::hours(24)); + assert_eq!(LoicDuration::hours(1), LoicDuration::minutes(60)); + assert_eq!(LoicDuration::minutes(1), LoicDuration::seconds(60)); + + // Overshoot: planck × NUM − n × DEN lies in [0, NUM), which is the + // ceiling stated as an inequality: never short, never a whole Planck + // time long. + let one = *LoicDuration::seconds(1).planck(); + let overshoot = one * PLANCK_NUMERATOR_I512 - PLANCK_DENOMINATOR; + assert!(overshoot >= I512_ZERO && overshoot < PLANCK_NUMERATOR_I512); + } + + /// The division-free conversion must agree with the direct formula + /// everywhere: zero, both signs, the numerator itself and its + /// neighbours, the present epoch, and the far ends of what an `i64` + /// `tv_sec` can produce—then along a geometric sweep between. The + /// reference is the one 512-bit multiply and divide the hot path + /// refuses to perform, performed here, slowly, where nobody minds. + #[test] + fn test_ns_conversion_matches_reference() { + let reference = |ns: i128| (ns.as_::() * TEN_TO_41) / PLANCK_NUMERATOR_I512; + let offset = i128::from(LOIC_TO_UNIX_OFFSET_NS); + let samples = [ + 0i128, + 1, + -1, + 5_391_246, + 5_391_247, + -5_391_247, + 1_000_000_000, + 1_788_806_391_000_000_000 + offset, + i128::from(i64::MAX) * 1_000_000_000 + 999_999_999 + offset, + i128::from(i64::MIN) * 1_000_000_000 + offset, + ]; + for ns in samples { + assert_eq!( + ns_to_planck(ns), + reference(ns), + "ns = {ns}: limbs vs formula" + ); + } + // A geometric sweep across twenty-odd orders of magnitude, both + // signs, with a prime in the step so the samples do not fall on + // anything round. + let mut ns: i128 = 1; + while ns < 10i128.pow(28) { + assert_eq!( + ns_to_planck(ns), + reference(ns), + "ns = {ns}: limbs vs formula" + ); + assert_eq!( + ns_to_planck(-ns), + reference(-ns), + "ns = -{ns}: limbs vs formula" + ); + ns = ns * 3 + 7_919; + } + } + + /// The sub-nanosecond draw must always land inside one nanosecond: the + /// rejection loop's whole purpose, checked a thousand times with a + /// thousand different stirs. + #[test] + fn test_sub_ns_entropy_is_in_range() { + for stir in 0..1_000u64 { + let e = sub_ns_entropy(stir); + assert!(e >= I512_ZERO && e < SUB_NS_RANGE); + } + } + + /// The sub-nanosecond entropy is uniform on its range: a hundred + /// thousand draws, each stirred with a different word as `now()` stirs + /// them, fall into sixteen equal buckets within a few percent of one + /// another, and no two consecutive draws coincide. Sixteen buckets of + /// 6,250 have a standard deviation of 77 apiece; the tolerance is more + /// than six of them, which a uniform source fails once in a geological + /// age and a broken one fails at once. Uniformity is the acceptance + /// criterion of the whole entropy design, and this is where it is + /// measured rather than asserted. + #[test] + fn test_sub_ns_entropy_is_uniform() { + let draws = 100_000u32; + let mut buckets = [0u32; 16]; + let mut previous = sub_ns_entropy(0); + for stir in 1..=draws { + let e = sub_ns_entropy(u64::from(stir)); + assert!(e >= I512_ZERO && e < SUB_NS_RANGE); + assert_ne!(e, previous); + previous = e; + let bucket = (e * 16i64.as_::()) / SUB_NS_RANGE; + buckets[usize::try_from(bucket.as_::()).expect("a bucket index under 16")] += 1; + } + let expected = draws / 16; + for (i, &count) in buckets.iter().enumerate() { + assert!( + count.abs_diff(expected) < expected / 12, + "bucket {i} holds {count}, expected about {expected}; the source is not uniform" + ); + } + } + + /// The Boolean identities of the lattice on a single prime from each + /// channel: join and meet against the bottom, the top, and the + /// complement; the involution of complement; the operators agreeing + /// with the methods; and the partial order being genuinely partial. + #[test] + fn test_lattice_operations() { + let a = Mask::andyte(); + let d = Mask::dyad(); + let full = Mask::full(); + let whisper = Mask::whisper(); + + assert_eq!(a.join(&d).bits(), (1 << 0) | (1 << 7)); + assert_eq!(a.meet(&d), whisper); + assert_eq!(a.join(&whisper), a); + assert_eq!(a.meet(&full), a); + assert_eq!(a.complement().join(&a), full); + assert_eq!(a.complement().meet(&a), whisper); + assert_eq!(!full, whisper); + assert_eq!(!whisper, full); + assert_eq!(!!a, a); + assert_eq!(a | d, a.join(&d)); + assert_eq!(a & d, a.meet(&d)); + + // The partial order is partial: comparable up and down a chain, and + // silent across one. + assert_eq!(a.partial_cmp(&full), Some(Ordering::Less)); + assert_eq!(full.partial_cmp(&a), Some(Ordering::Greater)); + assert_eq!(a.partial_cmp(&a), Some(Ordering::Equal)); + assert_eq!(a.partial_cmp(&d), None); + assert!(a < full && whisper < a); + // Incomparable: every ordering predicate is false, and so is + // equality, which is a thing bool can express and this line sits + // with. + assert!(!a.lt(&d) && !a.gt(&d) && !a.le(&d) && !a.ge(&d) && a != d); + } + + /// The kernel must at least answer the question. Whether it answers + /// honestly is a property of the machine, not of the crate, and is not + /// asserted here; a zero is a lie the first `now()` will deal with, and + /// a negative number would be a discovery. + #[test] + fn test_kernel_tai_offset_is_readable() { + let tai = kernel_tai_offset(); + assert!( + tai >= 0, + "a negative leap-second count would be news, and not the good kind" + ); + } +} diff --git a/crates/loid/Cargo.toml b/crates/loid/Cargo.toml new file mode 100644 index 0000000..d89b900 --- /dev/null +++ b/crates/loid/Cargo.toml @@ -0,0 +1,26 @@ +# The LOID generator: a Planck-time timestamp with entropy in its +# sub-nanosecond digits, offered as an identifier — two functions, an +# integer, and a refusal to be a UUID. Published under the workspace's one +# version; the registry metadata below is what it shows. +[package] +name = "loid" +version.workspace = true +edition = "2024" +authors.workspace = true +repository.workspace = true +license-file.workspace = true +description = "Loic Identifier. A Planck-time timestamp with hardware entropy in its sub-nanosecond digits. An integer. Your problem." +readme = "README.md" +keywords = ["identifier", "planck", "arpanet", "not-a-uuid", "your-problem"] +categories = ["date-and-time"] + +# The one dependency: the calendar itself, at the workspace's single stated +# version. A LOID is an instant that has been asked to serve as a name, and +# an instant is the library's to make. +[dependencies] +loic.workspace = true + +# The library target, named and placed explicitly rather than inferred. +[lib] +name = "loid" +path = "src/lib.rs" diff --git a/crates/loid/README.md b/crates/loid/README.md new file mode 100644 index 0000000..8c43bdc --- /dev/null +++ b/crates/loid/README.md @@ -0,0 +1,41 @@ +# loid + +Loic Identifier. A Planck-time timestamp. An integer. Your problem. + +```rust +let id = loid::loid(); // ~53 decimal digits, subject to the inevitable passing of time +let short = loid::short(); // ~30 decimal digits, subject to the inevitable passing of time +``` + +Two functions. One type (`I512`). One dependency (`loic`). No wrapper. No Display of +its own. No serde. No monotonicity. No opinions. Universal and absolute. + +## What it does + +Each call samples the current moment via `CLOCK_TAI` (atomic time) and a generator +seeded from the kernel's entropy pool and stirred with the nanosecond of the +observation itself, producing a 512-bit signed integer counting Planck times since +the Loic epoch (the first ARPANET transmission, 1969-10-30 06:30:41 UTC). Nineteen +of its digits say which nanosecond you are in. The remaining thirty-four are the +universe's answer to which Planck time within that nanosecond, and the universe does +not repeat itself. + +`short()` divides the full timestamp by 10²³, keeping ~11 of the original ~34 +entropy digits. Two `short()` values minted in the same nanosecond collide with +probability better than one in a hundred billion, which is either reassuring or +terrifying depending on what you were planning to do with them. + +## Requirements + +Linux, and a kernel that knows what TAI is. `CLOCK_TAI` is only TAI if a time daemon +has read a leap-second table and told the kernel the offset — chrony with +`leapseclist /usr/share/zoneinfo/leap-seconds.list` or `leapsectz right/UTC`, or ntpd with a `leapfile`. systemd-timesyncd never does. On a +machine where the offset is zero, the first call panics and tells you which line to +add. If you're on anything else, this crate is not for you, and you should reflect on +why. + +## License + +Dual-licensed under AGPL-3.0 and the Loic Public License. See the workspace root for +the terms, and the workspace README for the theoretical substrate the license keeps +citing. diff --git a/crates/loid/src/lib.rs b/crates/loid/src/lib.rs new file mode 100644 index 0000000..815b563 --- /dev/null +++ b/crates/loid/src/lib.rs @@ -0,0 +1,149 @@ +//! # LOID — Loic Identifier +//! +//! Two functions. One type. No opinions, beyond the several that follow. +//! +//! A LOID is a Planck-time timestamp drawn from the Loic Calendar's quantum +//! observation pipeline—the mask-free half of it, the collapse without the +//! question. Each invocation of `loid()` collapses the sub-nanosecond +//! superposition of the present moment into a unique 512-bit signed +//! integer—deterministic in its upper digits (the atomic clock, read through +//! `CLOCK_TAI`), entropic in its lower digits (a per-thread generator seeded +//! from the kernel's pool and stirred by the timing of the observation +//! itself), and unreasonably large by any conventional metric, being a count +//! of Planck times since the first transmission between networked machines +//! and therefore some fifty-three digits long before it has finished +//! introducing itself. +//! +//! The shortened variant, `short()`, amputates the lowest 23 decimal orders +//! of magnitude via integer division, retaining ~11 digits of quantum +//! entropy from the original ~34. The result is still an `I512`. It is still +//! your problem. The workspace README lists this crate among the four as the +//! one with no wrapper type and no opinions; the second claim was +//! aspirational. +//! +//! ## What This Is Not +//! +//! - Not monotonic. Two calls within the same nanosecond may produce values +//! in either order, because the entropy that fills the nanosecond makes no +//! promises about sequence—it makes exactly one promise, uniformity, and +//! uniformity is the opposite of order. Across nanoseconds the atomic +//! clock is doing its best, and atomic clocks, when disciplined over a +//! network, have been known to step. If you need monotonicity, enforce it +//! yourself. The universe doesn't care, and per the workspace README, +//! section 1.3, does not even agree with itself about simultaneity. +//! +//! - Not a UUID. Not a ULID. Not a KSUID. Not a Snowflake. Not any of the +//! carefully-engineered identifier schemes designed by reasonable people +//! for reasonable systems, with their version nibbles and their variant +//! bits and their sixty-four-bit ambitions. This is a raw Planck timestamp +//! with entropy spliced into its sub-nanosecond residue—the Loic Public +//! License, Section 10, lists "generating unique identifiers from quantum +//! observations of the sub-nanosecond void" among the permitted uses, and +//! this crate is that permission exercised and nothing more. What you do +//! with it is, as noted above, your problem. +//! +//! - Not wrapped. There is no newtype, no `Display` of its own, no `FromStr` +//! of its own, no serde. The output is `I512`, which already has +//! `to_string()` and `from_str()`. The rest is ceremony, and ceremony is +//! not shipped here; a caller who wants an instant with methods on it +//! wants `loic::LoicInstant`, which is where these two functions get +//! theirs. +//! +//! - Not tested here. Every test would have to call `now()`, and `now()` +//! refuses machines whose kernel does not know what TAI is (see below), so +//! a test suite would pass or fail according to your time daemon rather +//! than this crate. The arithmetic is `loic`'s and is tested there, where +//! it is checked against a naive formula at twice the width; there is +//! nothing in these two functions to test that is not either that +//! arithmetic or the kernel. +//! +//! ## Usage +//! +//! ```rust,no_run +//! let id = loid::loid(); // full Planck timestamp (~53 digits) +//! let short_id = loid::short(); // truncated by 10^23 (~30 digits) +//! ``` + +#![warn(clippy::pedantic)] + +/// The one type. Re-exported from `loic`, which re-exports it from `bnum`, +/// so that a caller who names `loid::I512` and a caller who names +/// `loic::I512` are naming the same integer and not two integers that +/// merely agree—a distinction the type system enforces and a reader may +/// safely forget, which is the best kind of distinction. Five hundred and +/// twelve bits, signed, of which a fresh identifier uses about a hundred +/// and seventy-five. +pub use loic::I512; + +/// Procures a fresh Loic Identifier: the full Planck timestamp of this +/// instant, as an integer, with nothing wrapped around it. +/// +/// Each call observes the current moment through the Loic Calendar's +/// dual-source temporal pipeline—atomic time for the deterministic +/// component, entropy seeded from the kernel's pool and stirred by the +/// observation's own timing for the sub-nanosecond quantum residue—and +/// returns the resulting `I512`, copied out of the instant it came in, +/// since the instant has nothing else to offer an identifier. +/// +/// The value contains approximately 19 deterministic digits (from +/// `CLOCK_TAI`, encoding which nanosecond you are in) and 34 entropic digits +/// (from the seeded generator, collapsing the sub-nanosecond superposition +/// of roughly 10³⁴ Planck-scale coordinates into one), totaling roughly 53 +/// decimal digits. The two are not added but concatenated: the nanosecond +/// occupies the high digits and the collapse the low ones, and the whole is +/// one integer counting Planck times since the Whisper, not a pair of +/// numbers wearing a single type. Whether this degree of precision is +/// necessary, useful, or sane is a question this crate declines to +/// entertain, and the Loic Public License, Section 2, declines on its +/// behalf. +/// +/// # Panics +/// +/// Panics under the same three conditions as `loic::LoicInstant::now()`, of +/// which it is the thinnest possible wrapper: if `CLOCK_TAI` is unavailable, +/// if the kernel's entropy pool cannot furnish the generator's seed, or—once +/// per process, on the first call—if the kernel reports a TAI offset of +/// zero, which means `CLOCK_TAI` has been `CLOCK_REALTIME` in a name tag all +/// along. The first two do not occur on any Linux of the kernel generation +/// the calendar requires. The third occurs on most of them, until chrony or +/// ntpd is told where the leap-second table is; the panic message says which +/// line to add, and the workspace README, section 1.2, says why it matters. +/// On other operating systems, you should not be here, and the compiler will +/// already have said so. +#[inline] +#[must_use = "A Loic Identifier minted and discarded — the universe collapsed thirty-four digits of superposition for an integer nobody kept, and it will not collapse them the same way twice."] +pub fn loid() -> I512 { + *loic::LoicInstant::now().planck() +} + +/// Procures a shortened Loic Identifier: the full timestamp divided by +/// 10²³, by one 512-bit division that truncates toward zero. +/// +/// This function observes the full instant exactly as `loid()` does— +/// generating the full 34 digits of quantum entropy—and only then truncates +/// 23 of them away, through `loic::LoicInstant::shortened()`. The ordering +/// matters: one does not generate 11 digits of entropy directly. One +/// generates 34 and discards 23, because the generator draws uniformly at a +/// fixed granularity of one Planck time and truncating post-hoc preserves +/// the statistical properties of the original quantum observation, whereas +/// a generator asked for eleven digits would be answering a question about +/// a coarser superposition that the calendar does not recognise. +/// +/// The result retains approximately 11 digits of entropy, sufficient to +/// distinguish simultaneous observations with high probability. "High +/// probability" here means "better than one in a hundred billion," which is +/// either reassuring or terrifying depending on your failure mode +/// tolerance, and which the calendar notes is a great deal better than the +/// odds most calendars offer two events in the same second. +/// +/// # Panics +/// +/// Same conditions as `loid()`, for the same reason: the observation is the +/// same. The truncation itself cannot fail; integer division by a power of +/// ten is the one operation in this workspace that has never had an +/// opinion. +#[inline] +#[must_use = "A shortened Loic Identifier minted and discarded — twenty-three digits were amputated to make it convenient, and it was still not kept, which suggests convenience was not the obstacle."] +pub fn short() -> I512 { + loic::LoicInstant::now().shortened() +} diff --git a/derive_constants.sh b/derive_constants.sh new file mode 100755 index 0000000..f9a5518 --- /dev/null +++ b/derive_constants.sh @@ -0,0 +1,690 @@ +#!/bin/sh +# ╔═══════════════════════════════════════════════════════════════════════════╗ +# ║ ║ +# ║ THE LOIC CYCLE DERIVATION ORACLE ║ +# ║ ║ +# ║ Computing the Fundamental Cycle of the Loic Calendar from ║ +# ║ the Hubble Constant, the Fine-Structure Constant, and Pi ║ +# ║ ║ +# ║ Cycle = H₀⁻¹ × α^π / π ║ +# ║ ║ +# ╚═══════════════════════════════════════════════════════════════════════════╝ +# +# ═══════════════════════════════════════════════════════════════════════════ +# ON THE NECESSARY IMPURITY OF TRANSCENDENTAL COMPUTATION +# ═══════════════════════════════════════════════════════════════════════════ +# +# The companion script, derive_constants.sh, uses only integer arithmetic. +# This script cannot. The formula H₀⁻¹ × α^π / π requires computing +# α raised to an irrational power, which demands the transcendental +# functions e(x) and l(x) — exponential and natural logarithm. +# +# We use bc -l, which provides these functions via Taylor series expansion +# at arbitrary decimal precision. This is NOT IEEE 754 floating-point. +# bc does not use binary representation, does not silently truncate to +# 64 bits, does not harbor negative zero, and does not pretend that +# 0.1 + 0.2 equals 0.3 when it does not. bc computes in decimal, at +# whatever precision we demand, truncating only where we instruct it. +# +# The scale is set to 200 decimal places — far beyond the 155-digit +# limit of I512 and the ~46-digit physical significance of Planck time. +# The excess precision ensures that accumulated rounding in intermediate +# Taylor series terms does not contaminate the final result. +# +# When the computation is complete, the result is truncated to an integer. +# The irrational numbers — π and the transcendental α^π — are consumed +# during derivation and do not exist at runtime. Only the integer remains. +# This is not a compromise. It is the same treatment given to every other +# physical constant in the Loic Calendar: rational approximation with +# error below physical significance. +# +# ═══════════════════════════════════════════════════════════════════════════ +# USAGE +# ═══════════════════════════════════════════════════════════════════════════ +# +# ./derive_cycle.sh # Full human-readable derivation +# ./derive_cycle.sh --constant # Emit only PLANCK_PER_CYCLE +# ./derive_cycle.sh --json # Machine-readable JSON output +# ./derive_cycle.sh --help # Illuminate the path +# +# ═══════════════════════════════════════════════════════════════════════════ + +set -e + +# ═══════════════════════════════════════════════════════════════════════════════ +# +# WORKING PRECISION +# +# 200 decimal places. The universe requires ~46. We provide ~200. +# The excess is not waste; it is insurance against the accumulation +# of truncation error across dozens of Taylor series terms. +# +# ═══════════════════════════════════════════════════════════════════════════════ + +PRECISION=200 + +# ═══════════════════════════════════════════════════════════════════════════════ +# +# THE FUNDAMENTAL CONSTANTS +# +# Three axioms. Three constants. Three windows into the structure of +# the universe, through which the Loic cycle is glimpsed. +# +# ═══════════════════════════════════════════════════════════════════════════════ + +# ───────────────────────────────────────────────────────────────────────────── +# THE HUBBLE CONSTANT +# ───────────────────────────────────────────────────────────────────────────── +# +# H₀ = 67.4 km/s/Mpc +# +# The rate of cosmic expansion as measured by the Planck satellite (2018) +# through observation of the Cosmic Microwave Background — the oldest +# light in the universe, emitted 380,000 years after Creation when the +# cosmos first became transparent. +# +# A competing measurement exists: 73.0 ± 1.0 km/s/Mpc, derived from the +# local distance ladder (Cepheid variables and Type Ia supernovae). The +# discrepancy — known as the Hubble tension — is a 5σ disagreement that +# represents arguably the greatest crisis in modern cosmology. +# +# We choose 67.4. The CMB measurement peers deeper into the past than any +# other observation in the history of science. This is a calendar that +# begins at the beginning. We use the measurement that looked closest +# to Creation. +# +# The tension is documented. The choice is deliberate. If future physics +# resolves the disagreement, the constant may be revised — but the formula +# will endure. + +H0_KM_S_MPC="67.4" + +# 1 Megaparsec in meters (IAU 2012 exact definition) +# +# The parsec is defined as 648000/π AU, where 1 AU = 149,597,870,700 m +# exactly (IAU 2012 Resolution B2). The megaparsec is 10⁶ parsecs. +# +# Since the parsec definition involves π, the megaparsec in meters is +# itself irrational. We use a rational approximation to 17 significant +# figures — vastly exceeding the 3 significant figures of H₀ itself. +# The bottleneck of precision is the Hubble constant, not the unit +# conversion. + +MPC_METERS="30856775814913673000000" +# 3.0856775814913673 × 10²² meters. The 'e' notation is eschewed; +# bc does not speak exponential. + +# ───────────────────────────────────────────────────────────────────────────── +# THE FINE-STRUCTURE CONSTANT +# ───────────────────────────────────────────────────────────────────────────── +# +# α = 7.2973525643 × 10⁻³ +# +# The dimensionless coupling constant of quantum electrodynamics. +# It governs the strength of the electromagnetic interaction — how +# strongly charged particles talk to each other. Every photon emitted, +# every electron captured, every signal transmitted through copper wire +# is modulated by this number. +# +# The Whisper — "LO", transmitted from UCLA to Stanford over ARPANET — +# was an electromagnetic event. The characters were encoded as electrical +# signals, propagated through coaxial cable, decoded by transistors. +# Every stage of that transmission was governed by α. +# +# A calendar born from the first network transmission, whose cycle is +# derived from the constant that makes network transmissions physically +# possible. This is not metaphor. This is electrodynamics. +# +# CODATA 2022 recommended value: 7.2973525643(11) × 10⁻³ +# Uncertainty: ±0.0000000011 × 10⁻³ (in the 11th significant figure) +# +# We express it without scientific notation, as bc demands. + +ALPHA="0.0072973525643" + +# ───────────────────────────────────────────────────────────────────────────── +# THE PLANCK TIME RATIO (inherited from derive_constants.sh) +# ───────────────────────────────────────────────────────────────────────────── + +PLANCK_TIME_NUMERATOR="5391247" +PLANCK_TIME_DENOMINATOR="100000000000000000000000000000000000000000000000000" + +# ───────────────────────────────────────────────────────────────────────────── +# TIME UNIT DEFINITIONS (inherited) +# ───────────────────────────────────────────────────────────────────────────── + +SECONDS_PER_DAY="86400" +SECONDS_PER_JULIAN_YEAR="31557600" + +# ───────────────────────────────────────────────────────────────────────────── +# THE AGE OF THE UNIVERSE (inherited, Boltzmann encoding) +# ───────────────────────────────────────────────────────────────────────────── + +AGE_UNIVERSE_JULIAN_YEARS="13806491023" + +# ═══════════════════════════════════════════════════════════════════════════════ +# +# COMPUTATION PHASE 1 +# +# π TO 155 DECIMAL DIGITS +# +# ═══════════════════════════════════════════════════════════════════════════════ +# +# 155 decimal digits is the precision limit of I512 — the maximum number +# of decimal digits representable in a 512-bit signed integer. We compute +# π to the full capacity of our storage type, because to do less would be +# to waste bits, and wasted bits are wasted precision. +# +# The computation uses bc's arctangent function: π = 4 × arctan(1). +# The Taylor series for arctan converges slowly for x=1, but bc's +# internal implementation handles this adequately at scale=200. +# +# ───────────────────────────────────────────────────────────────────────────── +# A NOTE ON THE CANONICAL DERIVATION +# ───────────────────────────────────────────────────────────────────────────── +# +# The most elegant method for computing π is the Leibniz series: +# +# π/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - ... +# +# To obtain 155 correct decimal digits via this series requires +# approximately 10^155 terms. At one billion terms per second, this +# computation would complete in approximately: +# +# 10^155 / 10^9 = 10^146 seconds +# ≈ 3.17 × 10^138 years +# ≈ 2.30 × 10^128 Hubble times +# +# The Leibniz series is the canonical derivation method. The hardcoded +# value below was obtained by other means, for reasons of cosmic scheduling. +# ───────────────────────────────────────────────────────────────────────────── + +compute_pi() { + # bc -l provides a(x) = arctan(x) + # π = 4 × arctan(1), computed at scale=$PRECISION + PI=$(echo "scale=$PRECISION; 4 * a(1)" | bc -l) +} + +# ═══════════════════════════════════════════════════════════════════════════════ +# +# COMPUTATION PHASE 2 +# +# THE HUBBLE TIME IN SI SECONDS +# +# ═══════════════════════════════════════════════════════════════════════════════ +# +# H₀ is given in km/s/Mpc. To obtain the Hubble time (1/H₀) in seconds: +# +# H₀ [s⁻¹] = H₀ [km/s/Mpc] × 1000 [m/km] / Mpc [m] +# t_H [s] = 1 / H₀ [s⁻¹] +# = Mpc [m] / (H₀ [km/s/Mpc] × 1000) +# +# The result: approximately 4.578 × 10¹⁷ seconds, or ~14.5 billion years. +# This is close to — but not equal to — the age of the universe (13.8 Gyr). +# The near-coincidence is a deep fact about cosmological geometry. + +compute_hubble_time() { + HUBBLE_TIME_SECONDS=$(echo "scale=$PRECISION; $MPC_METERS / ($H0_KM_S_MPC * 1000)" | bc -l) +} + +# ═══════════════════════════════════════════════════════════════════════════════ +# +# COMPUTATION PHASE 3 +# +# THE HUBBLE TIME IN PLANCK UNITS +# +# ═══════════════════════════════════════════════════════════════════════════════ +# +# Convert from SI seconds to Planck times via rational arithmetic: +# +# planck_times = seconds × (1 / t_P) +# = seconds × (10^50 / 5391247) +# = seconds × PLANCK_TIME_DENOMINATOR / PLANCK_TIME_NUMERATOR +# +# We multiply first, then divide — preserving maximum precision. +# The result is approximately 8.49 × 10⁶⁰ Planck times. + +compute_hubble_planck() { + HUBBLE_TIME_PLANCK=$(echo "scale=$PRECISION; ($HUBBLE_TIME_SECONDS * $PLANCK_TIME_DENOMINATOR) / $PLANCK_TIME_NUMERATOR" | bc -l) +} + +# ═══════════════════════════════════════════════════════════════════════════════ +# +# COMPUTATION PHASE 4 +# +# α^π — THE HEART +# +# ═══════════════════════════════════════════════════════════════════════════════ +# +# Here lies the transcendental core of the derivation. +# +# α^π cannot be computed by integer arithmetic. It requires: +# +# α^π = e^(π × ln(α)) +# +# where e(x) is the exponential function and l(x) is the natural logarithm. +# Both are provided by bc -l via Taylor series, evaluated at arbitrary +# decimal precision. +# +# The result is approximately 1.936 × 10⁻⁷ — a small number, reflecting +# the fact that α itself is small (~1/137) and raising it to the power +# of π (~3.14159) attenuates it further. +# +# ───────────────────────────────────────────────────────────────────────────── +# WHY α^π AND NOT α³ +# ───────────────────────────────────────────────────────────────────────────── +# +# α³ produces a cycle of ~1,795 years. α⁴ produces ~13.1 years. Between +# them, α^π produces ~894 years — roughly half the α³ cycle. The factor +# of reduction is α^(π-3) = α^0.14159... ≈ 0.498. +# +# But the choice is not merely numerical. α³ is a rational exponent. +# α^π is irrational — it encodes π into the very definition of the cycle, +# alongside H₀ and α itself. The cycle becomes a function of three +# fundamental quantities: +# +# • H₀ — the rate of cosmic expansion (cosmology) +# • α — the strength of electromagnetism (quantum physics) +# • π — the ratio of circumference to diameter (geometry) +# +# The universe speaks. The electron couples. The circle closes. +# These three, combined, produce the rhythm of the Loic Calendar. + +compute_alpha_to_pi() { + # Step 1: Compute ln(α) + LN_ALPHA=$(echo "scale=$PRECISION; l($ALPHA)" | bc -l) + + # Step 2: Compute π × ln(α) + PI_LN_ALPHA=$(echo "scale=$PRECISION; $PI * $LN_ALPHA" | bc -l) + + # Step 3: Compute e^(π × ln(α)) = α^π + ALPHA_TO_PI=$(echo "scale=$PRECISION; e($PI_LN_ALPHA)" | bc -l) +} + +# ═══════════════════════════════════════════════════════════════════════════════ +# +# COMPUTATION PHASE 5 +# +# THE CYCLE: H₀⁻¹ × α^π / π +# +# ═══════════════════════════════════════════════════════════════════════════════ +# +# The final assembly. The Hubble time (in Planck units), multiplied by +# α^π, divided by π. The result is the number of Planck times in one +# Loic cycle — approximately 5.23 × 10⁵³. +# +# The integer truncation occurs here. The decimal portion — approximately +# 0.4 Planck times — is discarded. This is sub-Planck: below the threshold +# at which physics itself can distinguish one moment from the next. +# +# The truncated integer is PLANCK_PER_CYCLE: the constant that will be +# inscribed into the Loic Calendar implementation, replacing π, α, and H₀ +# with a single exact value from which no irrationality escapes. + +compute_cycle() { + # Compute the full-precision cycle in Planck times + CYCLE_PLANCK_FULL=$(echo "scale=$PRECISION; ($HUBBLE_TIME_PLANCK * $ALPHA_TO_PI) / $PI" | bc -l) + + # Truncate to integer (floor) + # bc's scale=0 division by 1 achieves floor truncation for positive values + PLANCK_PER_CYCLE=$(echo "scale=0; $CYCLE_PLANCK_FULL / 1" | bc) + + # Compute the truncation error for documentation + TRUNCATION_ERROR=$(echo "scale=$PRECISION; $CYCLE_PLANCK_FULL - $PLANCK_PER_CYCLE" | bc -l) +} + +# ═══════════════════════════════════════════════════════════════════════════════ +# +# COMPUTATION PHASE 6 +# +# HUMAN-SCALE CONVERSIONS +# +# ═══════════════════════════════════════════════════════════════════════════════ + +compute_human_units() { + # Cycle in SI seconds + CYCLE_SECONDS=$(echo "scale=$PRECISION; ($PLANCK_PER_CYCLE * $PLANCK_TIME_NUMERATOR) / $PLANCK_TIME_DENOMINATOR" | bc -l) + + # Cycle in days + CYCLE_DAYS=$(echo "scale=$PRECISION; $CYCLE_SECONDS / $SECONDS_PER_DAY" | bc -l) + + # Cycle in Julian years + CYCLE_YEARS=$(echo "scale=$PRECISION; $CYCLE_SECONDS / $SECONDS_PER_JULIAN_YEAR" | bc -l) +} + +# ═══════════════════════════════════════════════════════════════════════════════ +# +# COMPUTATION PHASE 7 +# +# COSMOLOGICAL CONTEXT +# +# ═══════════════════════════════════════════════════════════════════════════════ + +compute_cosmological_context() { + # Age of the universe in seconds + AGE_UNIVERSE_SECONDS=$(echo "$AGE_UNIVERSE_JULIAN_YEARS * $SECONDS_PER_JULIAN_YEAR" | bc) + + # Age in Planck times + AGE_UNIVERSE_PLANCK=$(echo "scale=0; ($AGE_UNIVERSE_SECONDS * $PLANCK_TIME_DENOMINATOR) / $PLANCK_TIME_NUMERATOR" | bc) + + # Completed cycles since Creation + CYCLES_SINCE_CREATION=$(echo "scale=0; $AGE_UNIVERSE_PLANCK / $PLANCK_PER_CYCLE" | bc) + + # Precise ratio (for fractional position) + CYCLES_SINCE_CREATION_PRECISE=$(echo "scale=20; $AGE_UNIVERSE_PLANCK / $PLANCK_PER_CYCLE" | bc -l) + + # Position within current cycle (in Planck times) + POSITION_IN_CYCLE=$(echo "$AGE_UNIVERSE_PLANCK % $PLANCK_PER_CYCLE" | bc) + + # Fraction through current cycle + CYCLE_FRACTION=$(echo "scale=20; $POSITION_IN_CYCLE / $PLANCK_PER_CYCLE" | bc -l) + + # Position in years + POSITION_YEARS=$(echo "scale=10; ($POSITION_IN_CYCLE * $PLANCK_TIME_NUMERATOR) / ($PLANCK_TIME_DENOMINATOR * $SECONDS_PER_JULIAN_YEAR)" | bc -l) +} + +# ═══════════════════════════════════════════════════════════════════════════════ +# +# COMPUTATION PHASE 8 +# +# ANNIHILATION AND CREATION +# +# ═══════════════════════════════════════════════════════════════════════════════ + +compute_boundaries() { + ANNIHILATION_PLANCK=$(echo "2^511 - 1" | bc | tr -d '\\\n') + CREATION_PLANCK_POS=$(echo "($AGE_UNIVERSE_SECONDS * $PLANCK_TIME_DENOMINATOR) / $PLANCK_TIME_NUMERATOR" | bc) + CREATION_PLANCK="-$CREATION_PLANCK_POS" + + # Total representable span + TOTAL_SPAN=$(echo "$ANNIHILATION_PLANCK + $CREATION_PLANCK_POS" | bc) + + # Cycles in total span + TOTAL_CYCLES=$(echo "scale=0; $TOTAL_SPAN / $PLANCK_PER_CYCLE" | bc) +} + +# ═══════════════════════════════════════════════════════════════════════════════ +# +# OUTPUT: HUMAN FORM +# +# ═══════════════════════════════════════════════════════════════════════════════ + +output_human() { + cat << 'HEADER' +╔═══════════════════════════════════════════════════════════════════════════════╗ +║ LOIC CYCLE DERIVATION ║ +║ ║ +║ Cycle = H₀⁻¹ × α^π / π ║ +║ ║ +║ The Hubble time, attenuated through the electromagnetic coupling strength ║ +║ raised to the most fundamental irrational power, divided by that same ║ +║ irrational — the quantum of computation in Planck units. ║ +║ ║ +║ Computed using POSIX bc at 200 decimal places of working precision. ║ +║ No IEEE 754 floating-point arithmetic was used or contemplated. ║ +╚═══════════════════════════════════════════════════════════════════════════════╝ + +HEADER + + echo "═══════════════════════════════════════════════════════════════════════════════" + echo " INPUT CONSTANTS" + echo "═══════════════════════════════════════════════════════════════════════════════" + echo "" + echo " H₀ (Hubble constant) = $H0_KM_S_MPC km/s/Mpc" + echo " Source: Planck 2018 CMB (the measurement that looked closest to Creation)" + echo " Tension: Local distance ladder gives 73.0 ± 1.0 km/s/Mpc" + echo "" + echo " α (fine-structure constant) = $ALPHA" + echo " Source: CODATA 2022 recommended value" + echo " Significance: governs electromagnetic coupling — why The Whisper was" + echo " physically possible" + echo "" + echo " t_P (Planck time) = $PLANCK_TIME_NUMERATOR / 10^50 seconds" + echo " The quantum of duration" + echo "" + + echo "═══════════════════════════════════════════════════════════════════════════════" + echo " INTERMEDIATE VALUES" + echo "═══════════════════════════════════════════════════════════════════════════════" + echo "" + echo " π (to 155 decimal digits — the I512 precision limit):" + # Format π with line wrapping for readability + echo " $PI" | fold -w 74 | sed 's/^/ /' + echo "" + echo " Hubble time (1/H₀):" + echo " In seconds: $(echo "$HUBBLE_TIME_SECONDS" | head -c 20)... × 10^17" + echo " In Planck times: $(echo "$HUBBLE_TIME_PLANCK" | head -c 20)... × 10^60" + echo "" + echo " ln(α): $LN_ALPHA" | head -c 80 + echo "..." + echo " π·ln(α): $PI_LN_ALPHA" | head -c 80 + echo "..." + echo " α^π: $ALPHA_TO_PI" | head -c 80 + echo "..." + echo "" + + echo "═══════════════════════════════════════════════════════════════════════════════" + echo " THE CYCLE" + echo "═══════════════════════════════════════════════════════════════════════════════" + echo "" + echo " Formula: H₀⁻¹ × α^π / π" + echo "" + echo " PLANCK_PER_CYCLE =" + echo " $PLANCK_PER_CYCLE" + echo "" + echo " Digits: $(echo -n "$PLANCK_PER_CYCLE" | wc -c)" + echo "" + echo " Truncation error: $TRUNCATION_ERROR Planck times" + echo " (< 1 Planck time — sub-Planck, below physical significance)" + echo "" + echo " In human units:" + echo " Seconds: $(echo "$CYCLE_SECONDS" | head -c 20)..." + echo " Days: $(echo "$CYCLE_DAYS" | head -c 20)..." + echo " Julian years: $(echo "$CYCLE_YEARS" | head -c 20)..." + echo "" + + echo "═══════════════════════════════════════════════════════════════════════════════" + echo " COSMOLOGICAL CONTEXT" + echo "═══════════════════════════════════════════════════════════════════════════════" + echo "" + echo " Age of universe: ~13.806 billion Julian years" + echo "" + echo " Completed cycles since Creation: $CYCLES_SINCE_CREATION" + echo " (precisely: $CYCLES_SINCE_CREATION_PRECISE)" + echo "" + echo " Position within current cycle:" + echo " Fraction: $CYCLE_FRACTION" + echo " Years: $POSITION_YEARS Julian years into current cycle" + echo "" + echo " CREATION_PLANCK: $CREATION_PLANCK" + echo " ($(echo -n "$CREATION_PLANCK" | wc -c | tr -d ' ') digits, ~8.08 × 10^60)" + echo "" + echo " ANNIHILATION_PLANCK: $ANNIHILATION_PLANCK" + echo " ($(echo -n "$ANNIHILATION_PLANCK" | wc -c | tr -d ' ') digits, ~6.7 × 10^153)" + echo "" + echo " Total cycles in representable span: $TOTAL_CYCLES" + echo " ($(echo -n "$TOTAL_CYCLES" | wc -c | tr -d ' ') digits)" + echo "" + + echo "═══════════════════════════════════════════════════════════════════════════════" + echo " THE FORMULA, FOR THE RECORD" + echo "═══════════════════════════════════════════════════════════════════════════════" + echo "" + echo " PLANCK_PER_CYCLE = floor( (Mpc_m / (H₀ × 1000)) × (10^50 / t_P_num) × α^π / π )" + echo "" + echo " Where:" + echo " Mpc_m = $MPC_METERS (1 Megaparsec in meters)" + echo " H₀ = $H0_KM_S_MPC km/s/Mpc (Planck 2018 CMB)" + echo " t_P_num = $PLANCK_TIME_NUMERATOR (Planck time numerator)" + echo " 10^50 = Planck time denominator" + echo " α = $ALPHA (CODATA 2022)" + echo " π = 3.14159265358979... (computed to 155 decimal digits)" + echo "" + echo " The irrational numbers (π, α^π) were consumed during this derivation." + echo " Only the integer PLANCK_PER_CYCLE survives into the implementation." + echo " No irrationality escapes into runtime." + echo "" + + cat << 'FOOTER' +═══════════════════════════════════════════════════════════════════════════════ + VERIFICATION NOTES +═══════════════════════════════════════════════════════════════════════════════ + + This constant should be independently verified using at least one other + arbitrary-precision computation system (e.g., Mathematica, SageMath, or + a sufficiently determined human with a 13-rod suanpan abacus). + + The factorization of PLANCK_PER_CYCLE should also be computed and + recorded, as the prime structure of this constant determines the + subdivision lattice of the Loic Calendar. + +═══════════════════════════════════════════════════════════════════════════════ +FOOTER +} + +# ═══════════════════════════════════════════════════════════════════════════════ +# +# OUTPUT: MACHINE FORM +# +# ═══════════════════════════════════════════════════════════════════════════════ + +output_json() { + cat << EOF +{ + "formula": "H0_inverse * alpha_to_pi / pi", + "inputs": { + "H0_km_s_Mpc": "$H0_KM_S_MPC", + "H0_source": "Planck 2018 CMB", + "alpha": "$ALPHA", + "alpha_source": "CODATA 2022", + "Mpc_meters": "$MPC_METERS", + "PLANCK_TIME_NUMERATOR": "$PLANCK_TIME_NUMERATOR", + "PLANCK_TIME_DENOMINATOR": "$PLANCK_TIME_DENOMINATOR", + "working_precision_digits": $PRECISION + }, + "result": { + "PLANCK_PER_CYCLE": "$PLANCK_PER_CYCLE", + "cycle_seconds": "$(echo "$CYCLE_SECONDS" | head -c 30)", + "cycle_days": "$(echo "$CYCLE_DAYS" | head -c 20)", + "cycle_julian_years": "$(echo "$CYCLE_YEARS" | head -c 20)", + "truncation_error_planck": "$(echo "$TRUNCATION_ERROR" | head -c 20)", + "digit_count": $(echo -n "$PLANCK_PER_CYCLE" | wc -c | tr -d ' ') + }, + "cosmology": { + "cycles_since_creation": "$CYCLES_SINCE_CREATION", + "cycles_since_creation_precise": "$CYCLES_SINCE_CREATION_PRECISE", + "current_cycle_fraction": "$CYCLE_FRACTION", + "current_cycle_years": "$(echo "$POSITION_YEARS" | head -c 20)", + "CREATION_PLANCK": "$CREATION_PLANCK", + "ANNIHILATION_PLANCK": "$ANNIHILATION_PLANCK", + "total_representable_cycles": "$TOTAL_CYCLES" + }, + "derivation": { + "method": "bc_arbitrary_precision_decimal", + "ieee754_used": false, + "pi_digits_computed": 155, + "note": "Irrational numbers consumed during derivation. Only integer survives." + } +} +EOF +} + +# ═══════════════════════════════════════════════════════════════════════════════ +# +# OUTPUT: CONSTANT ONLY +# +# For piping into other tools. Just the number. Nothing else. +# +# ═══════════════════════════════════════════════════════════════════════════════ + +output_constant() { + echo "$PLANCK_PER_CYCLE" +} + +# ═══════════════════════════════════════════════════════════════════════════════ +# +# THE MAIN RITUAL +# +# ═══════════════════════════════════════════════════════════════════════════════ + +main() { + mode="human" + + for arg in "$@"; do + case "$arg" in + --json) mode="json" ;; + --constant) mode="constant" ;; + --help|-h) + cat << 'HELP' +╔═══════════════════════════════════════════════════════════════════════════════╗ +║ LOIC CYCLE DERIVATION ORACLE ║ +╚═══════════════════════════════════════════════════════════════════════════════╝ + +USAGE: + ./derive_cycle.sh [OPTIONS] + +OPTIONS: + (none) Full human-readable derivation with cosmological context + --constant Emit only the PLANCK_PER_CYCLE integer (for piping) + --json Machine-readable JSON output + --help, -h Illuminate the path + +DESCRIPTION: + Derives the Loic Calendar cycle constant from first principles: + + Cycle = H₀⁻¹ × α^π / π + + Where: + H₀ = 67.4 km/s/Mpc (Planck 2018 CMB) + α = 7.2973525643e-3 (CODATA 2022 fine-structure constant) + π = 3.14159... (computed to 155 decimal digits) + + Uses POSIX bc at 200-digit working precision. No IEEE 754 floating-point. + The result is truncated to an integer with sub-Planck error. + +PHILOSOPHY: + "The universe speaks. The electron couples. The circle closes. + These three — H₀, α, π — combined, produce the rhythm of the + Loic Calendar. The irrational numbers are consumed during derivation. + Only the integer survives." + +HELP + exit 0 + ;; + *) + echo "Unknown option: $arg" >&2 + exit 1 + ;; + esac + done + + # ─────────────────────────────────────────────────────────────────────── + # THE COMPUTATION CASCADE + # ─────────────────────────────────────────────────────────────────────── + # Each phase depends on the previous. The order is immutable. + + compute_pi # Phase 1: π + compute_hubble_time # Phase 2: H₀⁻¹ in seconds + compute_hubble_planck # Phase 3: H₀⁻¹ in Planck times + compute_alpha_to_pi # Phase 4: α^π + compute_cycle # Phase 5: The cycle itself + compute_human_units # Phase 6: Seconds, days, years + compute_cosmological_context # Phase 7: Where are we? + compute_boundaries # Phase 8: Creation and Annihilation + + # ─────────────────────────────────────────────────────────────────────── + # THE OUTPUT + # ─────────────────────────────────────────────────────────────────────── + + case "$mode" in + human) output_human ;; + json) output_json ;; + constant) output_constant ;; + esac +} + +# ═══════════════════════════════════════════════════════════════════════════════ +# BEGIN EXECUTION +# ═══════════════════════════════════════════════════════════════════════════════ + +main "$@" \ No newline at end of file