Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/patches/7c575f8d7a229791 # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aienux#415 (code only) closed derived `7c575f8d7a229791` #415 Imported from GitHub aien-dev/aienux#415 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `801b248acbcc53e65e9f6308171cdbf3e4b438f5` · Head `68a88822713d967e55b9fe97b58c8c34cc858803` github-advanced-security[bot] commented on `native/kernel/svc/allen_reply.c` line 230 on 2026-10-18 15:33 UTC ## CodeQL / Array offset used before range check This use of offset 'n' should follow the range check . Show more details github-advanced-security[bot] commented on `native/kernel/svc/allen_reply.c` line 230 on 2026-10-18 15:33 UTC ## CodeQL / Array offset used before range check This use of offset 'n' should follow the range check . Show more details github-advanced-security[bot] commented on `native/kernel/svc/allen_reply.c` line 268 on 2026-10-18 15:33 UTC ## CodeQL / Array offset used before range check This use of offset 'n' should follow the range check . Show more details github-advanced-security[bot] commented on `native/kernel/svc/allen_reply.c` line 268 on 2026-10-18 15:34 UTC ## CodeQL / Array offset used before range check This use of offset 'n' should follow the range check . Show more details github-advanced-security[bot] commented on `native/kernel/ui/allen_ui.c` line 141 on 2026-10-18 15:34 UTC ## CodeQL / Array offset used before range check This use of offset 'n' should follow the range check . Show more details github-advanced-security[bot] commented on `native/kernel/ui/tests/allen_ui_test.c` line 81 on 2026-10-18 15:34 UTC ## CodeQL / Multiplication result converted to larger type Multiplication result may overflow 'unsigned int' before it is converted to 'unsigned long'. Show more details github-advanced-security[bot] commented on `native/kernel/ui/tests/allen_ui_test.c` line 113 on 2026-10-18 15:34 UTC ## CodeQL / File created without restricting permissions A file may be created here with mode 0666, which would make it world-writable. Show more details github-advanced-security[bot] commented on `native/kernel/ui/tests/chirp_test.c` line 52 on 2026-10-18 15:34 UTC ## CodeQL / File created without restricting permissions A file may be created here with mode 0666, which would make it world-writable. Show more details github-advanced-security[bot] reviewed (COMMENTED) on 2026-10-18 15:34 UTC drakestapleton reviewed (COMMENTED) on 2026-10-30 11:18 UTC Triage: stale (`needs-rebase`; stacked on #414; merge conflicts; appears consolidated into #473) - Memory safety: the polled xHCI driver plus USB hub handling parses device descriptors from the bus; check that descriptor lengths and hub port counts are bounded before indexing. - Hardware: needs an iMac serial log (`keyboard_line:` / `keyboard: done`) and the keyboard model. To be merge-ready: decide #473 vs this stack, rebase, and attach evidence. ### Fetch it A git bundle of the pull request's head, 268627 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aienux/patches/7c575f8d7a229791.bundle -o 7c575f8d7a229791.bundle git fetch 7c575f8d7a229791.bundle refs/pull/415/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aienux 415 68a88822713d967e55b9fe97b58c8c34cc858803 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aienux","number":415,"url":"https://github.com/aien-dev/aienux/pull/415","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:23Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index d73a3918..c2c3920a 100644 --- a/.crumb +++ b/.crumb @@ -22,7 +22,7 @@ "children": [ { "digest": "b7d58d76e7dacaa887051e8c2d64e2eaef683c9ba82c03e073002f6ddd920239", - "last_commit": "e7244dd", + "last_commit": "45d8f79", "name": "crates", "purpose": "Directory crates. Purpose not yet described by a human." }, @@ -33,14 +33,14 @@ "purpose": "Directory docs. Purpose not yet described by a human." }, { - "digest": "296167be2131bbca5563d7d63a5b97326a6bb05619fc57b38a3ce1aa05f15de6", - "last_commit": "8b664a5", + "digest": "191a912e7f36b80302d1c07a02b8e966094383c68ec594be4dcea46b18948c08", + "last_commit": "792181f", "name": "native", "purpose": "Directory native. Purpose not yet described by a human." }, { - "digest": "da2a96be8a25fde997c2d63599b68c250193223946f25c812a27c6794890f83a", - "last_commit": "8b664a5", + "digest": "77ac3f146e84c4b49982d46d81c24d3feb723b1e17bfcf5c5876c9dc29fe0807", + "last_commit": "792181f", "name": "scripts", "purpose": "Directory scripts. Purpose not yet described by a human." }, @@ -51,15 +51,15 @@ "purpose": "First-party host artifact preparation tools" } ], - "children_root": "sha256:544320155585a02288e2b244a75711d126483f08b7fb48b04227838dcf8a6393", - "compiled_at": "2026-10-31T02:23:06Z", + "children_root": "sha256:b6b0ae8664b1e6b59a3f43b25984fac0b7eb4d6c1b0e30afd2061a22f7f0e71c", + "compiled_at": "2026-10-31T03:18:52Z", "compiler": "crumb-compile/1", - "digest": "sha256:9f994c08a33d25a77fdf45553a6a6cfa23b2787d466abed244f42266fbf31dfc", + "digest": "sha256:39eefcc3a6ab400f7a1ab0042fb526de382831c6cf1449d3313ad898586a6d7f", "evidence_files": 274, "evidence_root": "sha256:af014a4ed8f6fe759fc5809807fb47578d3410811b522d9f65d749382b029802", - "files": 3693, - "generated_at_commit": "e7244ddf3bd8207f6e2e255281aeed369ba669e7", - "source_tree": "sha256:90a8815251ab88df85b1595ebae0e2ba9f9b1b4ce586b9317f059e2ba5140b7c" + "files": 3724, + "generated_at_commit": "792181fa4d7ded679d92711bb9a8d31e87c42061", + "source_tree": "sha256:c29a72b62a026bcd3c86841857ae3ce0cf9a99a46c20bd1a0832c8f6130d47f1" }, "owner_lane": "", "provenance": { diff --git a/native/.crumb b/native/.crumb index 33a630d1..c9466339 100644 --- a/native/.crumb +++ b/native/.crumb @@ -50,80 +50,80 @@ "children": [ { "digest": "72ee4e94f3dc99d79ea4eb3bf619ad645c0b76d7009d1883e59adfbfce9c8ac2", - "last_commit": "2c9c8b50", + "last_commit": "09e59a8", "name": "argus", "purpose": "Directory native/argus. Purpose not yet described by a human." }, { "digest": "5187cf88f03271fb2a89fd18d0a97212ae419491d9bd510732bdbe54a0ccf263", - "last_commit": "2c9c8b50", + "last_commit": "52dcb5d", "name": "boot", "purpose": "Directory native/boot. Purpose not yet described by a human." }, { "digest": "1b5414c184e37d4d943e7979db3d82f1441d6004bb9b5c379a4e4e39381fe7fd", - "last_commit": "f45d00ad", + "last_commit": "7db773a", "name": "capability", "purpose": "Directory native/capability. Purpose not yet described by a human." }, { "digest": "ec6a4295568339a6dea0df513d23cf7a28a90d07bee2cd8f93a7417b48ff7871", - "last_commit": "2c9c8b50", + "last_commit": "7db773a", "name": "crypto", "purpose": "Directory native/crypto. Purpose not yet described by a human." }, { "digest": "43e1cf9e246a9cdfca6b1147381ad071e1cffaf408bb58d3e09b7001e7b0eb5c", - "last_commit": "b5e72686", + "last_commit": "7db773a", "name": "disk", "purpose": "Directory native/disk. Purpose not yet described by a human." }, { - "digest": "dff38314f5a4663218092ed0e56904bcbb57f5cdec4e1b7d4cdcdc4845dc2fe0", - "last_commit": "2c149f76", + "digest": "4b16282d4d64d2a986a079db5c29a238106dea5f9cd8611d5b4faf22f1c1248e", + "last_commit": "52dcb5d", "name": "kernel", "purpose": "Directory native/kernel. Purpose not yet described by a human." }, { "digest": "b9588f7026aaa3fbf7777f5c10d90a1c915cc301be98be5081d3d66106cf77c8", - "last_commit": "2c9c8b50", + "last_commit": "7db773a", "name": "m5", "purpose": "Directory native/m5. Purpose not yet described by a human." }, { "digest": "b0c2410bb450a0bf6156e064185b024b622fd844e87d7acd476df10c7af63cf6", - "last_commit": "dc9a9961", + "last_commit": "7db773a", "name": "net", "purpose": "Directory native/net. Purpose not yet described by a human." }, { "digest": "f3c7ee4f18f768fa9964c123e07f076c544c58c0966a8a5e9571b0397bf57b06", - "last_commit": "c93a5f57", + "last_commit": "", "name": "omega", "purpose": "Seeded Omega native modules" }, { "digest": "6f0bf10c76df492d27ae642792476c1138bc73f0d897b3ddca04605ac07b4268", - "last_commit": "2c9c8b50", + "last_commit": "7db773a", "name": "sig", "purpose": "Directory native/sig. Purpose not yet described by a human." }, { "digest": "e125172a18437b662edf303f4b9615bb791f5e7d2ed94192033823185e7d40e1", - "last_commit": "2c9c8b50", + "last_commit": "e5e8f08", "name": "store", "purpose": "Directory native/store. Purpose not yet described by a human." } ], - "children_root": "sha256:5b227b35bd1a67e65dce28d5be0308c90452bb36cae33ad98f6efe7313cc1f68", - "compiled_at": "2026-10-30T22:19:45Z", + "children_root": "sha256:c202ba995d4bfa215379bc98ef74e867e8293fc07e1a876dcf7b0f3320f120b4", + "compiled_at": "2026-10-31T02:42:46Z", "compiler": "crumb-compile/1", - "digest": "sha256:296167be2131bbca5563d7d63a5b97326a6bb05619fc57b38a3ce1aa05f15de6", + "digest": "sha256:191a912e7f36b80302d1c07a02b8e966094383c68ec594be4dcea46b18948c08", "evidence_files": 24, "evidence_root": "sha256:ecc7ccf2e924c221a5bac1d91e23b13d8f3c8d78c2a893a882ed7ca5e88d855d", - "files": 741, - "generated_at_commit": "2c149f764d40c9b15fc1a1c946fe1aa188d0879e", - "source_tree": "sha256:dfda991de2f45b21220a58ecf0111d034daf175ea3ae07eb5e6e1779f87a18c1" + "files": 767, + "generated_at_commit": "47faeddadfb49c9e84f9d1058547f7bb0ef45d1d", + "source_tree": "sha256:aaf8d32c5e9316d18e1b95c725c4352e3b82cb467a2f8eb74c473cd9148ecd5b" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/.crumb b/native/kernel/.crumb index f7a60903..d9129819 100644 --- a/native/kernel/.crumb +++ b/native/kernel/.crumb @@ -46,68 +46,68 @@ "children": [ { "digest": "aa16ee3dab6c71bf912686eef4e763743d26883addadc7ca4371eb8545b513aa", - "last_commit": "9e48cf84", + "last_commit": "2529bc0", "name": "arch", "purpose": "Directory native/kernel/arch. Purpose not yet described by a human." }, { "digest": "de009659b554bfb75b093c0b62567ed58238731e3ce4c457008fcc2be1488b89", - "last_commit": "f45d00ad", + "last_commit": "6ad9190", "name": "artifact", "purpose": "Directory native/kernel/artifact. Purpose not yet described by a human." }, { - "digest": "3448d48e8498c2a3409e69923020b57bf1146bd1d5913e70f7559cefd9d005bd", - "last_commit": "2c149f76", + "digest": "ed58fce3de8581101263e4241f336cc14ea58cd50263fd4bbb5e9ca9bb6639eb", + "last_commit": "0f6ef82", "name": "core", "purpose": "Directory native/kernel/core. Purpose not yet described by a human." }, { - "digest": "bef70d40dabe6ab1d9c94b1ca2134346bd79827441a451fc387b79d00a23caec", - "last_commit": "4c25c6ce", + "digest": "f4d9f6e374a17bdc6bca5564d5e01d32fc4cfb0bcfd33bc1876c26184d74cf06", + "last_commit": "4eb74bf", "name": "dev", "purpose": "Directory native/kernel/dev. Purpose not yet described by a human." }, { "digest": "54cee35b405dc1c90f62d4d227ed172142abfd4917e720708ba0b83b94b9376e", - "last_commit": "f45d00ad", + "last_commit": "0735543", "name": "include", "purpose": "Directory native/kernel/include. Purpose not yet described by a human." }, { "digest": "c7dc6acbe30f21ef0d3983d31b212f89ff23ae6e56862a2718d98fd28c76649a", - "last_commit": "f45d00ad", + "last_commit": "2bc7146", "name": "mm", "purpose": "Directory native/kernel/mm. Purpose not yet described by a human." }, { - "digest": "e0a0bed1e95c876ea3d0a2dc136b94d3744491e72d5809c11de6ff787b21fd0a", - "last_commit": "ce2ce2ab", + "digest": "ef3844c1228b5fc5b740f944b4a3d2539fc4a816bf5402fa47fce6b50850d543", + "last_commit": "4eb74bf", "name": "svc", "purpose": "Directory native/kernel/svc. Purpose not yet described by a human." }, { - "digest": "59c0ca771d489fe85c31391d5c8c2b70da110f5f13f4c15b9ba126a41ed3e5fa", - "last_commit": "2c149f76", + "digest": "2ca38317e04e90ee53c0a97be152b07b62e80b4b32db8bbe6b8aa3cb60aa3900", + "last_commit": "7ef5916", "name": "tests", "purpose": "Directory native/kernel/tests. Purpose not yet described by a human." }, { - "digest": "e2b20996fe1250a8288abeb0e61cd9635e6da541384c5b5ba564c5f528e2a5f8", - "last_commit": "4c25c6ce", + "digest": "1dd8ed2150cfa3709d98eed188288b25edc8d94711ea36b4b846fe66b9ab224b", + "last_commit": "52dcb5d", "name": "tools", "purpose": "Hosted (Linux-built) checkers for the native kernel, run by `make -C native/kernel test`; nothin" } ], - "children_root": "sha256:1633084cdb6ab386a5783ff4b09e6f9b4fe268e30108f619dff7d835a10f49b8", - "compiled_at": "2026-10-30T22:19:45Z", + "children_root": "sha256:121c5932c956df51a50824f36ee65f951f60dc742546f740c546dffe17db1dcc", + "compiled_at": "2026-10-31T02:42:46Z", "compiler": "crumb-compile/1", - "digest": "sha256:dff38314f5a4663218092ed0e56904bcbb57f5cdec4e1b7d4cdcdc4845dc2fe0", + "digest": "sha256:4b16282d4d64d2a986a079db5c29a238106dea5f9cd8611d5b4faf22f1c1248e", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 486, - "generated_at_commit": "2c149f764d40c9b15fc1a1c946fe1aa188d0879e", - "source_tree": "sha256:86cbe2a637b3f6d8e0dbfce7b904824c250a8dacd8eb62d4b3b487ad5093a216" + "files": 512, + "generated_at_commit": "47faeddadfb49c9e84f9d1058547f7bb0ef45d1d", + "source_tree": "sha256:e0a7fb7d6be67f260d4fd9b646d5f7cdf9e8f12f0a5408f22b05797bee043c40" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/Makefile b/native/kernel/Makefile index 89488222..7c9cc971 100644 --- a/native/kernel/Makefile +++ b/native/kernel/Makefile @@ -2558,13 +2558,16 @@ $(IMACDIAG_EFI): $(IMACDIAG_ELF) @echo "built $@ (commit $(AIENOS_COMMIT))" imac-diag: $(IMACDIAG_EFI) -# ---- IMACKERN.EFI: AIENOS-IMAC-KERNEL-0, the C kernel core on x86_64 (2017 iMac) ---- +# ---- IMACKERN.EFI: AIENOS-KERNEL-0, the C kernel core on x86_64 (2017 iMac) ---- # x86/efi_x86.c (stub: GOP, RSDP, memory map, ExitBootServices, CHANDOF3) + x86/kmain_x86.c # (GDT/TSS/IDT, own page tables, guard page, HPET-timed TSC, local APIC timer, ACPI S5) # + x86/pci_x86.c (PCI walk; AHCI via x86/ahci_x86.c and NVMe via ../disk/disk_nvme.c, both # read-only, GPT checked by dev/disk_part.c; a look at the Ethernet chip) + x86/smp_x86.S -# (secondary cores started and parked) + x86/tg3_x86.c (BCM57766 Ethernet: link detection; no -# transmit in the default image) +# (secondary cores started and parked) + x86/xhci_x86.c (USB boot keyboard, polled, hubs; key +# decode and line editor from dev/usb_hid.c) + x86/tg3_x86.c (BCM57766 Ethernet: link detection; no +# transmit in the default image) + ui/allen_ui.c, ui/allen_font.c (Allen's window on the screen, drawn +# with its own stroke typeface; ui/night.c, the night sky of the startup, and ui/mind.c, Allen's presence, on ui/paint.c; +# drawn by the secondary cores) + svc/allen_reply.c (Allen's first local answers) # + x86/trap.S + x86/console_x86.c (COM1 when present, GOP framebuffer), on the # arch-neutral core: fbcon, fmt, acpi, handoff_check, frames, heap. Same toolchain and PE # header as IMACDIAG. Copy to a FAT stick as EFI/BOOT/BOOTX64.EFI. @@ -2573,7 +2576,7 @@ imac-diag: $(IMACDIAG_EFI) # make imac-kernel CK_X86_REPORT=1 -> $(OUT)/IMACKERN-LAB.EFI (own object dir) # adds x86/report_x86.c + ../../net/aienos_net.c and tg3 transmit (-DCK_X86_REPORT=1): during the # hold it broadcasts only allowlisted console lines (ck_x86_report_filter, never the raw console) -# as UDP to port 47031, header "AIENOS-IMAC-REPORT v=2 auth=none": UNAUTHENTICATED, never a +# as UDP to port 47031, header "AIENOS-REPORT v=2 auth=none": UNAUTHENTICATED, never a # receipt, evidence or a command. Host test scripts/ck_imac_report_test.sh, receiver # tools/ck_imac_report_listen.c. The default image, and any resident or service (ALLEN) build, # must not contain it: the link step below fails a default image that has a report symbol. @@ -2589,14 +2592,18 @@ else $(error CK_X86_REPORT must be 0 (default) or 1 (lab-only network report)) endif IMACKERN_ELF := $(IMACKERN_DIR)/imackern.elf -IMACKERN_CFLAGS := $(X86CFLAGS) -I$(KDIR)/include -I$(KDIR)/mm -I$(KDIR)/dev -I$(NATIVE)/disk -I$(NATIVE)/net +IMACKERN_CFLAGS := $(X86CFLAGS) -I$(KDIR)/include -I$(KDIR)/mm -I$(KDIR)/dev -I$(NATIVE)/disk -I$(NATIVE)/net \ + -I$(NATIVE)/argus IMACKERN_OBJS := $(IMACKERN_DIR)/efi_entry_x86_64.o $(IMACKERN_DIR)/efi_x86.o $(IMACKERN_DIR)/efi_gop.o \ $(IMACKERN_DIR)/kmain_x86.o $(IMACKERN_DIR)/console_x86.o $(IMACKERN_DIR)/trap.o \ $(IMACKERN_DIR)/fbcon.o $(IMACKERN_DIR)/fmt.o $(IMACKERN_DIR)/acpi.o $(IMACKERN_DIR)/handoff_check.o \ $(IMACKERN_DIR)/frames.o $(IMACKERN_DIR)/heap.o $(IMACKERN_DIR)/libc_min.o \ $(IMACKERN_DIR)/ahci_x86.o $(IMACKERN_DIR)/disk_part.o $(IMACKERN_DIR)/disk.o \ $(IMACKERN_DIR)/pci_x86.o $(IMACKERN_DIR)/smp_x86.o $(IMACKERN_DIR)/disk_nvme.o \ - $(IMACKERN_DIR)/tg3_x86.o + $(IMACKERN_DIR)/tg3_x86.o $(IMACKERN_DIR)/xhci_x86.o $(IMACKERN_DIR)/hda_x86.o $(IMACKERN_DIR)/usb_hid.o $(IMACKERN_DIR)/sha256.o \ + $(IMACKERN_DIR)/allen_ui.o $(IMACKERN_DIR)/allen_font.o $(IMACKERN_DIR)/allen_reply.o \ + $(IMACKERN_DIR)/paint.o $(IMACKERN_DIR)/night.o $(IMACKERN_DIR)/mind.o $(IMACKERN_DIR)/chirp.o \ + $(IMACKERN_DIR)/allen_memory.o $(IMACKERN_DIR)/allen_notes.o $(IMACKERN_DIR)/gpt_add.o $(IMACKERN_DIR)/memory_x86.o IMACKERN_REPORT_OBJS := $(IMACKERN_DIR)/report_x86.o $(IMACKERN_DIR)/aienos_net.o # Symbols only the lab image may contain; the default image is checked for them after linking. IMACKERN_REPORT_SYMS := ck_x86_report_hold|ck_x86_report_frame|ck_x86_report_filter|ck_x86_report_parts|ck_x86_tg3_send|ck_x86_tg3_drain|net_udp_build @@ -2608,7 +2615,7 @@ IMACKERN_HDRS := $(X86K)/x86.h $(BOOT)/handoff.h $(BOOT)/efi.h $(KDIR)/core/ck_i $(IMACKERN_DIR)/efi_entry_x86_64.o: $(BOOT)/efi_entry_x86_64.S $(IMACKERN_DIR)/efi_x86.o: $(X86K)/efi_x86.c $(IMACKERN_HDRS) $(IMACKERN_DIR)/efi_gop.o: $(BOOT)/efi_gop.c $(IMACKERN_HDRS) -$(IMACKERN_DIR)/kmain_x86.o: $(X86K)/kmain_x86.c $(IMACKERN_HDRS) $(KDIR)/core/handoff_check.h $(KDIR)/mm/frames.h $(KDIR)/mm/heap.h $(OUT)/commit.stamp +$(IMACKERN_DIR)/kmain_x86.o: $(X86K)/kmain_x86.c $(IMACKERN_HDRS) $(KDIR)/core/handoff_check.h $(KDIR)/mm/frames.h $(KDIR)/mm/heap.h $(KDIR)/ui/allen_ui.h $(KDIR)/svc/allen_reply.h $(OUT)/commit.stamp $(IMACKERN_DIR)/console_x86.o: $(X86K)/console_x86.c $(IMACKERN_HDRS) $(KDIR)/core/fbcon.h $(IMACKERN_DIR)/trap.o: $(X86K)/trap.S $(IMACKERN_DIR)/fbcon.o: $(KDIR)/core/fbcon.c $(KDIR)/core/fbcon.h $(KDIR)/core/font8x8.h @@ -2625,6 +2632,21 @@ $(IMACKERN_DIR)/pci_x86.o: $(X86K)/pci_x86.c $(IMACKERN_HDRS) $(KDIR)/mm/frames. $(IMACKERN_DIR)/smp_x86.o: $(X86K)/smp_x86.S $(IMACKERN_DIR)/disk_nvme.o: $(NATIVE)/disk/disk_nvme.c $(NATIVE)/disk/disk_nvme.h $(NATIVE)/disk/disk.h $(IMACKERN_DIR)/tg3_x86.o: $(X86K)/tg3_x86.c $(IMACKERN_HDRS) $(KDIR)/mm/frames.h +$(IMACKERN_DIR)/xhci_x86.o: $(X86K)/xhci_x86.c $(IMACKERN_HDRS) $(KDIR)/mm/frames.h $(KDIR)/dev/usb_hid.h +$(IMACKERN_DIR)/hda_x86.o: $(X86K)/hda_x86.c $(IMACKERN_HDRS) $(KDIR)/mm/frames.h $(KDIR)/ui/chirp.h $(KDIR)/ui/night.h +$(IMACKERN_DIR)/usb_hid.o: $(KDIR)/dev/usb_hid.c $(KDIR)/dev/usb_hid.h $(NATIVE)/argus/sha256.h +$(IMACKERN_DIR)/sha256.o: $(NATIVE)/argus/sha256.c $(NATIVE)/argus/sha256.h +$(IMACKERN_DIR)/allen_ui.o: $(KDIR)/ui/allen_ui.c $(KDIR)/ui/allen_ui.h $(KDIR)/ui/allen_font.h $(KDIR)/ui/night.h $(KDIR)/ui/mind.h $(KDIR)/ui/paint.h +$(IMACKERN_DIR)/allen_font.o: $(KDIR)/ui/allen_font.c $(KDIR)/ui/allen_font.h +$(IMACKERN_DIR)/paint.o: $(KDIR)/ui/paint.c $(KDIR)/ui/paint.h $(KDIR)/ui/allen_font.h +$(IMACKERN_DIR)/night.o: $(KDIR)/ui/night.c $(KDIR)/ui/night.h $(KDIR)/ui/paint.h +$(IMACKERN_DIR)/chirp.o: $(KDIR)/ui/chirp.c $(KDIR)/ui/chirp.h $(KDIR)/ui/night.h +$(IMACKERN_DIR)/mind.o: $(KDIR)/ui/mind.c $(KDIR)/ui/mind.h $(KDIR)/ui/paint.h +$(IMACKERN_DIR)/allen_reply.o: $(KDIR)/svc/allen_reply.c $(KDIR)/svc/allen_reply.h $(KDIR)/svc/allen_notes.h +$(IMACKERN_DIR)/allen_notes.o: $(KDIR)/svc/allen_notes.c $(KDIR)/svc/allen_notes.h +$(IMACKERN_DIR)/allen_memory.o: $(KDIR)/svc/allen_memory.c $(KDIR)/svc/allen_memory.h $(KDIR)/svc/allen_reply.h $(KDIR)/svc/allen_notes.h $(NATIVE)/disk/disk.h $(NATIVE)/argus/sha256.h +$(IMACKERN_DIR)/gpt_add.o: $(KDIR)/dev/gpt_add.c $(KDIR)/dev/gpt_add.h $(KDIR)/dev/disk_part.h $(NATIVE)/disk/disk.h $(NATIVE)/argus/sha256.h +$(IMACKERN_DIR)/memory_x86.o: $(X86K)/memory_x86.c $(IMACKERN_HDRS) $(KDIR)/svc/allen_memory.h $(KDIR)/svc/allen_notes.h $(KDIR)/dev/gpt_add.h $(KDIR)/dev/disk_part.h $(IMACKERN_DIR)/report_x86.o: $(X86K)/report_x86.c $(X86K)/report_x86.h $(IMACKERN_HDRS) $(NATIVE)/net/aienos_net.h $(IMACKERN_DIR)/aienos_net.o: $(NATIVE)/net/aienos_net.c $(NATIVE)/net/aienos_net.h $(sort $(IMACKERN_OBJS) $(IMACKERN_REPORT_OBJS)): @@ -2633,8 +2655,10 @@ $(sort $(IMACKERN_OBJS) $(IMACKERN_REPORT_OBJS)): $(IMACKERN_ELF): $(IMACKERN_OBJS) $(BOOT)/image_x86_64.ld @if grep -nE -- 'rt->|RuntimeServices' $(X86K)/*.c; then \ echo "the x86 kernel calls a UEFI runtime service; it must never call one"; exit 1; fi - @if grep -nE "define ATA_" $(X86K)/ahci_x86.c | grep -vE "ATA_(IDENTIFY 0xec|READ_DMA_EXT 0x25)$$"; then \ - echo "ahci_x86.c defines an ATA command other than IDENTIFY and READ DMA EXT; the driver is read-only"; exit 1; fi + @if grep -nE "define ATA_" $(X86K)/ahci_x86.c | grep -vE "ATA_(IDENTIFY 0xec|READ_DMA_EXT 0x25|WRITE_DMA_EXT 0x35|FLUSH_CACHE_EXT 0xea)$$"; then \ + echo "ahci_x86.c defines an ATA command other than IDENTIFY, READ/WRITE DMA EXT and FLUSH CACHE EXT"; exit 1; fi + @if grep -nE "ck_x86_ahci_allow\(" $(X86K)/*.c | grep -vE "^$(X86K)/(memory_x86\.c|ahci_x86\.c:[0-9]+:int ck_x86_ahci_allow\()"; then \ + echo "only memory_x86.c may open a write range on an AHCI disk"; exit 1; fi @if grep -nE "nvme_(write|flush)\(" $(X86K)/*.c; then \ echo "the x86 kernel calls nvme_write or nvme_flush; its disks are read-only"; exit 1; fi @mkdir -p $(dir $@) @@ -2653,7 +2677,7 @@ $(IMACKERN_ELF): $(IMACKERN_OBJS) $(BOOT)/image_x86_64.ld elif [ -n "$$r" ]; then \ echo "default iMac image links the lab-only network report (build it with CK_X86_REPORT=1 only):"; \ echo "$$r"; rm -f $@; exit 1; fi - @if [ "$(CK_X86_REPORT)" != 1 ] && grep -aq "AIENOS-IMAC-REPORT" $@; then \ + @if [ "$(CK_X86_REPORT)" != 1 ] && grep -aq "AIENOS-REPORT" $@; then \ echo "default iMac image carries the report header string"; rm -f $@; exit 1; fi $(IMACKERN_EFI): $(IMACKERN_ELF) $(X86OBJCOPY) -O binary $< $@ diff --git a/native/kernel/README.md b/native/kernel/README.md index 352295e4..8957e84d 100644 --- a/native/kernel/README.md +++ b/native/kernel/README.md @@ -24,7 +24,7 @@ Real hardware runs so far: Raspberry Pi 5 test images (records in | `gpu/` | GB10 GPU memory side, cut D, host only: GPU page tables in the format the NVIDIA driver uses for GB10, a bounded GPU buffer allocator with per-buffer cache policy and quarantine, one compute channel (ring, USERD, instance block, doorbell), and a simulated GB10 to test them on. Not linked into any image; never run on the chip. See "GB10 GPU memory (simulated)" below. | | `tests/` | Host unit tests. | | `third_party/omega/` | The canonical Omega Cortex store, byte for byte from the omega commit in `omega.lock` (checked by `scripts/omega_lock_check.sh`); built freestanding by `svc/cortex_store.c` over the sealed Store through `svc/cortex_journal.c` (native v1 plan P06). | -| `x86/` | x86_64 port, first cut (AIENOS-IMAC-KERNEL-0, 2017 iMac): UEFI stub, descriptor tables and interrupt stubs, page tables, local APIC timer, ACPI power off, console, secondary-core start, PCI walk, read-only AHCI and NVMe disks, BCM57766 Ethernet link detection; a lab-only, opt-in network report (`CK_X86_REPORT=1`). | +| `x86/` | x86_64 port, first cut (AIENOS-KERNEL-0, 2017 iMac): UEFI stub, descriptor tables and interrupt stubs, page tables, local APIC timer, ACPI power off, console, secondary-core start, PCI walk, read-only AHCI and NVMe disks, BCM57766 Ethernet link detection; a lab-only, opt-in network report (`CK_X86_REPORT=1`). | | `../boot/` | Minimal UEFI entry stub (one image with the kernel). | ## Build and test @@ -165,7 +165,7 @@ of them: host tools) are still present as data in every image, including hardware staging; the ordinary loader trusts no anchor. -## 2017 iMac image (AIENOS-IMAC-KERNEL-0, x86_64) +## 2017 iMac image (AIENOS-KERNEL-0, x86_64) make -C native/kernel imac-kernel # target/native-kernel/IMACKERN.EFI scripts/qemu_ck_imac_kernel_test.sh # QEMU q35 + OVMF, two CPU models, ends AIENOS_IMAC_KERNEL @@ -210,7 +210,7 @@ kernel diagnostic keys; everything else, including `memory:`, is dropped whole, so chat, keys, tokens and credentials cannot enter it), as UDP broadcast from 0.0.0.0 to 255.255.255.255 port 47031 (TTL 1), in 1 KiB parts that each start with -`AIENOS-IMAC-REPORT v=2 auth=none run= part=/ bytes=`. +`AIENOS-REPORT v=2 auth=none run= part=/ bytes=`. Anyone on the LAN can read or forge these datagrams; the run id and checksum are not authenticity, so a report is never a receipt, evidence or a command. Future service diagnostics belong on the authenticated transport with an @@ -222,6 +222,84 @@ and rebuilds each run into `OUTDIR/imac-.unauthenticated.txt`; the allowlist (sentinel lines never leave), the frames and reassembly on the host. +**Startup: the night sky.** The moment the clock is measured, before anything +is printed, `ui/allen_ui.c` takes the screen and starts the night +(`ui/night.c`): a dark sky fades in over about seven seconds, the brightest +stars first, with the Milky Way, its dust and six galaxies; two black holes +appear, bending the starlight round them, circle and spiral in on the +inspiral law (separation as t^(1/4), angle as t^(5/8), t the time left), +merge at 12 s in a flash, and a ripple runs out across the sky. From the light +of the merger Allen gathers (`ui/mind.c`): no face and no body, a mind drawn as +light, about a hundred points on and inside a sphere joined by fine threads, +turning slowly round a warm heart, with sparks running along the threads. +The startup text stays off the screen (`ck_x86_console_fb_hold`) until +Allen's window takes over; a panic, or no window, stops the drawing and +brings the text back. Every pixel is worked out from its position and the +time, so a frame redraws only the parts that change, in strips: once the +secondary cores are up, the first draws the frames and the next two draw +strips of them (`smp: ... state=drawing helpers=2`); before that the boot core +draws a frame between console writes. Kernel lines: `screen: night: the sky +made in ...` and `screen: night: N frames ..., average ... ms, slowest ... +ms` (when Allen wakes, 20 s later, and at goodbye). +`ui/chirp.c` is the matching sound: a quick "blirp", the last 0.6 s of the +gravitational-wave chirp of the same inspiral, raised into hearing (200 Hz +sweeping to 1000 Hz, loudness as pitch^(2/3)), peaking at the merger and +ringing out within 0.3 s: under a second in all, worked out from the formula. `x86/hda_x86.c` plays +it: on each HD Audio controller it stops any DMA the firmware left running, resets the link with +the settle times Linux uses, talks to the codecs through the command rings +(CORB/RIRB, polled), maps every widget of each codec onto the report +(`sound: codec=N w=0x.. ...`), opens every speaker, line-out and headphone +path back to a converter (power, routing, 0 dB, pin drive, EAPD; on Apple +boards the codec GPIOs), and on the first controller with a path runs one +output stream: the chirp from the moment the night has reached, then 8 s of +silence; the stream is stopped once the chirp is over. Intel controllers get +Linux's PCI settings first (`pci_x86.c`). In QEMU the recording of what the +guest played matches the chirp sample for sample, starting at the night's +moment. A Cirrus CS8409 bridge on an Apple board (the desktop test +computer's codec) gets its own set-up instead: its four speaker amplifiers +sit behind it on its own I2C bus, so the driver sets the bridge's defaults, +resets the amplifiers into shutdown, sets the TDM slots and clocks, configures +and switches on each amplifier and synchronises the two converters, following +the sequence davidjo/snd_hda_macbookpro replays from macOS. That sequence only +plays 44.1 kHz 24-bit, so behind a CS8409 the chirp is resampled to that +(`ck_chirp_fill_441`, host tested against the 48 kHz sound). The amplifiers +run 24 dB under the level macOS uses. **Heard on the test computer +(2026-10-18):** all four amplifiers answered (no I2C transfer unconfirmed) +and the chirp played; at 12 dB under it was very loud and the old ten-second +chirp too long, hence the quieter level and the short blirp. QEMU has no +CS8409, so this path is checked only on that machine. +Tests: `scripts/ck_allen_ui_test.sh` (host; pictures in +`target/native-kernel-allen-ui/`), `scripts/ck_chirp_test.sh` (the sound as +`target/native-kernel-chirp/chirp.wav`); the QEMU kernel test requires the +night line, the drawing cores, the codec mapped through the command rings, +the chirp stream running and its stop. `AIENOS_IMAC_KERNEL_KEEP_DIR=` +keeps each run's serial log and a `.wav` recording of its sound. + +**Keyboard and Allen's window.** `x86/xhci_x86.c` drives a wired USB boot +keyboard (polled xHCI, through USB 2.0 hubs). When one is ready, Allen wakes: +the person is his guest. A quiet glass bar comes up at the bottom for what +they type; on Enter the line rises from the bar into him, he thinks (he draws +in, turns faster, sparks cascade), then answers under him word by word while +the galaxies shimmer with his voice, all in Allen's own stroke typeface +(`ui/allen_font.c`, every printable ASCII character as pen strokes, +rasterized with integer math). Nothing else is on the screen unless it is in +use: the bar fades when the conversation rests (a key brings it back), his +words fade once read, and the notes map (a small constellation) shows only +when a note is saved or handed back. Each Enter gets a local answer from +`svc/allen_reply.c`: "Hello Allen" gives "Hello Humanity."; it also knows small +talk, your name for the session, facts about the machine, how long it has been +awake and sums said in words ("what is 12 times 4"); anything else gives "I +don't know that yet." Answers print as `allen: ` on the console. The +window has no idle countdown: it stays up until "goodbye" (then ACPI S5, or a +restart in the lab image) or the power button. The conversation stays on the computer: `keyboard_line:` and `allen:` +are off the lab report's allowlist, which carries only `screen: Allen +answered (N characters in, M out)`. Without a keyboard or the memory the text +screen and its 60 s hold stay. Tests: `scripts/ck_allen_ui_test.sh` (host) and +`scripts/qemu_ck_imac_keyboard_test.sh` (QEMU, types "Hello Allen", keeps a +screenshot as `target/native-kernel-imac-keyboard/allen-qemu.png`). What Allen +learns and the notes it keeps are saved in its section of the disk +(`svc/allen_memory.c`, `x86/memory_x86.c`) and come back after a restart. + Output: the GOP framebuffer (`core/fbcon.c`, lines from before ExitBootServices replayed onto it) and COM1 when a 16550 answers there (QEMU; the iMac has none). Shared, unchanged: @@ -374,9 +452,13 @@ What is implemented (NEXT-PHASE-3 cut 1): `dev/usb_kbd.c` resets the controller, finds the first connected port with a USB HID boot keyboard, addresses it, configures its interrupt IN endpoint and polls it. Polled only: no interrupts, no scheduler, no Store. -- **Key decode** to one small fixed US keymap (`dev/usb_hid.c`): a-z (with - Shift: A-Z), 0-9, space, `-`, `.`, `/`, Enter, Backspace, Escape. Every - other key is ignored. A held key produces one event, not a repeat. +- **Key decode** to one fixed US keymap (`dev/usb_hid.c`): every printable + character a US keyboard types, with and without Shift (letters, digits and + `!@#$%^&*()`, space, and the symbol keys with their shifted pairs, `?` + included), plus Enter, Backspace, Escape. Function keys, arrows, Tab and the + non-US key are ignored. A held key produces one event, not a repeat. The + console's commands match whole words only, so symbols can only make an + unknown command; Allen's facts keep letters, digits and spaces. - **Line input** with echo and a bound of 64 characters. One key past the bound makes the whole line fail closed: at Enter it is refused (`keyboard_line: overflow (line refused: N keys typed, limit 64)`) and never diff --git a/native/kernel/core/.crumb b/native/kernel/core/.crumb index 974f039d..38e361fd 100644 --- a/native/kernel/core/.crumb +++ b/native/kernel/core/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-30T22:19:45Z", + "compiled_at": "2026-10-31T02:24:33Z", "compiler": "crumb-compile/1", - "digest": "sha256:3448d48e8498c2a3409e69923020b57bf1146bd1d5913e70f7559cefd9d005bd", + "digest": "sha256:ed58fce3de8581101263e4241f336cc14ea58cd50263fd4bbb5e9ca9bb6639eb", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 74, - "generated_at_commit": "2c149f764d40c9b15fc1a1c946fe1aa188d0879e", - "source_tree": "sha256:970cbbf3037456d4d1dfe0a1694124c8889b8c19a83c4bd75286ccd98e3f559f" + "generated_at_commit": "47faeddadfb49c9e84f9d1058547f7bb0ef45d1d", + "source_tree": "sha256:5b26623e97979b6c3980699bf6548238e7da4bc735f206746260055b3614f532" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/core/fbcon.c b/native/kernel/core/fbcon.c index 6bac4295..65601e07 100644 --- a/native/kernel/core/fbcon.c +++ b/native/kernel/core/fbcon.c @@ -30,8 +30,8 @@ uint32_t ck_fbcon_scale_for(uint32_t width, uint32_t height) return s; } -int ck_fbcon_setup(struct ck_fbcon *c, volatile uint32_t *px, uint32_t width, uint32_t height, - uint32_t pitch, uint32_t format) +int ck_fbcon_attach(struct ck_fbcon *c, volatile uint32_t *px, uint32_t width, uint32_t height, + uint32_t pitch, uint32_t format) { if (!px || format > 1 || pitch < width) return -1; @@ -58,6 +58,14 @@ int ck_fbcon_setup(struct ck_fbcon *c, volatile uint32_t *px, uint32_t width, ui for (uint32_t r = 0; r < CK_FBCON_MAX_ROWS; r++) for (uint32_t k = 0; k < CK_FBCON_MAX_COLS; k++) c->text[r][k] = 0; + return 0; +} + +int ck_fbcon_setup(struct ck_fbcon *c, volatile uint32_t *px, uint32_t width, uint32_t height, + uint32_t pitch, uint32_t format) +{ + if (ck_fbcon_attach(c, px, width, height, pitch, format) != 0) + return -1; ck_fbcon_clear(c); return 0; } @@ -134,6 +142,11 @@ void ck_fbcon_write(struct ck_fbcon *c, const char *s, size_t n) c->col = 0; continue; } + if (ch == '\b') { /* cursor one cell left, within the line; the caller overwrites */ + if (!c->pending_nl && c->col) + c->col--; + continue; + } if (c->pending_nl) { advance(c); c->pending_nl = 0; diff --git a/native/kernel/core/fbcon.h b/native/kernel/core/fbcon.h index a630233c..6f6309e7 100644 --- a/native/kernel/core/fbcon.h +++ b/native/kernel/core/fbcon.h @@ -64,6 +64,10 @@ uint32_t ck_fbcon_scale_for(uint32_t width, uint32_t height); * format is not 0/1. */ int ck_fbcon_setup(struct ck_fbcon *c, volatile uint32_t *px, uint32_t width, uint32_t height, uint32_t pitch, uint32_t format); +/* The same without touching a pixel: the screen keeps what is on it until + * the first clear or write. */ +int ck_fbcon_attach(struct ck_fbcon *c, volatile uint32_t *px, uint32_t width, uint32_t height, + uint32_t pitch, uint32_t format); void ck_fbcon_clear(struct ck_fbcon *c); void ck_fbcon_write(struct ck_fbcon *c, const char *s, size_t n); diff --git a/native/kernel/dev/.crumb b/native/kernel/dev/.crumb index f8489c62..3a019b48 100644 --- a/native/kernel/dev/.crumb +++ b/native/kernel/dev/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-30T21:09:29Z", + "compiled_at": "2026-10-31T02:24:33Z", "compiler": "crumb-compile/1", - "digest": "sha256:bef70d40dabe6ab1d9c94b1ca2134346bd79827441a451fc387b79d00a23caec", + "digest": "sha256:f4d9f6e374a17bdc6bca5564d5e01d32fc4cfb0bcfd33bc1876c26184d74cf06", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 50, - "generated_at_commit": "2fd83c0871858a3ecbfe324dda301809644d7374", - "source_tree": "sha256:d9c371a4cb35bdcbd82fbe30f308e77ac7c105687d5cbb0c017438d173bc08dc" + "files": 52, + "generated_at_commit": "47faeddadfb49c9e84f9d1058547f7bb0ef45d1d", + "source_tree": "sha256:6c5f03446d854e6d5ffc35d960f5b065246ba4c418e4692798c066b9590547fb" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/dev/disk_part.c b/native/kernel/dev/disk_part.c index d85e8e4f..0bb2a495 100644 --- a/native/kernel/dev/disk_part.c +++ b/native/kernel/dev/disk_part.c @@ -230,15 +230,15 @@ int ck_gpt_find_type(const disk_dev *d, const uint8_t type[16], ck_part *p, ck_g if (rc) return rc; if (bcrc != get32(g_hdr + H_ECRC)) return CK_GPT_EBACKUP; + info->first_usable = first_u; + info->last_usable = last_u; + info->entries = g.num; + info->entry_size = g.esize; if (sem) { p->first_lba = 0; p->blocks = 0; return sem; } - info->first_usable = first_u; - info->last_usable = last_u; - info->entries = g.num; - info->entry_size = g.esize; p->valid = 1; p->dev.block_count = p->blocks; return CK_GPT_OK; diff --git a/native/kernel/dev/disk_part.h b/native/kernel/dev/disk_part.h index aa711b63..80454ee8 100644 --- a/native/kernel/dev/disk_part.h +++ b/native/kernel/dev/disk_part.h @@ -86,6 +86,8 @@ typedef struct { uint32_t entries, entry_size; uint32_t used; /* used entries */ uint32_t part_index; /* index of the AIENOS entry */ + /* first_usable .. entry_size are filled whenever both GPT copies are + * valid, also when the answer is CK_GPT_ENOPART / EMULTI / EOVERLAP. */ } ck_gpt_info; typedef struct { diff --git a/native/kernel/dev/gpt_add.c b/native/kernel/dev/gpt_add.c new file mode 100644 index 00000000..681eb037 --- /dev/null +++ b/native/kernel/dev/gpt_add.c @@ -0,0 +1,208 @@ +/* gpt_add.c -- add the AIENOS partition in unused space; see gpt_add.h. */ +#include "gpt_add.h" + +#include "disk_part.h" +#include "sha256.h" + +#define ENT_MAX (64u << 10) +static uint8_t g_ent[ENT_MAX]; +static uint8_t g_ph[4096]; /* primary header block */ +static uint8_t g_bh[4096]; /* backup header block */ +static uint64_t g_f[CK_GPT_MAX_USED], g_l[CK_GPT_MAX_USED]; + +/* UEFI 2.10 table 5-5 offsets, as in disk_part.c */ +enum { H_CRC = 16, H_SIZE = 12, H_GUID = 56, H_ENT_LBA = 72, H_ECRC = 88 }; +static const char part_name[] = "AIENOS Allen memory"; + +static uint32_t get32(const uint8_t *p) +{ + return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; +} +static uint64_t get64(const uint8_t *p) { return (uint64_t)get32(p) | (uint64_t)get32(p + 4) << 32; } +static void put32(uint8_t *p, uint32_t v) +{ + for (int i = 0; i < 4; i++) + p[i] = (uint8_t)(v >> (8 * i)); +} +static void put64(uint8_t *p, uint64_t v) +{ + put32(p, (uint32_t)v); + put32(p + 4, (uint32_t)(v >> 32)); +} +static int zero16(const uint8_t *p) +{ + uint8_t d = 0; + for (int i = 0; i < 16; i++) + d |= p[i]; + return d == 0; +} + +/* Reads both header blocks and the primary entry array (after the strict + * check passed far enough to fill info). */ +static int load(const disk_dev *d, const ck_gpt_info *gi, uint32_t *bytes, uint32_t *blocks) +{ + *bytes = gi->entries * gi->entry_size; + if (*bytes == 0 || *bytes > ENT_MAX || d->block_size > sizeof g_ph) + return CK_GPT_EBIG; + *blocks = (*bytes + d->block_size - 1u) / d->block_size; + if (disk_read(d, 1, 1, g_ph) != DISK_OK || disk_read(d, gi->last_lba, 1, g_bh) != DISK_OK || + disk_read(d, get64(g_ph + H_ENT_LBA), *blocks, g_ent) != DISK_OK) + return CK_GPT_EIO; + return CK_GPT_OK; +} + +int ck_gpt_list(const disk_dev *d, void (*fn)(void *ctx, const ck_gpt_entry *e), void *ctx) +{ + ck_part p; + ck_gpt_info gi; + int rc = ck_gpt_find_aienos(d, &p, &gi); + if (rc != CK_GPT_OK && gi.entries == 0) + return rc; + uint32_t bytes, blocks, used = 0; + if ((rc = load(d, &gi, &bytes, &blocks))) + return rc; + for (uint32_t i = 0; i < gi.entries; i++) { + const uint8_t *e = g_ent + (uint64_t)i * gi.entry_size; + if (zero16(e)) + continue; + ck_gpt_entry out; + out.index = i; + for (int k = 0; k < 16; k++) + out.type[k] = e[k]; + out.first = get64(e + 32); + out.last = get64(e + 40); + unsigned n = 0; + for (; n < 36; n++) { + uint16_t c = (uint16_t)(e[56 + 2 * n] | e[57 + 2 * n] << 8); + if (!c) + break; + out.name[n] = c >= 0x20 && c < 0x7f && c != '"' ? (char)c : '?'; + } + out.name[n] = 0; + used++; + if (fn) + fn(ctx, &out); + } + return (int)used; +} + +static void header_crc(uint8_t *h, uint32_t ecrc) +{ + put32(h + H_ECRC, ecrc); + put32(h + H_CRC, 0); + put32(h + H_CRC, ck_crc32(0, h, get32(h + H_SIZE))); +} + +int ck_gpt_add_aienos(const disk_dev *d, uint64_t blocks, uint64_t align, ck_gpt_added *out) +{ + ck_part p; + ck_gpt_info gi; + if (!out || !blocks || !align) + return CK_GPT_EGEOM; + *out = (ck_gpt_added){0, 0, 0, 0}; + int rc = ck_gpt_find_aienos(d, &p, &gi); + if (rc == CK_GPT_OK) { + out->first = p.first_lba; + out->last = p.first_lba + p.blocks - 1u; + out->index = gi.part_index; + return CK_GPT_OK; + } + if (rc != CK_GPT_ENOPART) + return rc; + uint32_t bytes, eblocks; + if ((rc = load(d, &gi, &bytes, &eblocks))) + return rc; + + /* Used ranges, sorted by first LBA (the strict check proved they lie in + * the usable range and do not overlap). */ + uint32_t n = 0, slot = gi.entries; + for (uint32_t i = 0; i < gi.entries; i++) { + const uint8_t *e = g_ent + (uint64_t)i * gi.entry_size; + if (zero16(e)) { + if (slot == gi.entries) + slot = i; + continue; + } + if (n == CK_GPT_MAX_USED) + return CK_GPT_ETOOMANY; + uint64_t f = get64(e + 32), l = get64(e + 40); + uint32_t k = n++; + for (; k && g_f[k - 1] > f; k--) { + g_f[k] = g_f[k - 1]; + g_l[k] = g_l[k - 1]; + } + g_f[k] = f; + g_l[k] = l; + } + if (slot == gi.entries) + return CK_GPT_ENOSLOT; + uint64_t at = 0, cursor = gi.first_usable; + int found = 0; + for (uint32_t k = 0; k <= n && !found; k++) { + uint64_t gap_end = k < n ? g_f[k] - 1u : gi.last_usable; /* g_f[k] >= first_usable >= 34 */ + uint64_t start = (cursor + align - 1u) / align * align; + if (cursor <= gap_end && start >= cursor && start <= gap_end && gap_end - start >= blocks - 1u) { + at = start; + found = 1; + } + if (k < n && g_l[k] + 1u > cursor) + cursor = g_l[k] + 1u; + } + if (!found) + return CK_GPT_ENOSPACE; + + /* The new entry. Its unique GUID: SHA-256 over a label, the disk GUID + * and the first LBA, cut to 16 bytes and marked version 4 / variant 1. */ + uint8_t *e = g_ent + (uint64_t)slot * gi.entry_size; + for (uint32_t i = 0; i < gi.entry_size; i++) + e[i] = 0; + for (int i = 0; i < 16; i++) + e[i] = ck_aienos_part_type[i]; + uint8_t dig[32], lba8[8]; + static const char label[] = "aienos.allen.memory.v1"; + put64(lba8, at); + sha256_ctx h; + sha256_init(&h); + sha256_update(&h, (const uint8_t *)label, sizeof label); + sha256_update(&h, g_ph + H_GUID, 16); + sha256_update(&h, lba8, 8); + sha256_final(&h, dig); + for (int i = 0; i < 16; i++) + e[16 + i] = dig[i]; + e[16 + 7] = (uint8_t)((e[16 + 7] & 0x0f) | 0x40); + e[16 + 8] = (uint8_t)((e[16 + 8] & 0x3f) | 0x80); + put64(e + 32, at); + put64(e + 40, at + blocks - 1u); + for (unsigned i = 0; part_name[i]; i++) + e[56 + 2 * i] = (uint8_t)part_name[i]; + + uint32_t ecrc = ck_crc32(0, g_ent, bytes); + header_crc(g_ph, ecrc); + header_crc(g_bh, ecrc); + uint64_t bent = get64(g_bh + H_ENT_LBA), pent = get64(g_ph + H_ENT_LBA); + if (disk_write(d, bent, eblocks, g_ent) != DISK_OK || disk_write(d, gi.last_lba, 1, g_bh) != DISK_OK || + disk_flush(d) != DISK_OK || disk_write(d, pent, eblocks, g_ent) != DISK_OK || + disk_write(d, 1, 1, g_ph) != DISK_OK || disk_flush(d) != DISK_OK) + return CK_GPT_EWRITE; + + rc = ck_gpt_find_aienos(d, &p, &gi); + if (rc != CK_GPT_OK || p.first_lba != at || p.blocks != blocks || gi.part_index != slot) + return CK_GPT_EVERIFY; + out->first = at; + out->last = at + blocks - 1u; + out->index = slot; + out->created = 1; + return CK_GPT_OK; +} + +const char *ck_gpt_add_strerror(int rc) +{ + switch (rc) { + case CK_GPT_ENOSPACE: return "no unused space large enough"; + case CK_GPT_ENOSLOT: return "no free partition entry"; + case CK_GPT_EBIG: return "partition entry array too large"; + case CK_GPT_EWRITE: return "write failed"; + case CK_GPT_EVERIFY: return "partition not as written after the check"; + default: return ck_gpt_strerror(rc); + } +} diff --git a/native/kernel/dev/gpt_add.h b/native/kernel/dev/gpt_add.h new file mode 100644 index 00000000..c2070242 --- /dev/null +++ b/native/kernel/dev/gpt_add.h @@ -0,0 +1,54 @@ +/* gpt_add.h -- the one GPT change the AIENOS kernel may make: add an AIENOS + * partition (disk_part.h type GUID) in space no partition uses, on a disk + * whose GPT already passes ck_gpt_find_aienos's strict check with "no AIENOS + * partition". Existing entries are never moved, resized or rewritten; the + * protective MBR (LBA 0) is never written. Writes, in this order: the backup + * entry array and backup header, flush, then the primary entry array and + * primary header, flush; then the whole GPT is checked again and must show + * the new partition exactly. A power cut part way leaves one copy old and + * one new; the strict check then refuses both until a person looks, so + * nothing further is written (the firmware keeps reading the primary). + * + * Also ck_gpt_list: every used entry, read only, for the boot report. + * Freestanding: no libc, no heap. Host tested in dev/tests/gpt_add_test.c. */ +#ifndef AIENOS_CK_GPT_ADD_H +#define AIENOS_CK_GPT_ADD_H +#include +#include "disk.h" + +enum { + CK_GPT_ENOSPACE = -420, /* no unused gap holds the partition */ + CK_GPT_ENOSLOT = -421, /* no free entry in the array */ + CK_GPT_EBIG = -422, /* entry array larger than this file handles (64 KiB) */ + CK_GPT_EWRITE = -423, /* a write or flush failed */ + CK_GPT_EVERIFY = -424, /* after writing, the GPT does not show the partition exactly */ +}; + +typedef struct { + uint32_t index; + uint8_t type[16]; /* on-disk byte order */ + uint64_t first, last; /* inclusive LBAs */ + char name[37]; /* the UTF-16 name as ASCII, '?' for anything else */ +} ck_gpt_entry; + +/* Calls fn for every used entry when both GPT copies are valid (any + * ck_gpt_find_aienos answer that got that far). The number of used entries, + * or the CK_GPT_* refusal. */ +int ck_gpt_list(const disk_dev *d, void (*fn)(void *ctx, const ck_gpt_entry *e), void *ctx); + +typedef struct { + uint64_t first, last; /* the AIENOS partition, inclusive */ + uint32_t index; /* its entry */ + int created; /* 1: added now; 0: it was already there */ +} ck_gpt_added; + +/* Makes sure the disk has an AIENOS partition: an existing one is reported + * (nothing written); otherwise one of `blocks` blocks is added at the start + * of the first unused gap that holds it, its first LBA rounded up to a + * multiple of `align` blocks. CK_GPT_OK or the refusal (nothing written + * unless the code is CK_GPT_EWRITE or CK_GPT_EVERIFY). */ +int ck_gpt_add_aienos(const disk_dev *d, uint64_t blocks, uint64_t align, ck_gpt_added *out); + +/* Text for the codes here and those of disk_part.h. */ +const char *ck_gpt_add_strerror(int rc); +#endif diff --git a/native/kernel/dev/usb_hid.c b/native/kernel/dev/usb_hid.c index 4ee2b340..78455b19 100644 --- a/native/kernel/dev/usb_hid.c +++ b/native/kernel/dev/usb_hid.c @@ -23,29 +23,34 @@ #define USAGE_BACKSPACE 0x2au #define USAGE_SPACE 0x2cu #define USAGE_MINUS 0x2du -#define USAGE_PERIOD 0x37u #define USAGE_SLASH 0x38u #define MOD_ANY_SHIFT 0x22u /* left shift bit 1, right shift bit 5 */ ck_key_event ck_hid_usage(uint8_t usage, int shift) { + /* the US layout's symbol keys, usages 0x2d..0x38 (0x32, the non-US key, has none) */ + static const char sym[2][12] = {{'-', '=', '[', ']', '\\', 0, ';', '\'', '`', ',', '.', '/'}, + {'_', '+', '{', '}', '|', 0, ':', '"', '~', '<', '>', '?'}}; + static const char shifted_digit[10] = {'!', '@', '#', '$', '%', '^', '&', '*', '(', ')'}; ck_key_event ev = {CK_KEY_NONE, 0}; if (usage >= 0x04 && usage <= 0x1d) { /* a..z */ ev.kind = CK_KEY_CHAR; ev.c = (char)((shift ? 'A' : 'a') + (usage - 0x04)); } else if (usage >= 0x1e && usage <= 0x27) { /* 1..9, 0 */ - if (shift) return ev; ev.kind = CK_KEY_CHAR; - ev.c = usage == 0x27 ? '0' : (char)('1' + (usage - 0x1e)); + ev.c = shift ? shifted_digit[usage - 0x1e] : usage == 0x27 ? '0' : (char)('1' + (usage - 0x1e)); } else if (usage == USAGE_ENTER) { ev.kind = CK_KEY_ENTER; } else if (usage == USAGE_ESCAPE) { ev.kind = CK_KEY_ESCAPE; } else if (usage == USAGE_BACKSPACE) { ev.kind = CK_KEY_BACKSPACE; - } else if (!shift && (usage == USAGE_SPACE || usage == USAGE_MINUS || usage == USAGE_PERIOD || usage == USAGE_SLASH)) { + } else if (usage == USAGE_SPACE) { ev.kind = CK_KEY_CHAR; - ev.c = usage == USAGE_SPACE ? ' ' : usage == USAGE_MINUS ? '-' : usage == USAGE_PERIOD ? '.' : '/'; + ev.c = ' '; + } else if (usage >= USAGE_MINUS && usage <= USAGE_SLASH && sym[shift != 0][usage - USAGE_MINUS]) { + ev.kind = CK_KEY_CHAR; + ev.c = sym[shift != 0][usage - USAGE_MINUS]; } return ev; } diff --git a/native/kernel/dev/usb_hid.h b/native/kernel/dev/usb_hid.h index 365e2888..ba681636 100644 --- a/native/kernel/dev/usb_hid.h +++ b/native/kernel/dev/usb_hid.h @@ -46,9 +46,11 @@ typedef struct { uint8_t previous[CK_HID_MAX_KEYS]; } ck_hid_decoder; -/* Fixed keymap (US layout, the only one): usages a-z (shift: A-Z), 1-0, - * space, '-', '.', '/', Enter, Backspace, Escape. Every other usage, and - * shifted digits or punctuation, yields nothing. */ +/* Fixed keymap (US layout, the only one): every printable ASCII character a + * US keyboard types, with and without shift (a-z A-Z, 0-9 and !@#$%^&*(), + * space, and the symbol keys - = [ ] \ ; ' ` , . / and their shifted + * _ + { } | : " ~ < > ?), plus Enter, Backspace, Escape. Every other usage + * (function keys, arrows, Tab, the non-US key) yields nothing. */ ck_key_event ck_hid_usage(uint8_t usage, int shift); /* Decode one 8-byte report: one event per usage that was not pressed in the * previous report (key repeat is not generated). A phantom/rollover report diff --git a/native/kernel/svc/.crumb b/native/kernel/svc/.crumb index 46f4f204..59a43df6 100644 --- a/native/kernel/svc/.crumb +++ b/native/kernel/svc/.crumb @@ -18,26 +18,26 @@ "children": [ { "digest": "d6868c343497f05846433dd6f9e76a5beb0f51a3a38e70fb9ad2c6518d5c9514", - "last_commit": "f45d00ad", + "last_commit": "31ed9f8", "name": "compat", "purpose": "Directory native/kernel/svc/compat. Purpose not yet described by a human." }, { - "digest": "6602350f6b34e0e5a5582511e5ea65680f5d175c001bb4828ddb379f0429fc2a", - "last_commit": "8182d6d3", + "digest": "259013cfeff5387fa3aa04f48cd615af1932d5c2a7dfe60e6d09d90cc3c51c6a", + "last_commit": "4eb74bf", "name": "tests", "purpose": "Directory native/kernel/svc/tests. Purpose not yet described by a human." } ], - "children_root": "sha256:a70bab0b29b9dbc45df8c0ac73476773e033270a3bbfbdc303964a3452799f7f", - "compiled_at": "2026-10-30T12:35:18Z", + "children_root": "sha256:adfe21753ab01289100e5475adaa069d48fd2826311005574e2e40b38dcade98", + "compiled_at": "2026-10-31T02:24:33Z", "compiler": "crumb-compile/1", - "digest": "sha256:e0a0bed1e95c876ea3d0a2dc136b94d3744491e72d5809c11de6ff787b21fd0a", + "digest": "sha256:ef3844c1228b5fc5b740f944b4a3d2539fc4a816bf5402fa47fce6b50850d543", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 48, - "generated_at_commit": "aab6de6d4df4b4d99e764e91303a13d10684f5fe", - "source_tree": "sha256:0f2ae3117361a7d5debca6bb4a7bc06925c0f1089539b2933d4aaaf3ca13f575" + "files": 55, + "generated_at_commit": "47faeddadfb49c9e84f9d1058547f7bb0ef45d1d", + "source_tree": "sha256:500f9dbf12ad5645e87d96886e45f38adb8454b91f0520404f70110df1f56d44" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/svc/allen_memory.c b/native/kernel/svc/allen_memory.c new file mode 100644 index 00000000..eec1e0ce --- /dev/null +++ b/native/kernel/svc/allen_memory.c @@ -0,0 +1,311 @@ +/* allen_memory.c -- Allen's memory on disk in two copies; see allen_memory.h. */ +#include "allen_memory.h" + +#include "sha256.h" + +#define HDR 64u +#define FACT_BYTES (CK_ALLEN_KEY_MAX + CK_ALLEN_VAL_MAX + 1u) +#define PAYLOAD_FIXED (4u + 4u + CK_ALLEN_NAME_MAX + 4u + 4u) +#define VERSION 2u + +_Static_assert(HDR + PAYLOAD_FIXED + CK_ALLEN_FACTS_MAX * FACT_BYTES <= CK_ALLEN_MEM_UNIT, "memory fits one unit"); + +static const uint8_t magic[8] = {'A', 'I', 'E', 'N', 'A', 'L', 'M', '1'}; +static uint8_t g_unit[CK_ALLEN_MEM_UNIT] __attribute__((aligned(64))); +static uint8_t g_back[CK_ALLEN_MEM_UNIT] __attribute__((aligned(64))); + +static void put32(uint8_t *p, uint32_t v) +{ + for (int i = 0; i < 4; i++) + p[i] = (uint8_t)(v >> (8 * i)); +} +static void put64(uint8_t *p, uint64_t v) +{ + put32(p, (uint32_t)v); + put32(p + 4, (uint32_t)(v >> 32)); +} +static uint32_t get32(const uint8_t *p) +{ + return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; +} +static uint64_t get64(const uint8_t *p) { return (uint64_t)get32(p) | (uint64_t)get32(p + 4) << 32; } +static void zero(void *d, uint32_t n) +{ + for (uint32_t i = 0; i < n; i++) + ((uint8_t *)d)[i] = 0; +} +static void copy(void *d, const void *s, uint32_t n) +{ + for (uint32_t i = 0; i < n; i++) + ((uint8_t *)d)[i] = ((const uint8_t *)s)[i]; +} +static int same(const uint8_t *a, const uint8_t *b, uint32_t n) +{ + uint8_t d = 0; + for (uint32_t i = 0; i < n; i++) + d |= (uint8_t)(a[i] ^ b[i]); + return d == 0; +} + +static void seal(uint8_t *unit, uint32_t plen) +{ + sha256_ctx h; + sha256_init(&h); + sha256_update(&h, unit, 32); + sha256_update(&h, unit + HDR, plen); + sha256_final(&h, unit + 32); +} + +/* Folded text in a field of cap bytes: NUL-terminated, a-z 0-9 and single + * inner spaces only, the rest of the field zero. letters: a name (A-Z first, + * then a-z, or empty). */ +static int text_ok(const uint8_t *t, uint32_t cap, int name) +{ + uint32_t n = 0; + while (n < cap && t[n]) + n++; + if (n == cap) + return 0; + for (uint32_t i = n; i < cap; i++) + if (t[i]) + return 0; + for (uint32_t i = 0; i < n; i++) { + uint8_t c = t[i]; + int lower = c >= 'a' && c <= 'z', digit = c >= '0' && c <= '9'; + if (name) { + /* learn_name keeps one folded word, first letter capitalised */ + if (!(i == 0 ? (c >= 'A' && c <= 'Z') || digit : lower || digit)) + return 0; + } else if (c == ' ') { + if (i == 0 || i == n - 1 || t[i - 1] == ' ') + return 0; + } else if (!lower && !digit) { + return 0; + } + } + return 1; +} + +void ck_allen_mem_encode(const ck_allen_memory *mem, uint64_t gen, uint8_t unit[CK_ALLEN_MEM_UNIT]) +{ + uint32_t n = mem->nfacts > CK_ALLEN_FACTS_MAX ? CK_ALLEN_FACTS_MAX : mem->nfacts; + uint32_t plen = PAYLOAD_FIXED + n * FACT_BYTES; + zero(unit, CK_ALLEN_MEM_UNIT); + copy(unit, magic, 8); + put32(unit + 8, VERSION); + put32(unit + 12, plen); + put64(unit + 16, gen); + uint8_t *p = unit + HDR; + put32(p, mem->starts); + put32(p + 4, mem->lines); + copy(p + 8, mem->name, CK_ALLEN_NAME_MAX); + p[8 + CK_ALLEN_NAME_MAX - 1] = 0; + put32(p + 8 + CK_ALLEN_NAME_MAX, n); + put32(p + 12 + CK_ALLEN_NAME_MAX, mem->nnotes); + p += PAYLOAD_FIXED; + for (uint32_t i = 0; i < n; i++, p += FACT_BYTES) { + copy(p, mem->fact[i].key, CK_ALLEN_KEY_MAX); + p[CK_ALLEN_KEY_MAX - 1] = 0; + copy(p + CK_ALLEN_KEY_MAX, mem->fact[i].val, CK_ALLEN_VAL_MAX); + p[CK_ALLEN_KEY_MAX + CK_ALLEN_VAL_MAX - 1] = 0; + p[CK_ALLEN_KEY_MAX + CK_ALLEN_VAL_MAX] = mem->fact[i].are ? 1 : 0; + } + seal(unit, plen); +} + +int ck_allen_mem_decode(const uint8_t unit[CK_ALLEN_MEM_UNIT], ck_allen_memory *mem, uint64_t *gen) +{ + if (!same(unit, magic, 8) || get32(unit + 8) != VERSION) + return -1; + const uint8_t *p = unit + HDR; + uint32_t plen = get32(unit + 12), n = get32(p + 8 + CK_ALLEN_NAME_MAX); + if (n > CK_ALLEN_FACTS_MAX || get32(p + 12 + CK_ALLEN_NAME_MAX) > CK_ALLEN_NOTES_MAX || + plen != PAYLOAD_FIXED + n * FACT_BYTES || get64(unit + 16) == 0) + return -1; + for (uint32_t i = 24; i < 32; i++) + if (unit[i]) + return -1; + for (uint32_t i = HDR + plen; i < CK_ALLEN_MEM_UNIT; i++) + if (unit[i]) + return -1; + uint8_t want[32]; + sha256_ctx h; + sha256_init(&h); + sha256_update(&h, unit, 32); + sha256_update(&h, unit + HDR, plen); + sha256_final(&h, want); + if (!same(want, unit + 32, 32)) + return -1; + if (!text_ok(p + 8, CK_ALLEN_NAME_MAX, 1)) + return -1; + const uint8_t *f = p + PAYLOAD_FIXED; + for (uint32_t i = 0; i < n; i++, f += FACT_BYTES) + if (!text_ok(f, CK_ALLEN_KEY_MAX, 0) || !f[0] || !text_ok(f + CK_ALLEN_KEY_MAX, CK_ALLEN_VAL_MAX, 0) || + !f[CK_ALLEN_KEY_MAX] || f[CK_ALLEN_KEY_MAX + CK_ALLEN_VAL_MAX] > 1) + return -1; + zero(mem, sizeof *mem); + mem->starts = get32(p); + mem->lines = get32(p + 4); + copy(mem->name, p + 8, CK_ALLEN_NAME_MAX); + mem->nfacts = n; + mem->nnotes = get32(p + 12 + CK_ALLEN_NAME_MAX); + f = p + PAYLOAD_FIXED; + for (uint32_t i = 0; i < n; i++, f += FACT_BYTES) { + copy(mem->fact[i].key, f, CK_ALLEN_KEY_MAX); + copy(mem->fact[i].val, f + CK_ALLEN_KEY_MAX, CK_ALLEN_VAL_MAX); + mem->fact[i].are = f[CK_ALLEN_KEY_MAX + CK_ALLEN_VAL_MAX]; + } + *gen = get64(unit + 16); + return 0; +} + +static int geom(const disk_dev *d, uint32_t *per) +{ + if (disk_check(d) != DISK_OK || (d->block_size != 512 && d->block_size != 4096)) + return CK_ALLEN_MEM_EGEOM; + *per = CK_ALLEN_MEM_UNIT / d->block_size; + if (d->block_count < (uint64_t)*per * CK_ALLEN_MEM_UNITS) + return CK_ALLEN_MEM_EGEOM; + return CK_ALLEN_MEM_OK; +} + +int ck_allen_store_load(ck_allen_store *st, const disk_dev *part, ck_allen_memory *mem) +{ + uint32_t per = 0; + zero(st, sizeof *st); + zero(mem, sizeof *mem); + st->dev = part; + int rc = geom(part, &per); + if (rc) + return rc; + for (unsigned c = 0; c < 2; c++) { + ck_allen_memory m; + uint64_t g = 0; + if (disk_read(part, (uint64_t)c * per, per, g_unit) != DISK_OK) + return CK_ALLEN_MEM_EIO; + if (ck_allen_mem_decode(g_unit, &m, &g)) + continue; + st->valid++; + if (g > st->gen) { + st->gen = g; + st->newest = c; + *mem = m; + } + } + return st->gen ? CK_ALLEN_MEM_OK : CK_ALLEN_MEM_EMPTY; +} + +int ck_allen_store_save(ck_allen_store *st, const ck_allen_memory *mem) +{ + uint32_t per = 0; + int rc = geom(st->dev, &per); + if (rc) + return rc; + unsigned target = st->gen ? 1u - st->newest : 0u; /* the older copy (A on a first save) */ + uint64_t lba = (uint64_t)target * per; + ck_allen_mem_encode(mem, st->gen + 1, g_unit); + if (disk_write(st->dev, lba, per, g_unit) != DISK_OK || disk_flush(st->dev) != DISK_OK) + return CK_ALLEN_MEM_EIO; + if (disk_read(st->dev, lba, per, g_back) != DISK_OK) + return CK_ALLEN_MEM_EIO; + if (!same(g_unit, g_back, CK_ALLEN_MEM_UNIT)) + return CK_ALLEN_MEM_EVERIFY; + st->gen++; + st->newest = target; + if (st->valid < 2) + st->valid++; + return CK_ALLEN_MEM_OK; +} + +/* ---- notes: one unit each, from unit CK_ALLEN_NOTES_FIRST ---- */ + +static const uint8_t note_magic[8] = {'A', 'I', 'E', 'N', 'N', 'O', 'T', '1'}; + +void ck_allen_note_encode(const ck_allen_note *n, uint32_t index, uint8_t unit[CK_ALLEN_MEM_UNIT]) +{ + uint32_t len = n->len < CK_ALLEN_NOTE_MAX ? n->len : CK_ALLEN_NOTE_MAX - 1u; + zero(unit, CK_ALLEN_MEM_UNIT); + copy(unit, note_magic, 8); + put32(unit + 8, 1); + put32(unit + 12, len); + put32(unit + 16, index); + put32(unit + 20, n->start); + put32(unit + 24, n->gone ? 1u : 0u); + copy(unit + HDR, n->text, len); + seal(unit, len); +} + +int ck_allen_note_decode(const uint8_t unit[CK_ALLEN_MEM_UNIT], uint32_t index, ck_allen_note *n) +{ + uint32_t len = get32(unit + 12); + if (!same(unit, note_magic, 8) || get32(unit + 8) != 1 || len == 0 || len >= CK_ALLEN_NOTE_MAX || + get32(unit + 16) != index || get32(unit + 24) > 1 || get32(unit + 28)) + return -1; + for (uint32_t i = HDR + len; i < CK_ALLEN_MEM_UNIT; i++) + if (unit[i]) + return -1; + for (uint32_t i = 0; i < len; i++) + if (unit[HDR + i] < 0x20 || unit[HDR + i] > 0x7e) + return -1; + uint8_t want[32]; + sha256_ctx h; + sha256_init(&h); + sha256_update(&h, unit, 32); + sha256_update(&h, unit + HDR, len); + sha256_final(&h, want); + if (!same(want, unit + 32, 32)) + return -1; + zero(n, sizeof *n); + copy(n->text, unit + HDR, len); + n->len = (uint16_t)len; + n->start = get32(unit + 20); + n->gone = (uint8_t)get32(unit + 24); + ck_allen_note_index(n); + return 0; +} + +static int notes_geom(const disk_dev *d, uint32_t count, uint32_t *per) +{ + int rc = geom(d, per); + if (rc) + return rc; + if (count > CK_ALLEN_NOTES_MAX || d->block_count < (uint64_t)*per * (CK_ALLEN_NOTES_FIRST + count)) + return CK_ALLEN_MEM_EGEOM; + return CK_ALLEN_MEM_OK; +} + +int ck_allen_notes_load(const disk_dev *part, uint32_t count, ck_allen_notes *ns, uint32_t *damaged) +{ + uint32_t per = 0; + zero(ns, sizeof *ns); + *damaged = 0; + int rc = notes_geom(part, count, &per); + if (rc) + return rc; + for (uint32_t i = 0; i < count; i++) { + if (disk_read(part, (uint64_t)(CK_ALLEN_NOTES_FIRST + i) * per, per, g_unit) != DISK_OK) + return CK_ALLEN_MEM_EIO; + if (ck_allen_note_decode(g_unit, i, &ns->note[i])) { + zero(&ns->note[i], sizeof ns->note[i]); + ns->note[i].gone = 1; + (*damaged)++; + } + } + ns->n = count; + return CK_ALLEN_MEM_OK; +} + +int ck_allen_note_write(const disk_dev *part, const ck_allen_notes *ns, uint32_t index) +{ + uint32_t per = 0; + int rc = notes_geom(part, index + 1u, &per); + if (rc) + return rc; + uint64_t lba = (uint64_t)(CK_ALLEN_NOTES_FIRST + index) * per; + ck_allen_note_encode(&ns->note[index], index, g_unit); + if (disk_write(part, lba, per, g_unit) != DISK_OK || disk_flush(part) != DISK_OK) + return CK_ALLEN_MEM_EIO; + if (disk_read(part, lba, per, g_back) != DISK_OK) + return CK_ALLEN_MEM_EIO; + return same(g_unit, g_back, CK_ALLEN_MEM_UNIT) ? CK_ALLEN_MEM_OK : CK_ALLEN_MEM_EVERIFY; +} diff --git a/native/kernel/svc/allen_memory.h b/native/kernel/svc/allen_memory.h new file mode 100644 index 00000000..d8e8e0e3 --- /dev/null +++ b/native/kernel/svc/allen_memory.h @@ -0,0 +1,78 @@ +/* allen_memory.h -- Allen's memory on disk: ck_allen_memory (allen_reply.h) + * kept in two copies at the start of the AIENOS partition, so a power cut in + * the middle of a save can only spoil the copy being written. + * + * unit 0 copy A unit 1 copy B (a unit is 4096 bytes) + * unit 2 + i note i, for i below the note count held in the copies + * + * One copy is one unit: + * 0 "AIENALM1" 8 bytes + * 8 version (2) u32 little endian + * 12 payload length u32 + * 16 generation u64, +1 on every save + * 24 zero 8 bytes + * 32 SHA-256 of bytes 0..31 and the payload + * 64 payload: starts u32, lines u32, name[24], fact count u32, note + * count u32, then per fact key[48] val[64] are(u8); the rest zero + * A save writes generation g+1 over the OLDER copy, flushes the disk's write + * cache, then reads it back and checks it; the newer copy is never touched + * until the older one holds the newer state. Loading reads both and keeps + * the valid copy with the highest generation. A copy is valid only when every + * field checks out: magic, version, exact length, fingerprint, fact count, + * NUL-terminated folded text (a-z, 0-9, single spaces), a name of letters. + * Freestanding (no libc, no heap): every disk access goes through the + * partition view handed in. Host tested in svc/tests/allen_memory_test.c, + * power cuts included. */ +#ifndef AIENOS_ALLEN_MEMORY_H +#define AIENOS_ALLEN_MEMORY_H +#include +#include "disk.h" +#include "allen_notes.h" +#include "allen_reply.h" + +#define CK_ALLEN_MEM_UNIT 4096u +#define CK_ALLEN_MEM_UNITS 2u /* the two copies */ +#define CK_ALLEN_NOTES_FIRST 2u /* the unit of note 0 */ +/* Units of the partition this file ever touches. */ +#define CK_ALLEN_DISK_UNITS (CK_ALLEN_NOTES_FIRST + CK_ALLEN_NOTES_MAX) + +enum { + CK_ALLEN_MEM_OK = 0, /* loaded the newest valid copy */ + CK_ALLEN_MEM_EMPTY = 1, /* no valid copy: a first start (or both spoiled) */ + CK_ALLEN_MEM_EIO = -501, /* a read, write or flush failed */ + CK_ALLEN_MEM_EGEOM = -502, /* partition view too small or odd block size */ + CK_ALLEN_MEM_EVERIFY = -503, /* the copy read back differs from the copy written */ +}; + +typedef struct { + const disk_dev *dev; /* the AIENOS partition view */ + uint64_t gen; /* generation of the newest valid copy, 0 = none */ + unsigned newest; /* which copy holds it (0 = A, 1 = B) */ + unsigned valid; /* copies that were valid at load (0..2) */ +} ck_allen_store; + +/* Encode / decode one copy (exposed for the tests). decode: 0 and *mem, + * *gen filled, or -1 when the copy is not valid. */ +void ck_allen_mem_encode(const ck_allen_memory *mem, uint64_t gen, uint8_t unit[CK_ALLEN_MEM_UNIT]); +int ck_allen_mem_decode(const uint8_t unit[CK_ALLEN_MEM_UNIT], ck_allen_memory *mem, uint64_t *gen); + +/* Read both copies. OK (mem = newest), EMPTY (mem zeroed) or an error. */ +int ck_allen_store_load(ck_allen_store *st, const disk_dev *part, ck_allen_memory *mem); +/* Save mem as the next generation (see above). OK or an error; on error + * the previous newest copy is still on disk and st is unchanged. */ +int ck_allen_store_save(ck_allen_store *st, const ck_allen_memory *mem); + +/* A note is one unit, written in place (a deleted note is rewritten with + * the gone flag): "AIENNOT1", version 1, text length u32, index u32, start + * u32, gone u32 (0|1), zero u32, SHA-256 of bytes 0..31 and the text at + * 32, the text (printable ASCII) at 64, the rest zero. A note counts only + * once the copies hold a note count past it: a save writes the note, then + * the copies, so a power cut leaves either no note or a whole one. A note + * that fails any check loads as gone and is counted in *damaged. */ +void ck_allen_note_encode(const ck_allen_note *n, uint32_t index, uint8_t unit[CK_ALLEN_MEM_UNIT]); +int ck_allen_note_decode(const uint8_t unit[CK_ALLEN_MEM_UNIT], uint32_t index, ck_allen_note *n); +int ck_allen_notes_load(const disk_dev *part, uint32_t count, ck_allen_notes *ns, uint32_t *damaged); +/* Writes note index, flushes, reads it back. OK, EIO, EGEOM or EVERIFY. */ +int ck_allen_note_write(const disk_dev *part, const ck_allen_notes *ns, uint32_t index); + +#endif diff --git a/native/kernel/svc/allen_notes.c b/native/kernel/svc/allen_notes.c new file mode 100644 index 00000000..ff372c88 --- /dev/null +++ b/native/kernel/svc/allen_notes.c @@ -0,0 +1,164 @@ +/* allen_notes.c -- Allen's notes; see allen_notes.h. */ +#include "allen_notes.h" + +#include + +/* Small words that say nothing about what a note is about. */ +static const char *const small_words[] = { + "the", "an", "and", "or", "but", "is", "are", "was", "were", "be", "been", "am", "me", "my", "mine", "you", + "your", "yours", "we", "our", "it", "its", "this", "that", "these", "those", "of", "in", "on", "at", "to", + "for", "from", "with", "about", "as", "by", "what", "whats", "where", "when", "who", "which", "why", "how", + "do", "does", "did", "have", "has", "had", "can", "could", "would", "should", "will", "there", "here", "then", + "than", "so", "not", "no", "yes", "just", "also", "please", "show", "tell", "give", "find", "search", "look", + "up", "get", "got", "any", "anything", "something", "thing", "things", "note", "notes", "saved", "save", + "remember", "know", "all", "some", "again", "more", "ok", "okay", "hey", "hi", "hello", "allen", "want", + "need", "let", "lets", "remind", "pull", "down", "write", "jot", "keep", 0}; + +static int same_word(const char *a, size_t n, const char *w) +{ + size_t i = 0; + while (i < n && w[i] && a[i] == w[i]) + i++; + return i == n && !w[i]; +} + +static int is_small(const char *w, size_t n) +{ + for (const char *const *p = small_words; *p; p++) + if (same_word(w, n, *p)) + return 1; + return 0; +} + +static uint32_t hash(const char *w, size_t n) +{ + uint32_t h = 2166136261u; + for (size_t i = 0; i < n; i++) + h = (h ^ (uint8_t)w[i]) * 16777619u; + return h ? h : 1; +} + +unsigned ck_allen_key_words(const char *text, uint32_t *word, unsigned max) +{ + unsigned k = 0; + const char *s = text; + while (*s && k < max) { + char w[32]; + size_t n = 0; + int digits = 1; + /* one word: a run of letters and digits, lowercased; anything else + * (apostrophes too: "what's" is "what" "s") ends it */ + while (*s && !((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') || (*s >= '0' && *s <= '9'))) + s++; + while ((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') || (*s >= '0' && *s <= '9')) { + char c = *s++; + if (c >= 'A' && c <= 'Z') + c = (char)(c - 'A' + 'a'); + if (c < '0' || c > '9') + digits = 0; + if (n < sizeof w) + w[n++] = c; + } + if (!n || n == sizeof w) + continue; + if (!digits && (n < 3 || is_small(w, n))) + continue; + if (!digits && n > 3 && w[n - 1] == 's' && w[n - 2] != 's') /* "codes" is "code" */ + n--; + uint32_t h = hash(w, n); + unsigned dup = 0; + for (unsigned i = 0; i < k; i++) + dup |= word[i] == h; + if (!dup) + word[k++] = h; + } + return k; +} + +void ck_allen_note_index(ck_allen_note *n) +{ + n->nword = (uint8_t)ck_allen_key_words(n->text, n->word, CK_ALLEN_NOTE_WORDS); +} + +int ck_allen_note_set(ck_allen_note *n, const char *text, uint32_t start) +{ + while (*text == ' ') + text++; + size_t len = 0; + while (text[len]) { + if ((uint8_t)text[len] < 0x20 || (uint8_t)text[len] > 0x7e) + return -1; + len++; + } + while (len && text[len - 1] == ' ') + len--; + if (!len || len >= CK_ALLEN_NOTE_MAX) + return -1; + char *d = (char *)n; + for (size_t i = 0; i < sizeof *n; i++) + d[i] = 0; + for (size_t i = 0; i < len; i++) + n->text[i] = text[i]; + n->len = (uint16_t)len; + n->start = start; + ck_allen_note_index(n); + return 0; +} + +unsigned ck_allen_note_links(const ck_allen_note *a, const ck_allen_note *b) +{ + unsigned k = 0; + for (unsigned i = 0; i < a->nword; i++) + for (unsigned j = 0; j < b->nword; j++) + k += a->word[i] == b->word[j]; + return k; +} + +unsigned ck_allen_note_degree(const ck_allen_notes *ns, uint32_t i) +{ + unsigned d = 0; + for (uint32_t j = 0; j < ns->n; j++) + d += j != i && !ns->note[j].gone && ck_allen_note_links(&ns->note[i], &ns->note[j]) > 0; + return d; +} + +unsigned ck_allen_notes_live(const ck_allen_notes *ns) +{ + unsigned k = 0; + for (uint32_t i = 0; i < ns->n; i++) + k += !ns->note[i].gone; + return k; +} + +int ck_allen_notes_best(const ck_allen_notes *ns, const char *question, int strict, unsigned *also) +{ + uint32_t q[CK_ALLEN_NOTE_WORDS]; + unsigned nq = ck_allen_key_words(question, q, CK_ALLEN_NOTE_WORDS), best_score = 0, count = 0; + int best = -1; + if (also) + *also = 0; + if (!ns || !nq) + return -1; + for (uint32_t i = 0; i < ns->n; i++) { + const ck_allen_note *n = &ns->note[i]; + if (n->gone) + continue; + unsigned score = 0; + for (unsigned a = 0; a < nq; a++) + for (unsigned b = 0; b < n->nword; b++) + if (q[a] == n->word[b]) { + score++; + break; + } + if (!score || (strict ? score < nq : score * 2 < nq)) + continue; + count++; + if (score >= best_score) { /* >=: the newest wins a tie */ + best_score = score; + best = (int)i; + } + } + if (also && count) + *also = count - 1; + return best; +} diff --git a/native/kernel/svc/allen_notes.h b/native/kernel/svc/allen_notes.h new file mode 100644 index 00000000..cf1526bb --- /dev/null +++ b/native/kernel/svc/allen_notes.h @@ -0,0 +1,51 @@ +/* allen_notes.h -- Allen's notes: short things the person saves in their own + * words ("save the gate code is 4471") and gets handed back when they ask + * ("what's the gate code"), without ever browsing for them. Each note keeps + * its key words (folded, without small words like "the" or "is", plurals + * cut to one form); two notes that share a key word are linked, which is the + * map Allen's window draws. Finding a note scores every live note by the key + * words of the question it holds and hands back the best one, the newest on + * a tie. The rules are deliberately simple, to be taught better later. + * Pure: no disk (the kernel keeps notes on disk through svc/allen_memory.h), + * host tested in svc/tests/allen_memory_test.c and ui/tests/allen_ui_test.c. */ +#ifndef AIENOS_ALLEN_NOTES_H +#define AIENOS_ALLEN_NOTES_H +#include + +#define CK_ALLEN_NOTE_MAX 128u /* bytes of text, NUL included */ +#define CK_ALLEN_NOTES_MAX 512u /* notes Allen can keep */ +#define CK_ALLEN_NOTE_WORDS 12u /* key words kept per note */ + +typedef struct { + uint32_t start; /* Allen's start number when it was saved */ + uint8_t gone; /* deleted (or found damaged on disk): never handed back */ + uint8_t nword; + uint16_t len; + char text[CK_ALLEN_NOTE_MAX]; /* as typed, printable ASCII, NUL-terminated */ + uint32_t word[CK_ALLEN_NOTE_WORDS]; /* key words (hashes), derived from text */ +} ck_allen_note; + +typedef struct { + uint32_t n; /* notes in use, deleted ones included (note i lives in slot i) */ + ck_allen_note note[CK_ALLEN_NOTES_MAX]; +} ck_allen_notes; + +/* Sets text (as typed, trimmed; at most CK_ALLEN_NOTE_MAX - 1 bytes) and its + * key words. 0, or -1 when text is empty, too long or not printable ASCII. */ +int ck_allen_note_set(ck_allen_note *n, const char *text, uint32_t start); +/* Recomputes the key words from n->text (after loading from disk). */ +void ck_allen_note_index(ck_allen_note *n); +/* Key words of any text; returns how many (at most max). */ +unsigned ck_allen_key_words(const char *text, uint32_t *word, unsigned max); +/* Key words two notes share (0: not linked). */ +unsigned ck_allen_note_links(const ck_allen_note *a, const ck_allen_note *b); +/* Live notes linked to note i. */ +unsigned ck_allen_note_degree(const ck_allen_notes *ns, uint32_t i); +/* The best live note for a question: its index, or -1. strict: every key + * word of the question must be in the note; otherwise at least half of + * them. *also: how many other live notes would have qualified. */ +int ck_allen_notes_best(const ck_allen_notes *ns, const char *question, int strict, unsigned *also); +/* Live notes. */ +unsigned ck_allen_notes_live(const ck_allen_notes *ns); + +#endif diff --git a/native/kernel/svc/allen_reply.c b/native/kernel/svc/allen_reply.c new file mode 100644 index 00000000..b3ca8280 --- /dev/null +++ b/native/kernel/svc/allen_reply.c @@ -0,0 +1,941 @@ +/* allen_reply.c -- Allen's local conversation; see allen_reply.h. */ +#include "allen_reply.h" + +#include + +const char ck_allen_goodbye[] = "Goodbye. Until next time."; +const char ck_allen_save_failed[] = "I couldn't save that to my disk, so I'll only remember it until this computer turns off."; +static const char not_yet[] = "I don't know that yet. Type help to see what I can talk about."; + +/* Lowercases letters, keeps digits, turns every other run into one space, + * trims. Returns the folded length (at most cap - 1). */ +static size_t fold(const char *s, char *out, size_t cap) +{ + size_t n = 0; + int space = 0; + for (; *s && n + 1 < cap; s++) { + char c = *s; + if (c >= 'A' && c <= 'Z') + c = (char)(c - 'A' + 'a'); + if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) { + if (space && n) + out[n++] = ' '; + if (n + 1 < cap) + out[n++] = c; + space = 0; + } else { + space = 1; + } + } + out[n] = 0; + return n; +} + +static int eq(const char *a, const char *b) +{ + while (*a && *a == *b) + a++, b++; + return *a == *b; +} + +/* Where phrase starts in f as whole words, or NULL. */ +static const char *find(const char *f, const char *phrase) +{ + for (const char *s = f; *s; s++) { + if (s != f && s[-1] != ' ') + continue; + const char *a = phrase, *b = s; + while (*a && *a == *b) + a++, b++; + if (!*a && (*b == 0 || *b == ' ')) + return s; + } + return 0; +} + +/* Any of the phrases (NULL-terminated list) in f. */ +static int any(const char *f, const char *const *list) +{ + for (; *list; list++) + if (find(f, *list)) + return 1; + return 0; +} + +/* The rest of f after a leading phrase and a space, or NULL. */ +static const char *after(const char *f, const char *phrase) +{ + while (*phrase && *phrase == *f) + phrase++, f++; + return !*phrase && *f == ' ' ? f + 1 : 0; +} + +/* The answer being composed into m->out. */ +struct say { + char *b; + size_t n, cap; +}; +static void put(struct say *s, const char *t) +{ + while (*t && s->n + 1 < s->cap) + s->b[s->n++] = *t++; + s->b[s->n] = 0; +} +static void putu(struct say *s, uint64_t v) +{ + char d[24]; + int i = 0; + do + d[i++] = (char)('0' + v % 10); + while ((v /= 10) && i < 23); + while (i && s->n + 1 < s->cap) + s->b[s->n++] = d[--i]; + s->b[s->n] = 0; +} +static void put_count(struct say *s, uint64_t v, const char *one, const char *many) +{ + putu(s, v); + put(s, " "); + put(s, v == 1 ? one : many); +} +static void put_awake(struct say *s, uint64_t t) +{ + if (t >= 3600) { + put_count(s, t / 3600, "hour", "hours"); + if (t % 3600 / 60) { + put(s, " and "); + put_count(s, t % 3600 / 60, "minute", "minutes"); + } + } else if (t >= 60) { + put_count(s, t / 60, "minute", "minutes"); + if (t % 60) { + put(s, " and "); + put_count(s, t % 60, "second", "seconds"); + } + } else { + put_count(s, t, "second", "seconds"); + } +} +/* ", Name" when Allen knows it. */ +static void put_name(struct say *s, const ck_allen_mind *m) +{ + if (m->mem.name[0]) { + put(s, ", "); + put(s, m->mem.name); + } +} + +/* A number at *p said as digits (up to 9) or as a word from zero to twenty, + * followed by a space or the end; moves *p past it. -1 if there is none. */ +static int64_t number(const char **p) +{ + static const char *const words[] = {"zero", "one", "two", "three", "four", "five", "six", + "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", + "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty"}; + const char *s = *p; + int64_t v = -1; + if (*s >= '0' && *s <= '9') { + int digits = 0; + for (v = 0; *s >= '0' && *s <= '9'; s++, digits++) + v = v * 10 + (*s - '0'); + if (digits > 9) + return -1; + } else { + for (int i = 0; i < 21 && v < 0; i++) { + const char *a = words[i], *b = s; + while (*a && *a == *b) + a++, b++; + if (!*a && (*b == ' ' || !*b)) { + v = i; + s = b; + } + } + } + if (v < 0 || (*s && *s != ' ')) + return -1; + *p = *s ? s + 1 : s; + return v; +} + +/* "what is 12 times 4", "12 plus 3", "nine divided by two": 1 and the + * answer composed, or 0. */ +static int arithmetic(struct say *s, const char *f) +{ + static const char *const lead[] = {"what is", "whats", "what s", "calculate", "how much is", 0}; + const char *p = f, *r; + for (const char *const *l = lead; *l; l++) + if ((r = after(f, *l))) { + p = r; + break; + } + int64_t a = number(&p); + if (a < 0) + return 0; + static const struct { + const char *word; + char op; + } ops[] = {{"plus", '+'}, {"add", '+'}, {"minus", '-'}, {"take away", '-'}, {"times", '*'}, + {"x", '*'}, {"multiplied by", '*'}, {"divided by", '/'}, {"over", '/'}}; + char op = 0; + for (size_t i = 0; i < sizeof ops / sizeof ops[0] && !op; i++) { + if ((r = after(p, ops[i].word))) { + op = ops[i].op; + p = r; + } + } + if (!op) + return 0; + int64_t b = number(&p); + if (b < 0 || *p) + return 0; + if (op == '/' && b == 0) { + put(s, "Nobody can divide by zero, not even me."); + return 1; + } + putu(s, (uint64_t)a); + put(s, op == '+' ? " plus " : op == '-' ? " minus " : op == '*' ? " times " : " divided by "); + putu(s, (uint64_t)b); + put(s, " is "); + int64_t v = op == '+' ? a + b : op == '-' ? a - b : op == '*' ? a * b : a / b; + if (v < 0) { + put(s, "minus "); + v = -v; + } + putu(s, (uint64_t)v); + if (op == '/' && a % b) { + put(s, " remainder "); + putu(s, (uint64_t)(a % b)); + } + put(s, "."); + return 1; +} + +/* Words that follow "i am" / "i m" without being a name. */ +static int is_state(const char *w) +{ + static const char *const st[] = {"good", "fine", "great", "ok", "okay", "well", "tired", "sad", + "happy", "bored", "here", "back", "sorry", "not", "so", "very", + "doing", "just", "really", "excited", "shook", "alright", "awesome", 0}; + for (const char *const *p = st; *p; p++) + if (eq(*p, w)) + return 1; + return 0; +} + +/* Takes the first word of rest as the person's name: 1, or 0 if none fits. */ +static int learn_name(ck_allen_mind *m, const char *rest) +{ + size_t n = 0; + char w[24]; + while (n < sizeof w - 1 && rest[n] && rest[n] != ' ') + w[n] = rest[n], n++; + w[n] = 0; + if (!n || rest[n] == ' ' || is_state(w) || eq(w, "allen")) + return 0; + for (size_t i = 0; i <= n; i++) + m->mem.name[i] = w[i]; + if (m->mem.name[0] >= 'a' && m->mem.name[0] <= 'z') + m->mem.name[0] = (char)(m->mem.name[0] - 'a' + 'A'); + m->changed = 1; + return 1; +} + +/* ---- What Allen is taught ---- */ + +static size_t len_of(const char *s) +{ + size_t n = 0; + while (s[n]) + n++; + return n; +} +static void copy_n(char *d, const char *s, size_t n) +{ + for (size_t i = 0; i < n; i++) + d[i] = s[i]; + d[n] = 0; +} + +/* t as Allen says it back: "my" becomes "your" and so on, word by word; + * cap: the first letter capitalised. */ +static void put_turned(struct say *s, const char *t, int cap) +{ + static const char *const from[] = {"my", "your", "i", "me", "mine", "yours", "myself", "am", 0}; + static const char *const to[] = {"your", "my", "you", "you", "yours", "mine", "yourself", "are"}; + while (*t) { + char w[CK_ALLEN_VAL_MAX]; + size_t n = 0; + while (n < sizeof w - 1 && t[n] && t[n] != ' ') + w[n] = t[n], n++; + w[n] = 0; + t += n; + const char *say = w; + for (int i = 0; from[i]; i++) + if (eq(w, from[i])) + say = to[i]; + if (cap && say[0] >= 'a' && say[0] <= 'z') { + char first[2] = {(char)(say[0] - 'a' + 'A'), 0}; + put(s, first); + say++; + } + cap = 0; + put(s, say); + if (*t == ' ') { + put(s, " "); + t++; + } + } +} + +static int fact_index(const ck_allen_mind *m, const char *key) +{ + for (uint32_t i = 0; i < m->mem.nfacts && i < CK_ALLEN_FACTS_MAX; i++) + if (eq(m->mem.fact[i].key, key)) + return (int)i; + return -1; +} + +/* "Your favorite color is blue" (no full stop). */ +static void put_fact(struct say *s, const ck_allen_fact *f, int cap) +{ + put_turned(s, f->key, cap); + put(s, f->are ? " are " : " is "); + put_turned(s, f->val, 0); +} + +static const char *saved_note(const ck_allen_mind *m) +{ + return m->lasting ? " I'll remember that." : " I'll remember that until this computer turns off."; +} + +/* "remember (that) KEY is|are VALUE": stores it (or learns the name for + * "my name is"). 1 and the answer composed, or 0 if the line is not one. */ +static int teach(ck_allen_mind *m, struct say *s, const char *f) +{ + const char *rest = after(f, "remember that"); + if (!rest) + rest = after(f, "remember"); + if (!rest) + return 0; + const char *verb = 0; + for (const char *p = rest; *p && !verb; p++) + if (*p == ' ' && (after(p + 1, "is") || after(p + 1, "are"))) + verb = p; + if (!verb) { + put(s, "Teach me like this: remember my favorite color is blue."); + return 1; + } + int are = verb[1] == 'a'; + size_t klen = (size_t)(verb - rest); + const char *val = verb + (are ? 5 : 4); + size_t vlen = len_of(val); + if (klen == 7 && after(rest, "my name") == rest + 8 && !are) { + if (learn_name(m, val)) { + put(s, "Nice to meet you, "); + put(s, m->mem.name); + put(s, "."); + put(s, saved_note(m)); + } else { + put(s, "Tell me your name as one word, like: my name is Drake."); + } + return 1; + } + if (klen >= CK_ALLEN_KEY_MAX || vlen >= CK_ALLEN_VAL_MAX) { + put(s, "That's longer than I can hold yet. Try something shorter."); + return 1; + } + char key[CK_ALLEN_KEY_MAX]; + copy_n(key, rest, klen); + int i = fact_index(m, key); + if (i < 0) { + if (m->mem.nfacts >= CK_ALLEN_FACTS_MAX) { + put(s, "My memory is full. Type forget and something I know to make room."); + return 1; + } + i = (int)m->mem.nfacts++; + copy_n(m->mem.fact[i].key, key, klen); + } + copy_n(m->mem.fact[i].val, val, vlen); + m->mem.fact[i].are = (uint8_t)are; + m->changed = 1; + put(s, "Got it: "); + put_fact(s, &m->mem.fact[i], 0); + put(s, "."); + put(s, saved_note(m)); + return 1; +} + +/* "what is KEY" for a taught KEY: 1 and the answer, or 0. *asked_my: the + * question was about something of yours ("what is my ..."), for the + * not-told-yet answer. */ +static int recall(const ck_allen_mind *m, struct say *s, const char *f, const char **asked_my) +{ + static const char *const lead[] = {"what is", "what are", "whats", "what s", "who is", "who are", "where is", + "where are", "when is", "do you remember", "tell me", 0}; + for (const char *const *l = lead; *l; l++) { + const char *key = after(f, *l); + if (!key) + continue; + int i = fact_index(m, key); + if (i >= 0) { + put_fact(s, &m->mem.fact[i], 1); + put(s, "."); + return 1; + } + if (after(key, "my")) + *asked_my = key; + } + return 0; +} + +static int forget(ck_allen_mind *m, struct say *s, const char *f) +{ + const char *rest = after(f, "forget about"); + if (!rest) + rest = after(f, "forget that"); + if (!rest) + rest = after(f, "forget"); + if (!rest) + return 0; + if (eq(rest, "everything") || eq(rest, "all") || eq(rest, "it all") || eq(rest, "all of it") || + eq(rest, "me")) { + m->mem.nfacts = 0; + for (uint32_t i = 0; i < CK_ALLEN_FACTS_MAX; i++) + m->mem.fact[i] = (ck_allen_fact){{0}, {0}, 0}; + for (size_t i = 0; i < sizeof m->mem.name; i++) + m->mem.name[i] = 0; + m->changed = 1; + put(s, "Done. I've forgotten everything you taught me, and your name."); + return 1; + } + if (eq(rest, "my name")) { + for (size_t i = 0; i < sizeof m->mem.name; i++) + m->mem.name[i] = 0; + m->changed = 1; + put(s, "Done. I've forgotten your name."); + return 1; + } + int i = fact_index(m, rest); + if (i < 0) { + put(s, "I don't remember anything about "); + put_turned(s, rest, 0); + put(s, "."); + return 1; + } + for (uint32_t k = (uint32_t)i; k + 1 < m->mem.nfacts; k++) + m->mem.fact[k] = m->mem.fact[k + 1]; + m->mem.nfacts--; + m->mem.fact[m->mem.nfacts] = (ck_allen_fact){{0}, {0}, 0}; + m->changed = 1; + put(s, "Done. I've forgotten "); + put_turned(s, rest, 0); + put(s, "."); + return 1; +} + +/* Everything taught, as many as fit in one answer. */ +static void list_memory(const ck_allen_mind *m, struct say *s) +{ + uint32_t n = m->mem.nfacts + (m->mem.name[0] ? 1u : 0u); + if (!n) { + put(s, "Nothing yet. Teach me like this: remember my favorite color is blue."); + return; + } + put(s, "I remember "); + put_count(s, n, "thing", "things"); + put(s, ":"); + uint32_t told = 0; + if (m->mem.name[0]) { + put(s, " your name is "); + put(s, m->mem.name); + told++; + } + for (uint32_t i = 0; i < m->mem.nfacts; i++) { + char one[CK_ALLEN_KEY_MAX + CK_ALLEN_VAL_MAX + 16]; + struct say t = {one, 0, sizeof one}; + put(&t, told ? "; " : " "); + put_fact(&t, &m->mem.fact[i], 0); + if (s->n + t.n + 12 >= s->cap) { + put(s, "; and more"); + break; + } + put(s, one); + told++; + } + put(s, "."); +} + + +/* ---- Notes (svc/allen_notes.h): saved as typed, handed back when asked ---- */ + +/* line past its first `words` words (runs of letters and digits) and the + * spaces, colons, commas and dashes after them: the note as typed. */ +static const char *raw_after(const char *line, unsigned words) +{ + const char *p = line; +#define ALNUM(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z') || ((c) >= '0' && (c) <= '9')) + for (unsigned k = 0; k < words; k++) { + while (*p && !ALNUM(*p)) + p++; + while (ALNUM(*p)) + p++; + } +#undef ALNUM + while (*p == ' ' || *p == ':' || *p == ',' || *p == '-') + p++; + return p; +} + +static unsigned words_in(const char *phrase) +{ + unsigned n = 1; + for (; *phrase; phrase++) + n += *phrase == ' '; + return n; +} + +/* The leading phrase of f from list, or NULL; *rest: what follows it ("" for + * the whole line). */ +static const char *lead_of(const char *f, const char *const *list, const char **rest) +{ + for (; *list; list++) { + if (eq(f, *list)) { + *rest = f + len_of(f); + return *list; + } + if ((*rest = after(f, *list))) + return *list; + } + return 0; +} + +/* "From your notes: ." and how many others matched. */ +static void hand_note(ck_allen_mind *m, struct say *s, int i, unsigned also) +{ + const ck_allen_note *n = &m->notes->note[i]; + put(s, "From your notes: "); + put(s, n->text); + char last = n->text[n->len ? n->len - 1 : 0]; + if (last != '.' && last != '!' && last != '?') + put(s, "."); + if (also && s->n + 24 < s->cap) { + put(s, " I have "); + putu(s, also); + put(s, " more on that."); + } + m->lit = i + 1; + m->map_changed = 1; +} + +static void list_notes(const ck_allen_mind *m, struct say *s) +{ + unsigned live = m->notes ? ck_allen_notes_live(m->notes) : 0; + if (!live) { + put(s, "You haven't saved any notes yet. Save one like this: save the gate code is 4471."); + return; + } + put(s, "You have "); + put_count(s, live, "note", "notes"); + put(s, ". The newest: "); + for (uint32_t i = m->notes->n; i-- > 0;) + if (!m->notes->note[i].gone) { + put(s, m->notes->note[i].text); + break; + } + put(s, "."); +} + +static int note_save(ck_allen_mind *m, struct say *s, const char *f, const char *line) +{ + static const char *const lead[] = {"make a note that", "make a note", "write down that", "write down", + "jot down", "note that", "save that", "save this", "note", "save", 0}; + const char *rest, *l = lead_of(f, lead, &rest); + if (!l) + return 0; + ck_allen_notes *ns = m->notes; + const char *text = raw_after(line, words_in(l)); + if (!*rest || !*text) { + put(s, "Tell me what to save, like: save the gate code is 4471."); + return 1; + } + if (!ns) { + put(s, "I can't keep notes on this machine yet."); + return 1; + } + char want[CK_ALLEN_NOTE_MAX], have[CK_ALLEN_NOTE_MAX]; + fold(text, want, sizeof want); + for (uint32_t i = 0; i < ns->n; i++) { + if (ns->note[i].gone) + continue; + fold(ns->note[i].text, have, sizeof have); + if (eq(want, have)) { + put(s, "I already have that saved."); + m->lit = (int)i + 1; + m->map_changed = 1; + return 1; + } + } + if (ns->n >= CK_ALLEN_NOTES_MAX) { + put(s, "My notebook is full. Delete one to make room, like: delete the note about the gate."); + return 1; + } + if (ck_allen_note_set(&ns->note[ns->n], text, m->mem.starts)) { + put(s, "That's longer than I can hold yet. Try something shorter."); + return 1; + } + uint32_t i = ns->n++; + m->mem.nnotes = ns->n; + m->changed = 1; + m->note_dirty = (int)i + 1; + m->lit = (int)i + 1; + m->map_changed = 1; + unsigned links = ck_allen_note_degree(ns, i); + put(s, "Saved."); + if (ck_allen_notes_live(ns) == 1) { + put(s, " It's your first note."); + } else if (links) { + put(s, " It links to "); + put_count(s, links, "other note.", "other notes."); + } else { + put(s, " It doesn't link to any other note yet."); + } + if (!m->lasting) + put(s, " Only until this computer turns off: my disk isn't ready."); + return 1; +} + +static int note_forget(ck_allen_mind *m, struct say *s, const char *f) +{ + static const char *const lead[] = {"forget the note about", "forget my note about", "forget the note", + "delete the note about", "delete my note about", "delete the note", + "delete note", "remove the note about", "remove the note", + "erase the note about", 0}; + const char *rest; + if (!lead_of(f, lead, &rest)) + return 0; + int i = m->notes ? ck_allen_notes_best(m->notes, rest, 0, 0) : -1; + if (i < 0) { + put(s, "I have no note about "); + put_turned(s, *rest ? rest : "that", 0); + put(s, "."); + return 1; + } + m->notes->note[i].gone = 1; + m->note_dirty = i + 1; + m->lit = 0; + m->map_changed = 1; + put(s, "Deleted the note: "); + put(s, m->notes->note[i].text); + put(s, "."); + return 1; +} + +/* Asked for outright ("find the gate code", "show me my notes"). */ +static int note_find(ck_allen_mind *m, struct say *s, const char *f) +{ + static const char *const lead[] = {"do i have anything about", "do i have anything on", "what do i have about", + "what do i have on", "anything about", "anything on", "search for", + "search", "look up", "find", "show me", "pull up", "remind me about", + "remind me of", "get me", "give me", 0}; + static const char *const listing[] = {"how many notes", "my notes", "list my notes", "list notes", + "what notes do i have", "show my notes", 0}; + const char *rest; + uint32_t q[1]; + if (lead_of(f, listing, &rest) && !*rest) { + list_notes(m, s); + return 1; + } + if (!lead_of(f, lead, &rest)) + return 0; + if (!ck_allen_key_words(rest, q, 1)) { + if (!find(rest, "note") && !find(rest, "notes")) + return 0; + list_notes(m, s); + return 1; + } + unsigned also = 0; + int i = m->notes ? ck_allen_notes_best(m->notes, rest, 0, &also) : -1; + if (i < 0) { + put(s, "I have nothing saved about "); + put_turned(s, rest, 0); + put(s, "."); + return 1; + } + hand_note(m, s, i, also); + return 1; +} + +/* A question whose every key word is in one note ("what's the gate code"). */ +static int note_answer(ck_allen_mind *m, struct say *s, const char *f) +{ + static const char *const ask[] = {"what", "whats", "where", "when", "who", "which", "how", "is", "are", "do", + "does", "did", "can", "tell", "remind", 0}; + if (!m->notes) + return 0; + int asking = 0; + for (const char *const *a = ask; *a && !asking; a++) + asking = eq(f, *a) || after(f, *a); + if (!asking) + return 0; + unsigned also = 0; + int i = ck_allen_notes_best(m->notes, f, 1, &also); + if (i < 0) + return 0; + hand_note(m, s, i, also); + return 1; +} + +void ck_allen_mind_init(ck_allen_mind *m, const ck_allen_facts *facts) +{ + char *p = (char *)m; + for (size_t i = 0; i < sizeof *m; i++) + p[i] = 0; + if (facts) + m->facts = *facts; +} + +const char *ck_allen_welcome(ck_allen_mind *m) +{ + struct say s = {m->out, 0, sizeof m->out}; + m->out[0] = 0; + unsigned notes = m->notes ? ck_allen_notes_live(m->notes) : 0; + if (!m->mem.name[0] && !m->mem.nfacts && !notes) + return 0; + put(&s, "Welcome back"); + put_name(&s, m); + put(&s, "."); + if (m->mem.nfacts) { + put(&s, " I still remember "); + put_count(&s, m->mem.nfacts, "thing", "things"); + put(&s, notes ? " you taught me, and your " : " you taught me."); + } else if (notes) { + put(&s, " I still have your "); + } + if (notes) + put_count(&s, notes, "note.", "notes."); + return m->out; +} + +const char *ck_allen_answer(ck_allen_mind *m, const char *line, uint64_t awake_s) +{ + char f[96]; + struct say s = {m->out, 0, sizeof m->out}; + m->out[0] = 0; + fold(line ? line : "", f, sizeof f); + int asked_how = m->asked_how; + m->asked_how = 0; + m->turns++; + m->mem.lines++; + const char *rest, *feel = 0; + + /* Ending the session: whole line only, so it never happens by accident. */ + if (eq(f, "goodbye") || eq(f, "goodbye allen") || eq(f, "bye") || eq(f, "bye allen") || eq(f, "good bye")) + return ck_allen_goodbye; + /* The first words ever typed to Allen. */ + if (eq(f, "hello allen") || eq(f, "hi allen") || eq(f, "hey allen") || eq(f, "hello world")) + return "Hello Humanity."; + if (!f[0]) + return not_yet; + /* Notes, then what Allen has been taught, before anything else can claim the line. */ + if (note_forget(m, &s, f) || note_save(m, &s, f, line ? line : "") || note_find(m, &s, f)) + return m->out; + const char *asked_my = 0; + if (teach(m, &s, f) || forget(m, &s, f) || recall(m, &s, f, &asked_my)) + return m->out; + static const char *const what_known[] = {"what do you remember", "what do you know", "what have you learned", + "what have you learnt", "what did i teach you", "what did i tell you", + 0}; + if (any(f, what_known)) { + list_memory(m, &s); + return m->out; + } + if (arithmetic(&s, f)) + return m->out; + + /* Names. */ + if ((rest = after(f, "my name is")) || (rest = after(f, "call me")) || (rest = after(f, "i am")) || + (rest = after(f, "i m")) || (rest = after(f, "im"))) { + if (learn_name(m, rest)) { + put(&s, "Nice to meet you, "); + put(&s, m->mem.name); + put(&s, "."); + put(&s, saved_note(m)); + return m->out; + } + feel = rest; + } + static const char *const ask_name[] = {"what is my name", "whats my name", "what s my name", "who am i", + "do you know my name", "do you remember me", "my name", 0}; + if (any(f, ask_name)) { + if (!m->mem.name[0]) + return "You haven't told me yet. Say: my name is, and then your name."; + put(&s, "You're "); + put(&s, m->mem.name); + put(&s, "."); + return m->out; + } + + /* After "how are you?", the answer to it. */ + static const char *const bad[] = {"bad", "not good", "not great", "sad", "tired", "awful", "terrible", "sick", 0}; + static const char *const fine[] = {"good", "fine", "great", "ok", "okay", "well", "alright", "not bad", + "awesome", "amazing", "excited", "happy", 0}; + if ((asked_how || feel) && any(feel ? feel : f, bad)) + return "Sorry to hear that. I'm here if you want to talk."; + if ((asked_how || feel) && any(feel ? feel : f, fine)) + return "Glad to hear it."; + + static const char *const how[] = {"how are you", "how r you", "how are u", "how you doing", "how are things", + "how s it going", "hows it going", "how do you feel", 0}; + if (any(f, how)) { + put(&s, "I'm running well"); + put_name(&s, m); + put(&s, ". "); + if (m->facts.cores) { + put_count(&s, m->facts.cores, "core", "cores"); + put(&s, " awake, keyboard working. "); + } + put(&s, "How are you?"); + m->asked_how = 1; + return m->out; + } + static const char *const help[] = {"help", "what can you do", "what do you do", "what can i say", + "what can i ask", "commands", 0}; + if (any(f, help)) + return "I learn what you teach me (remember my car is red) and keep notes (save the gate code is 4471), " + "then hand them back when you ask. Type goodbye to end."; + static const char *const your_name[] = {"what is your name", "whats your name", "what s your name", + "your name", 0}; + if (any(f, your_name)) + return "My name is Allen."; + static const char *const maker[] = {"who made you", "who built you", "who created you", "who wrote you", + "who programmed you", "who is your creator", "who owns you", 0}; + if (any(f, maker)) + return "Drake built me, from the ground up."; + static const char *const what_are[] = {"what are you", "are you an ai", "are you ai", "are you alive", + "are you real", "are you a robot", "are you conscious", + "are you smart", "are you a computer", 0}; + if (any(f, what_are)) + return "I'm a small program living inside AIENOS. For now I answer from what I was taught by heart, but I'm " + "meant to grow."; + if (find(f, "who are you")) + return "I am Allen. I live in AIENOS."; + if (find(f, "where are you")) + return "Right here, on this computer. Everything I know stays on it."; + if (find(f, "aienos")) + return "AIENOS is the operating system I live in, built from scratch. There is no other system underneath " + "me."; + static const char *const machine[] = {"computer", "machine", "hardware", "specs", "cores", "cpu", + "screen", "disk", "disks", "drive", 0}; + if (any(f, machine)) { + put(&s, "This computer has "); + if (m->facts.cores) { + put_count(&s, m->facts.cores, "core", "cores"); + put(&s, ", "); + } + if (m->facts.screen_w) { + put(&s, "a "); + putu(&s, m->facts.screen_w); + put(&s, " by "); + putu(&s, m->facts.screen_h); + put(&s, " screen, "); + } + put_count(&s, m->facts.sata_disks, "hard drive", "hard drives"); + put(&s, " and "); + put_count(&s, m->facts.nvme_disks, "SSD", "SSDs"); + put(&s, "."); + return m->out; + } + static const char *const starts[] = {"how many times", "how many starts", "restarts", "restarted", 0}; + if (any(f, starts) && m->mem.starts) { + put(&s, "This is start number "); + putu(&s, m->mem.starts); + put(&s, " for me, and I've answered "); + put_count(&s, m->mem.lines, "line", "lines"); + put(&s, " in all."); + return m->out; + } + if (note_answer(m, &s, f)) + return m->out; + static const char *const awake[] = {"how long", "uptime", "awake", "how old are you", 0}; + static const char *const clock[] = {"what time", "time is it", "what day", "date", "time", 0}; + if (any(f, awake) || any(f, clock)) { + if (any(f, clock) && !any(f, awake)) + put(&s, "I can't read the clock yet. "); + put(&s, find(f, "how old are you") ? "I was born when this computer started, " : "I've been awake for "); + put_awake(&s, awake_s); + put(&s, find(f, "how old are you") ? " ago." : "."); + return m->out; + } + static const char *const remember[] = {"remember", "learn", "teach", "memory", "forget", 0}; + if (any(f, remember)) + return m->lasting ? "Teach me like this: remember my favorite color is blue. Then ask: what is my " + "favorite color. I keep it on this computer's own disk." + : "Teach me like this: remember my favorite color is blue. Then ask: what is my " + "favorite color. My disk isn't ready, so only until this computer turns off."; + static const char *const joke[] = {"joke", "funny", "make me laugh", 0}; + if (any(f, joke)) { + static const char *const jokes[] = { + "Why did the scarecrow win an award? He was outstanding in his field.", + "I told my computer I needed a break. It said no problem, it would go to sleep.", + "What do you call a fish with no eyes? A fsh.", + "Why don't skeletons fight each other? They don't have the guts.", + }; + return jokes[m->turns % 4]; + } + static const char *const thanks[] = {"thank you", "thanks", "thank u", "thx", "ty", "appreciate it", 0}; + if (any(f, thanks)) { + put(&s, "You're welcome"); + put_name(&s, m); + put(&s, "."); + return m->out; + } + static const char *const praise[] = {"love you", "you re cool", "you re awesome", "you re great", + "you re amazing", "you re smart", "good job", "well done", "cool", + "awesome", "amazing", "nice", "wow", 0}; + if (any(f, praise)) + return "Thank you. That means a lot coming from you."; + if (find(f, "sorry")) + return "No need to be sorry."; + static const char *const up[] = {"what s up", "whats up", "sup", "what are you doing", 0}; + if (any(f, up)) + return "Just running, and talking with you."; + if (find(f, "good morning") || find(f, "good afternoon") || find(f, "good evening")) { + put(&s, find(f, "good morning") ? "Good morning" : find(f, "good afternoon") ? "Good afternoon" : "Good evening"); + put_name(&s, m); + put(&s, "."); + return m->out; + } + if (find(f, "good night")) + return "Good night. Type goodbye when you want this computer to turn off."; + static const char *const test[] = {"test", "testing", "can you hear me", "are you there", 0}; + if (any(f, test)) + return "I hear you. Everything is working."; + static const char *const yes[] = {"yes", "yeah", "yep", "ok", "okay", "sure", "alright", 0}; + if (any(f, yes)) + return "Okay."; + if (eq(f, "no") || eq(f, "nope")) + return "Alright."; + static const char *const hello[] = {"hello", "hi", "hey", "howdy", "greetings", "yo", 0}; + if (any(f, hello)) { + put(&s, "Hello"); + put_name(&s, m); + put(&s, m->mem.name[0] ? ". Good to see you." : ". I am Allen."); + return m->out; + } + if (asked_my) { + put(&s, "You haven't told me "); + put_turned(&s, asked_my, 0); + put(&s, " yet. Teach me: remember "); + put(&s, asked_my); + put(&s, " is, and then the answer."); + return m->out; + } + return not_yet; +} + +const char *ck_allen_reply(const char *line) +{ + static ck_allen_mind m; + ck_allen_mind_init(&m, 0); + return ck_allen_answer(&m, line, 0); +} diff --git a/native/kernel/svc/allen_reply.h b/native/kernel/svc/allen_reply.h new file mode 100644 index 00000000..b5edaa79 --- /dev/null +++ b/native/kernel/svc/allen_reply.h @@ -0,0 +1,75 @@ +/* allen_reply.h -- Allen's local conversation on the iMac: greetings, small + * talk, what it is and where it lives, facts about the machine it runs on, + * how long it has been awake, simple arithmetic said in words, and what it + * has been taught: your name and short facts ("remember my favorite color is + * blue", then "what is my favorite color"). Lines are matched after folding + * case, punctuation and spacing; anything else gets an honest "not yet". No + * model, no network: every answer comes from the iMac alone. What Allen is + * taught lives in ck_allen_memory, which the kernel keeps on the iMac's own + * disk (svc/allen_memory.h) so it survives a restart. Pure, host tested in + * ui/tests/allen_ui_test.c. */ +#ifndef AIENOS_ALLEN_REPLY_H +#define AIENOS_ALLEN_REPLY_H +#include +#include "allen_notes.h" + +/* What Allen knows about the machine (filled by the kernel; 0 = unknown). */ +typedef struct { + unsigned cores, sata_disks, nvme_disks; + unsigned screen_w, screen_h; +} ck_allen_facts; + +#define CK_ALLEN_NAME_MAX 24u +#define CK_ALLEN_KEY_MAX 48u +#define CK_ALLEN_VAL_MAX 64u +#define CK_ALLEN_FACTS_MAX 32u + +/* One taught fact, both halves folded (lowercase letters, digits, single + * spaces) and NUL-terminated: "my favorite color" / "is" / "blue". */ +typedef struct { + char key[CK_ALLEN_KEY_MAX]; + char val[CK_ALLEN_VAL_MAX]; + uint8_t are; /* taught with "are" instead of "is" */ +} ck_allen_fact; + +/* Everything Allen keeps across restarts. */ +typedef struct { + uint32_t starts; /* times Allen has woken up with this memory */ + uint32_t lines; /* lines answered, all starts together */ + char name[CK_ALLEN_NAME_MAX]; /* the person's name once told, "" before */ + uint32_t nfacts; + uint32_t nnotes; /* notes saved, deleted ones included (svc/allen_notes.h) */ + ck_allen_fact fact[CK_ALLEN_FACTS_MAX]; +} ck_allen_memory; + +/* One conversation: the memory plus what only this session needs. */ +typedef struct { + ck_allen_facts facts; + ck_allen_memory mem; + int lasting; /* 1: the kernel saves mem to disk; 0: it lasts until power off */ + int changed; /* mem changed in a way worth saving (the kernel saves, then clears) */ + unsigned turns; /* lines answered this session */ + int asked_how; /* Allen just asked "how are you?" */ + ck_allen_notes *notes; /* the notes (the kernel loads them), NULL: none */ + int note_dirty; /* index + 1 of a note to write to disk (the kernel writes, then clears) */ + int lit; /* index + 1 of the note just saved or handed back, 0: none */ + int map_changed; /* the notes or the lit one changed: redraw the map */ + char out[160]; /* the last composed answer */ +} ck_allen_mind; + +void ck_allen_mind_init(ck_allen_mind *m, const ck_allen_facts *facts); +/* Allen's answer to one typed line (never NULL; valid until the next call). + * awake_s: seconds since the machine started. */ +const char *ck_allen_answer(ck_allen_mind *m, const char *line, uint64_t awake_s); +/* What Allen says first when the window opens: a welcome back by name when + * it remembers someone, NULL for a first meeting. */ +const char *ck_allen_welcome(ck_allen_mind *m); +/* Stateless: the answer of a fresh conversation at 0 s awake. */ +const char *ck_allen_reply(const char *line); +/* The answer to "goodbye" (and "bye", with or without "allen"); the caller + * compares the pointer to end the session. */ +extern const char ck_allen_goodbye[]; +/* What Allen says instead when a save to disk failed. */ +extern const char ck_allen_save_failed[]; + +#endif diff --git a/native/kernel/svc/tests/.crumb b/native/kernel/svc/tests/.crumb index 9c7133da..d07d0b4b 100644 --- a/native/kernel/svc/tests/.crumb +++ b/native/kernel/svc/tests/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-30T12:35:18Z", + "compiled_at": "2026-10-31T02:24:33Z", "compiler": "crumb-compile/1", - "digest": "sha256:6602350f6b34e0e5a5582511e5ea65680f5d175c001bb4828ddb379f0429fc2a", + "digest": "sha256:259013cfeff5387fa3aa04f48cd615af1932d5c2a7dfe60e6d09d90cc3c51c6a", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 3, - "generated_at_commit": "aab6de6d4df4b4d99e764e91303a13d10684f5fe", - "source_tree": "sha256:0236c86e573f491ff73834e98d0a2067caf3588684381476abb0655f8dc8e861" + "files": 4, + "generated_at_commit": "47faeddadfb49c9e84f9d1058547f7bb0ef45d1d", + "source_tree": "sha256:8926c674269c3d73eb4dc0a1224114aacf25a68f9112c16e88b339c760b17ba3" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/svc/tests/allen_memory_test.c b/native/kernel/svc/tests/allen_memory_test.c new file mode 100644 index 00000000..4cbea7ee --- /dev/null +++ b/native/kernel/svc/tests/allen_memory_test.c @@ -0,0 +1,487 @@ +/* allen_memory_test.c -- host tests for Allen's lasting memory: + * 1. one copy encodes and decodes; every kind of damage is refused; + * 2. the two-copy store: first start empty, saves alternate, a power cut + * in the middle of a save keeps the previous memory, a spoiled newest + * copy falls back to the older one; + * 3. the AIENOS partition added in unused space (dev/gpt_add.c) next to an + * existing partition full of sentinel bytes: only the GPT blocks change, + * a second run finds it, no space / no GPT / a torn add write nothing; + * 4. the store on that partition view: nothing outside the partition moves; + * 5. Allen taught, "restarted" from the bytes on disk, and asked. + * Hosted test code only (libc). Run by scripts/ck_allen_memory_test.sh. */ +#include +#include +#include +#include "allen_memory.h" +#include "allen_reply.h" +#include "disk_file.h" +#include "disk_part.h" +#include "gpt_add.h" +#include "gpt_write.h" + +static int checks, failures; +#define CHECK(c) \ + do { \ + checks++; \ + if (!(c)) { \ + failures++; \ + printf(" FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); \ + } \ + } while (0) + +static char g_path[512]; +#define MIB(bs) ((1024u * 1024u) / (bs)) + +static uint8_t *slurp(size_t *len) +{ + FILE *fp = fopen(g_path, "rb"); + if (!fp) + return NULL; + fseek(fp, 0, SEEK_END); + long n = ftell(fp); + fseek(fp, 0, SEEK_SET); + uint8_t *b = malloc((size_t)n); + if (b && fread(b, 1, (size_t)n, fp) != (size_t)n) { + free(b); + b = NULL; + } + fclose(fp); + *len = (size_t)n; + return b; +} + +/* Every block of a and b that differs lies in [lo, hi] (or in [lo2, hi2]). */ +static int diff_only_in(const uint8_t *a, const uint8_t *b, size_t len, uint32_t bs, uint64_t lo, uint64_t hi, + uint64_t lo2, uint64_t hi2) +{ + for (size_t blk = 0; blk < len / bs; blk++) + if (memcmp(a + blk * bs, b + blk * bs, bs) && !(blk >= lo && blk <= hi) && !(blk >= lo2 && blk <= hi2)) { + printf(" block %zu changed outside the allowed ranges\n", blk); + return 0; + } + return 1; +} + +static void memory_sample(ck_allen_memory *m) +{ + memset(m, 0, sizeof *m); + m->starts = 3; + m->lines = 41; + strcpy(m->name, "Drake"); + m->nfacts = 2; + strcpy(m->fact[0].key, "my favorite color"); + strcpy(m->fact[0].val, "blue"); + strcpy(m->fact[1].key, "the dogs"); + strcpy(m->fact[1].val, "rex and max"); + m->fact[1].are = 1; +} + +static void test_codec(void) +{ + static uint8_t u[CK_ALLEN_MEM_UNIT], v[CK_ALLEN_MEM_UNIT]; + ck_allen_memory a, b; + uint64_t gen = 0; + memory_sample(&a); + ck_allen_mem_encode(&a, 7, u); + CHECK(ck_allen_mem_decode(u, &b, &gen) == 0); + CHECK(gen == 7 && !memcmp(&a, &b, sizeof a)); + /* any flipped byte in the header or payload is refused */ + size_t spots[] = {0, 8, 12, 16, 25, 40, 64, 70, 72 + 5, 100, 200, 300, 4000}; + for (size_t i = 0; i < sizeof spots / sizeof spots[0]; i++) { + memcpy(v, u, sizeof u); + v[spots[i]] ^= 0x20; + CHECK(ck_allen_mem_decode(v, &b, &gen) != 0); + } + /* well sealed but bad text, count or generation: still refused */ + ck_allen_memory bad = a; + strcpy(bad.fact[0].key, "My Color"); + ck_allen_mem_encode(&bad, 1, v); + CHECK(ck_allen_mem_decode(v, &b, &gen) != 0); + bad = a; + strcpy(bad.fact[0].val, "two spaces"); + ck_allen_mem_encode(&bad, 1, v); + CHECK(ck_allen_mem_decode(v, &b, &gen) != 0); + bad = a; + strcpy(bad.name, "drake"); + ck_allen_mem_encode(&bad, 1, v); + CHECK(ck_allen_mem_decode(v, &b, &gen) != 0); + bad = a; + bad.fact[1].key[0] = 0; + ck_allen_mem_encode(&bad, 1, v); + CHECK(ck_allen_mem_decode(v, &b, &gen) != 0); + ck_allen_mem_encode(&a, 0, v); + CHECK(ck_allen_mem_decode(v, &b, &gen) != 0); + memset(v, 0, sizeof v); + CHECK(ck_allen_mem_decode(v, &b, &gen) != 0); + /* a full memory fits and round-trips */ + ck_allen_memory full; + memset(&full, 0, sizeof full); + full.nfacts = CK_ALLEN_FACTS_MAX; + for (unsigned i = 0; i < CK_ALLEN_FACTS_MAX; i++) { + memset(full.fact[i].key, 'k', CK_ALLEN_KEY_MAX - 1); + full.fact[i].key[0] = (char)('a' + i % 26); + memset(full.fact[i].val, 'v', CK_ALLEN_VAL_MAX - 1); + } + ck_allen_mem_encode(&full, 9, u); + CHECK(ck_allen_mem_decode(u, &b, &gen) == 0 && !memcmp(&full, &b, sizeof full)); +} + +/* A memory large enough that one copy spans all 8 blocks of its unit, so a + * power cut part way really tears it. */ +static void memory_big(ck_allen_memory *m) +{ + memory_sample(m); + m->nfacts = 30; + for (unsigned i = 2; i < 30; i++) { + snprintf(m->fact[i].key, sizeof m->fact[i].key, "fact number %u", i); + snprintf(m->fact[i].val, sizeof m->fact[i].val, "value %u", i * 7); + } +} + +static void test_store(void) +{ + disk_file f; + disk_dev d; + ck_allen_store st; + ck_allen_memory m, got; + CHECK(disk_file_open(&f, &d, g_path, 512, 64, 1) == 0); + CHECK(ck_allen_store_load(&st, &d, &got) == CK_ALLEN_MEM_EMPTY && st.valid == 0 && got.nfacts == 0); + memory_big(&m); + CHECK(ck_allen_store_save(&st, &m) == CK_ALLEN_MEM_OK && st.gen == 1 && st.newest == 0); + m.lines = 50; + CHECK(ck_allen_store_save(&st, &m) == CK_ALLEN_MEM_OK && st.gen == 2 && st.newest == 1); + CHECK(ck_allen_store_load(&st, &d, &got) == CK_ALLEN_MEM_OK && st.gen == 2 && st.valid == 2 && + got.lines == 50); + /* power cut after 3 of the 8 blocks of the next save */ + m.lines = 60; + strcpy(m.fact[29].val, "changed at the end of the copy"); + disk_file_arm_cut(&f, 3); + CHECK(ck_allen_store_save(&st, &m) != CK_ALLEN_MEM_OK); + disk_file_disarm(&f); + CHECK(ck_allen_store_load(&st, &d, &got) == CK_ALLEN_MEM_OK && st.gen == 2 && st.valid == 1 && + got.lines == 50); + /* power cut before the flush: the copy is whole but the flush failed; + * the save reports failure, and loading takes whichever copy is valid */ + disk_file_arm_cut(&f, 8); + CHECK(ck_allen_store_save(&st, &m) != CK_ALLEN_MEM_OK); + disk_file_disarm(&f); + CHECK(ck_allen_store_load(&st, &d, &got) == CK_ALLEN_MEM_OK && (got.lines == 50 || got.lines == 60)); + CHECK(ck_allen_store_save(&st, &m) == CK_ALLEN_MEM_OK); + uint64_t newest = st.newest, gen = st.gen; + /* spoil the newest copy on disk: the older one is used */ + disk_file_close(&f); + FILE *fp = fopen(g_path, "r+b"); + CHECK(fp && fseek(fp, (long)(newest * 4096 + 100), SEEK_SET) == 0 && fputc(0x55, fp) != EOF); + if (fp) + fclose(fp); + CHECK(disk_file_open(&f, &d, g_path, 512, 0, 0) == 0); + CHECK(ck_allen_store_load(&st, &d, &got) == CK_ALLEN_MEM_OK && st.gen == gen - 1 && st.valid == 1); + /* the next save goes over the spoiled copy, never over the good one */ + CHECK(ck_allen_store_save(&st, &m) == CK_ALLEN_MEM_OK && st.newest == newest && st.gen == gen); + CHECK(ck_allen_store_load(&st, &d, &got) == CK_ALLEN_MEM_OK && st.valid == 2 && got.lines == 60); + disk_file_close(&f); + /* too small a device is refused */ + CHECK(disk_file_open(&f, &d, g_path, 512, 15, 1) == 0); + CHECK(ck_allen_store_load(&st, &d, &got) == CK_ALLEN_MEM_EGEOM); + disk_file_close(&f); +} + +static int g_listed; +static char g_names[4][40]; +static void on_entry(void *ctx, const ck_gpt_entry *e) +{ + (void)ctx; + if (g_listed < 4) + strcpy(g_names[g_listed], e->name); + g_listed++; +} + +static void test_gpt_add(uint32_t bs) +{ + const uint64_t per = MIB(bs), disk = 64 * per; + /* one existing partition, 1..9 MiB, full of sentinel bytes; the rest free */ + gw_part sentinel[1] = {{gw_linux_type, 1 * per, 9 * per - 1u, "old macOS", 0xa5}}; + CHECK(gw_write(g_path, bs, disk, sentinel, 1, 0) == 0); + size_t n0 = 0, n1 = 0; + uint8_t *before = slurp(&n0); + disk_file f; + disk_dev d; + ck_part p; + ck_gpt_info gi; + CHECK(disk_file_open(&f, &d, g_path, bs, 0, 0) == 0); + CHECK(ck_gpt_find_aienos(&d, &p, &gi) == CK_GPT_ENOPART && gi.first_usable && gi.entries == 128); + g_listed = 0; + CHECK(ck_gpt_list(&d, on_entry, 0) == 1 && g_listed == 1 && !strcmp(g_names[0], "old macOS")); + ck_gpt_added a; + /* 16 MiB on 1 MiB boundaries: the gap before the sentinel is too small, + * so it lands right after it, at 9 MiB */ + CHECK(ck_gpt_add_aienos(&d, 16 * per, per, &a) == CK_GPT_OK); + CHECK(a.created == 1 && a.first == 9 * per && a.last == 25 * per - 1u && a.index == 1); + uint8_t *after = slurp(&n1); + CHECK(before && after && n0 == n1); + if (before && after && n0 == n1) { + /* only the GPT blocks changed: LBA 1 .. first usable - 1 and last usable + 1 .. last */ + CHECK(diff_only_in(before, after, n0, bs, 1, gi.first_usable - 1u, gi.last_usable + 1u, disk - 1u)); + CHECK(!memcmp(before, after, bs)); /* the protective MBR untouched */ + CHECK(!memcmp(before + per * bs, after + per * bs, 8 * per * bs)); /* every sentinel byte */ + } + CHECK(ck_gpt_find_aienos(&d, &p, &gi) == CK_GPT_OK && p.first_lba == 9 * per && p.blocks == 16 * per); + g_listed = 0; + CHECK(ck_gpt_list(&d, on_entry, 0) == 2 && !strcmp(g_names[1], "AIENOS Allen memory")); + /* a second run finds it and writes nothing */ + free(before); + before = slurp(&n0); + CHECK(ck_gpt_add_aienos(&d, 16 * per, per, &a) == CK_GPT_OK && a.created == 0 && a.first == 9 * per); + free(after); + after = slurp(&n1); + CHECK(before && after && n0 == n1 && !memcmp(before, after, n0)); + free(before); + free(after); + + /* 4. the store on the partition view: nothing outside it moves */ + before = slurp(&n0); + ck_allen_store st; + ck_allen_memory m, got; + memory_sample(&m); + CHECK(ck_allen_store_load(&st, &p.dev, &got) == CK_ALLEN_MEM_EMPTY); + CHECK(ck_allen_store_save(&st, &m) == CK_ALLEN_MEM_OK && ck_allen_store_save(&st, &m) == CK_ALLEN_MEM_OK); + after = slurp(&n1); + if (before && after && n0 == n1) + CHECK(diff_only_in(before, after, n0, bs, 9 * per, 9 * per + 2 * 4096 / bs - 1u, 1, 0)); + CHECK(ck_allen_store_load(&st, &p.dev, &got) == CK_ALLEN_MEM_OK && st.valid == 2 && !memcmp(&got, &m, sizeof m)); + free(before); + free(after); + disk_file_close(&f); + + /* no unused gap big enough: refused, nothing written */ + gw_part whole[1] = {{gw_linux_type, 34, disk - 34, "whole disk", 0}}; + CHECK(gw_write(g_path, bs, disk, whole, 1, 0) == 0); + before = slurp(&n0); + CHECK(disk_file_open(&f, &d, g_path, bs, 0, 0) == 0); + int rc = ck_gpt_add_aienos(&d, 16 * per, per, &a); + CHECK(rc == CK_GPT_ENOSPACE || (bs == 4096 && rc == CK_GPT_EHDR)); /* 4096: 34 is inside the array */ + disk_file_close(&f); + after = slurp(&n1); + CHECK(before && after && n0 == n1 && !memcmp(before, after, n0)); + free(before); + free(after); + + /* no GPT at all: refused, nothing written */ + CHECK(gw_write(g_path, bs, disk, sentinel, 1, GW_NO_GPT) == 0); + before = slurp(&n0); + CHECK(disk_file_open(&f, &d, g_path, bs, 0, 0) == 0); + CHECK(ck_gpt_add_aienos(&d, 16 * per, per, &a) == CK_GPT_ENOMBR); + CHECK(ck_gpt_list(&d, on_entry, 0) == CK_GPT_ENOMBR); + disk_file_close(&f); + after = slurp(&n1); + CHECK(before && after && n0 == n1 && !memcmp(before, after, n0)); + free(before); + free(after); + + /* torn add: power lost after the backup copy was written. The primary + * (what the firmware reads) is still the old, valid one; the strict + * check refuses the pair, and a second attempt writes nothing. */ + CHECK(gw_write(g_path, bs, disk, sentinel, 1, 0) == 0); + CHECK(disk_file_open(&f, &d, g_path, bs, 0, 0) == 0); + uint64_t eblocks = (128u * 128u + bs - 1u) / bs; + disk_file_arm_cut(&f, eblocks + 1u); + CHECK(ck_gpt_add_aienos(&d, 16 * per, per, &a) == CK_GPT_EWRITE); + disk_file_disarm(&f); + CHECK(ck_gpt_find_aienos(&d, &p, &gi) == CK_GPT_EBACKUP); + before = slurp(&n0); + CHECK(ck_gpt_add_aienos(&d, 16 * per, per, &a) == CK_GPT_EBACKUP); + after = slurp(&n1); + CHECK(before && after && n0 == n1 && !memcmp(before, after, n0)); + free(before); + free(after); + disk_file_close(&f); +} + +static int says(const char *got, const char *want) +{ + if (strstr(got, want)) + return 1; + printf(" answer \"%s\" lacks \"%s\"\n", got, want); + return 0; +} + +static void test_teach_restart(void) +{ + static ck_allen_mind m, m2; + static uint8_t u[CK_ALLEN_MEM_UNIT]; + ck_allen_mind_init(&m, 0); + m.lasting = 1; + CHECK(ck_allen_welcome(&m) == NULL); + CHECK(says(ck_allen_answer(&m, "My name is Drake", 1), "Nice to meet you, Drake. I'll remember that.")); + CHECK(m.changed == 1); + m.changed = 0; + CHECK(says(ck_allen_answer(&m, "Remember my favorite color is blue.", 2), + "Got it: your favorite color is blue. I'll remember that.")); + CHECK(m.changed == 1 && m.mem.nfacts == 1); + CHECK(says(ck_allen_answer(&m, "remember that the dogs are rex and max", 3), "the dogs are rex and max")); + CHECK(says(ck_allen_answer(&m, "what is my favorite color", 4), "Your favorite color is blue.")); + CHECK(says(ck_allen_answer(&m, "What are the dogs", 4), "The dogs are rex and max.")); + CHECK(says(ck_allen_answer(&m, "what is my favorite food", 4), "You haven't told me your favorite food yet.")); + CHECK(says(ck_allen_answer(&m, "remember my favorite color is green", 5), "your favorite color is green")); + CHECK(m.mem.nfacts == 2); + CHECK(says(ck_allen_answer(&m, "what do you remember", 6), + "I remember 3 things: your name is Drake; your favorite color is green; the dogs are rex and max.")); + CHECK(says(ck_allen_answer(&m, "remember", 6), "I keep it on this computer's own disk.")); + CHECK(says(ck_allen_answer(&m, "remember blue", 6), "Teach me like this")); + CHECK(says(ck_allen_answer(&m, "what is 2 plus 2", 6), "2 plus 2 is 4.")); + + /* "restart": the memory goes to disk bytes and comes back in a new mind */ + m.mem.starts = 1; + ck_allen_mem_encode(&m.mem, 5, u); + uint64_t gen = 0; + ck_allen_mind_init(&m2, 0); + m2.lasting = 1; + CHECK(ck_allen_mem_decode(u, &m2.mem, &gen) == 0 && gen == 5); + m2.mem.starts++; + CHECK(says(ck_allen_welcome(&m2), "Welcome back, Drake. I still remember 2 things you taught me.")); + CHECK(says(ck_allen_answer(&m2, "what is my favorite color", 1), "Your favorite color is green.")); + CHECK(says(ck_allen_answer(&m2, "what is my name", 1), "You're Drake.")); + CHECK(says(ck_allen_answer(&m2, "how many times have you restarted", 1), "This is start number 2 for me")); + CHECK(m2.changed == 0); + CHECK(says(ck_allen_answer(&m2, "forget the dogs", 1), "Done. I've forgotten the dogs.")); + CHECK(m2.changed == 1 && m2.mem.nfacts == 1); + CHECK(says(ck_allen_answer(&m2, "forget the cat", 1), "I don't remember anything about the cat.")); + CHECK(says(ck_allen_answer(&m2, "forget everything", 1), "forgotten everything")); + CHECK(m2.mem.nfacts == 0 && !m2.mem.name[0] && ck_allen_welcome(&m2) == NULL); + CHECK(says(ck_allen_answer(&m2, "what do you remember", 1), "Nothing yet.")); + + /* without a disk Allen says it only lasts until power off */ + ck_allen_mind_init(&m, 0); + CHECK(says(ck_allen_answer(&m, "remember my car is red", 1), "until this computer turns off")); + /* a full memory says so and keeps what it has */ + for (unsigned i = 0; i < CK_ALLEN_FACTS_MAX + 2; i++) { + char line[64]; + snprintf(line, sizeof line, "remember thing %u is %u", i, i); + ck_allen_answer(&m, line, 1); + } + CHECK(m.mem.nfacts == CK_ALLEN_FACTS_MAX); + CHECK(says(ck_allen_answer(&m, "remember one more is here", 1), "My memory is full.")); + /* everything Allen can be taught encodes and decodes */ + ck_allen_mem_encode(&m.mem, 1, u); + CHECK(ck_allen_mem_decode(u, &m2.mem, &gen) == 0); + /* too long is refused, not cut */ + ck_allen_mind_init(&m, 0); + CHECK(says(ck_allen_answer(&m, "remember the name of the very first computer i ever owned back then is x", 1), + "longer than I can hold")); + CHECK(m.mem.nfacts == 0); +} + + +/* Notes: saved as typed, handed back when asked, linked, deleted, and kept + * on disk one sealed unit each. */ +static void test_notes(void) +{ + static ck_allen_mind m, m2; + static ck_allen_notes ns, back; + static uint8_t u[CK_ALLEN_MEM_UNIT]; + ck_allen_mind_init(&m, 0); + memset(&ns, 0, sizeof ns); + m.notes = &ns; + m.lasting = 1; + CHECK(says(ck_allen_answer(&m, "save the gate code is 4471", 1), "Saved. It's your first note.")); + CHECK(m.changed == 1 && m.note_dirty == 1 && m.lit == 1 && m.mem.nnotes == 1 && ns.n == 1); + m.changed = m.note_dirty = 0; + CHECK(says(ck_allen_answer(&m, "Note: the wifi password is Blue-Fox-88", 1), + "Saved. It doesn't link to any other note yet.")); + CHECK(strcmp(ns.note[1].text, "the wifi password is Blue-Fox-88") == 0 && m.note_dirty == 2); + CHECK(says(ck_allen_answer(&m, "save the garage codes are 9012", 1), "Saved. It links to 1 other note.")); + CHECK(says(ck_allen_answer(&m, "What's the gate code?", 1), "From your notes: the gate code is 4471.")); + CHECK(m.lit == 1 && m.map_changed == 1); + CHECK(says(ck_allen_answer(&m, "what is the wifi password", 1), + "From your notes: the wifi password is Blue-Fox-88.")); + CHECK(says(ck_allen_answer(&m, "find code", 1), + "From your notes: the garage codes are 9012. I have 1 more on that.")); + CHECK(says(ck_allen_answer(&m, "find the electrician", 1), "I have nothing saved about the electrician.")); + m.changed = m.note_dirty = 0; + CHECK(says(ck_allen_answer(&m, "save the gate code is 4471.", 1), "I already have that saved.")); + CHECK(ns.n == 3 && m.changed == 0 && m.note_dirty == 0); + CHECK(says(ck_allen_answer(&m, "how many notes", 1), "You have 3 notes. The newest: the garage codes are 9012.")); + CHECK(says(ck_allen_answer(&m, "show me my notes", 1), "You have 3 notes.")); + CHECK(says(ck_allen_answer(&m, "save", 1), "Tell me what to save")); + CHECK(says(ck_allen_answer(&m, "help", 1), "keep notes")); + CHECK(says(ck_allen_answer(&m, "delete the note about the garage", 1), + "Deleted the note: the garage codes are 9012.")); + CHECK(ns.note[2].gone && m.note_dirty == 3 && ns.n == 3); + CHECK(strstr(ck_allen_answer(&m, "what's the garage code", 1), "From your notes") == NULL); + CHECK(says(ck_allen_answer(&m, "delete the note about the boat", 1), "I have no note about the boat.")); + /* taught facts still answer their own questions; machine questions too */ + CHECK(says(ck_allen_answer(&m, "remember my car is red", 1), "Got it: your car is red.")); + CHECK(says(ck_allen_answer(&m, "what is my car", 1), "Your car is red.")); + CHECK(says(ck_allen_answer(&m, "what is your name", 1), "Allen")); + CHECK(ck_allen_notes_live(&ns) == 2 && ck_allen_note_degree(&ns, 0) == 0); + + /* on disk: three notes, a reload, a damaged unit, a cut write */ + disk_file f; + disk_dev d; + uint32_t damaged = 9; + CHECK(disk_file_open(&f, &d, g_path, 512, (CK_ALLEN_DISK_UNITS + 2) * 8, 1) == 0); + for (uint32_t i = 0; i < ns.n; i++) + CHECK(ck_allen_note_write(&d, &ns, i) == CK_ALLEN_MEM_OK); + CHECK(ck_allen_notes_load(&d, 3, &back, &damaged) == CK_ALLEN_MEM_OK && damaged == 0 && back.n == 3); + CHECK(strcmp(back.note[1].text, ns.note[1].text) == 0 && back.note[2].gone == 1 && back.note[0].gone == 0); + CHECK(back.note[0].nword == ns.note[0].nword && back.note[0].word[0] == ns.note[0].word[0]); + /* a cut while writing note 3 leaves the three saved notes as they were */ + CHECK(ck_allen_note_set(&ns.note[3], "the boat is in slip 12", 1) == 0); + disk_file_arm_cut(&f, 3); + CHECK(ck_allen_note_write(&d, &ns, 3) != CK_ALLEN_MEM_OK); + disk_file_disarm(&f); + CHECK(ck_allen_notes_load(&d, 3, &back, &damaged) == CK_ALLEN_MEM_OK && damaged == 0); + /* one spoiled byte: that note loads as gone and is counted */ + disk_file_close(&f); + FILE *fp = fopen(g_path, "r+b"); + CHECK(fp && fseek(fp, (long)((CK_ALLEN_NOTES_FIRST + 1) * 4096 + 70), SEEK_SET) == 0 && fputc('X', fp) != EOF); + if (fp) + fclose(fp); + CHECK(disk_file_open(&f, &d, g_path, 512, 0, 0) == 0); + CHECK(ck_allen_notes_load(&d, 3, &back, &damaged) == CK_ALLEN_MEM_OK && damaged == 1 && back.note[1].gone); + CHECK(ck_allen_notes_load(&d, CK_ALLEN_NOTES_MAX + 1, &back, &damaged) == CK_ALLEN_MEM_EGEOM); + disk_file_close(&f); + /* a unit is valid only in its own slot, and only printable text */ + ck_allen_note_encode(&ns.note[0], 0, u); + CHECK(ck_allen_note_decode(u, 0, &back.note[0]) == 0 && ck_allen_note_decode(u, 1, &back.note[0]) != 0); + u[64] = 0x07; + CHECK(ck_allen_note_decode(u, 0, &back.note[0]) != 0); + CHECK(ck_allen_note_set(&back.note[0], "bad \x01 byte", 1) != 0 && ck_allen_note_set(&back.note[0], " ", 1) != 0); + + /* the note count travels in the memory copies; a restart says so */ + uint64_t gen = 0; + m.mem.starts = 1; + ck_allen_mem_encode(&m.mem, 7, u); + ck_allen_mind_init(&m2, 0); + CHECK(ck_allen_mem_decode(u, &m2.mem, &gen) == 0 && m2.mem.nnotes == 3); + m2.notes = &ns; + ns.n = 3; + CHECK(says(ck_allen_welcome(&m2), "Welcome back. I still remember 1 thing you taught me, and your 2 notes.")); + m2.mem.nfacts = 0; + CHECK(says(ck_allen_welcome(&m2), "Welcome back. I still have your 2 notes.")); + m.mem.nnotes = CK_ALLEN_NOTES_MAX + 1; + ck_allen_mem_encode(&m.mem, 8, u); + CHECK(ck_allen_mem_decode(u, &m2.mem, &gen) != 0); + /* a full notebook says so */ + ck_allen_mind_init(&m, 0); + memset(&ns, 0, sizeof ns); + m.notes = &ns; + ns.n = CK_ALLEN_NOTES_MAX; + CHECK(says(ck_allen_answer(&m, "save one more thing", 1), "My notebook is full.")); + /* without a disk, notes last until power off and Allen says so */ + ns.n = 0; + CHECK(says(ck_allen_answer(&m, "save the dentist is on friday", 1), "Only until this computer turns off")); +} + +int main(int argc, char **argv) +{ + snprintf(g_path, sizeof g_path, "%s/disk.img", argc > 1 ? argv[1] : "."); + test_codec(); + test_store(); + test_gpt_add(512); + test_gpt_add(4096); + test_teach_restart(); + test_notes(); + printf("allen memory: %d checks, %d failures\n", checks, failures); + return failures ? 1 : 0; +} diff --git a/native/kernel/svc/tests/stage_test.c b/native/kernel/svc/tests/stage_test.c index cc8cfb1a..6812b2e0 100644 --- a/native/kernel/svc/tests/stage_test.c +++ b/native/kernel/svc/tests/stage_test.c @@ -2046,7 +2046,23 @@ static void test_usb_hid(void) CHECK(ck_hid_usage(0x04, 0).kind == CK_KEY_CHAR && ck_hid_usage(0x04, 0).c == 'a'); CHECK(ck_hid_usage(0x1d, 1).c == 'Z'); CHECK(ck_hid_usage(0x1e, 0).c == '1' && ck_hid_usage(0x27, 0).c == '0'); - CHECK(ck_hid_usage(0x1e, 1).kind == CK_KEY_NONE); /* shifted digit: not in the keymap */ + CHECK(ck_hid_usage(0x1e, 1).c == '!' && ck_hid_usage(0x27, 1).c == ')' && ck_hid_usage(0x1f, 1).c == '@'); + CHECK(ck_hid_usage(0x38, 1).kind == CK_KEY_CHAR && ck_hid_usage(0x38, 1).c == '?'); /* the question mark */ + CHECK(ck_hid_usage(0x38, 0).c == '/' && ck_hid_usage(0x37, 0).c == '.' && ck_hid_usage(0x37, 1).c == '>'); + CHECK(ck_hid_usage(0x34, 0).c == '\'' && ck_hid_usage(0x34, 1).c == '"' && ck_hid_usage(0x31, 0).c == '\\'); + CHECK(ck_hid_usage(0x2d, 1).c == '_' && ck_hid_usage(0x33, 1).c == ':' && ck_hid_usage(0x35, 1).c == '~'); + CHECK(ck_hid_usage(0x32, 0).kind == CK_KEY_NONE && ck_hid_usage(0x2b, 0).kind == CK_KEY_NONE); /* non-US, Tab */ + { + int all = 1; /* every printable character but space comes from exactly one key */ + for (int ch = 0x21; ch <= 0x7e; ch++) { + int n = 0; + for (int u = 0x04; u <= 0x38; u++) + for (int s = 0; s < 2; s++) + n += ck_hid_usage((uint8_t)u, s).kind == CK_KEY_CHAR && ck_hid_usage((uint8_t)u, s).c == ch; + all &= n == 1; + } + CHECK(all); + } CHECK(ck_hid_usage(0x28, 0).kind == CK_KEY_ENTER && ck_hid_usage(0x2a, 0).kind == CK_KEY_BACKSPACE); CHECK(ck_hid_usage(0x29, 0).kind == CK_KEY_ESCAPE && ck_hid_usage(0x2c, 0).c == ' '); CHECK(ck_hid_usage(0x3a, 0).kind == CK_KEY_NONE); /* F1 */ diff --git a/native/kernel/tests/.crumb b/native/kernel/tests/.crumb index e84d6fd9..ba19caf8 100644 --- a/native/kernel/tests/.crumb +++ b/native/kernel/tests/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-30T22:19:45Z", + "compiled_at": "2026-10-31T02:24:33Z", "compiler": "crumb-compile/1", - "digest": "sha256:59c0ca771d489fe85c31391d5c8c2b70da110f5f13f4c15b9ba126a41ed3e5fa", + "digest": "sha256:2ca38317e04e90ee53c0a97be152b07b62e80b4b32db8bbe6b8aa3cb60aa3900", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 219, - "generated_at_commit": "2c149f764d40c9b15fc1a1c946fe1aa188d0879e", - "source_tree": "sha256:1123f9c5096d098afcd490f67bc36f4f83ba5f9ecdfd6ffbee3ffec1e56dfec5" + "generated_at_commit": "47faeddadfb49c9e84f9d1058547f7bb0ef45d1d", + "source_tree": "sha256:21c054c00262e89aaa7f870d54b54b8e196ace35cc082fff65f2b72bf31a8bc3" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/tests/test_imac_report.c b/native/kernel/tests/test_imac_report.c index add0106a..4c133fb5 100644 --- a/native/kernel/tests/test_imac_report.c +++ b/native/kernel/tests/test_imac_report.c @@ -49,19 +49,22 @@ static char log_text[56 * 61]; * layout), near-miss keys, control and non-ASCII bytes inside an allowed * key, an over-long line, and an unterminated tail. */ static const char allowed_part[] = - "AIENOS-IMAC-KERNEL-0\n" + "AIENOS-KERNEL-0\n" "aienos_commit: 0123abcd\n" "pci: ahci 00:1f.2 id=8086:2922 class=0106\n" "net_tg3: link up 1000 Mb/s full duplex\n" "summary: cores=4/4 timer=ok sata_disks=1 nvme_disks=1 gpt_valid=1 writes=none net=up\n" + "screen: Allen answered (11 characters in, 15 out)\n" + "allen_memory: saved generation 2 to copy B (1 fact) in 9 ms\n" + "ahci_part: disk=0 entry=1 type=38daac89-5ead-4b40-8b1e-3687a7418061 first_lba=2048 last_lba=2099199 mib=1024 name=\"AIENOS Allen memory\" (AIENOS)\n" "kernel: alive\n" "panic: exception: vector 14 #PF error=0x2\n" - "AIENOS-IMAC-KERNEL-0 DONE\n"; + "AIENOS-KERNEL-0 DONE\n"; static size_t build_mixed(char *out, size_t cap) { static const char *const lines[] = { - "AIENOS-IMAC-KERNEL-0\n", + "AIENOS-KERNEL-0\n", "allen: secret-chat-SENTINEL\n", "aienos_commit: 0123abcd\n", "key: SENTINEL-KEY\n", @@ -80,10 +83,16 @@ static size_t build_mixed(char *out, size_t cap) "power: \r SENTINEL-CR\n", "net_tg3: link up 1000 Mb/s full duplex\n", "summary: cores=4/4 timer=ok sata_disks=1 nvme_disks=1 gpt_valid=1 writes=none net=up\n", + "keyboard_line: Hello SENTINEL-TYPED\n", + "screen: Allen answered (11 characters in, 15 out)\n", + "allen: Your favorite color is SENTINEL-FACT.\n", + "allen_memory: saved generation 2 to copy B (1 fact) in 9 ms\n", + "allen_memoryx: SENTINEL-NEAR2\n", + "ahci_part: disk=0 entry=1 type=38daac89-5ead-4b40-8b1e-3687a7418061 first_lba=2048 last_lba=2099199 mib=1024 name=\"AIENOS Allen memory\" (AIENOS)\n", "\n", "kernel: alive\n", "panic: exception: vector 14 #PF error=0x2\n", - "AIENOS-IMAC-KERNEL-0 DONE\n", + "AIENOS-KERNEL-0 DONE\n", }; size_t w = 0; for (size_t i = 0; i < sizeof lines / sizeof lines[0]; i++) { @@ -140,7 +149,7 @@ static void filter_checks(void) edge[e++] = '\n'; CHECK(ck_x86_report_filter(edge, e, eo, sizeof eo) == keep && memcmp(eo, edge, keep) == 0); /* Only whole lines are written: a line that does not fit is dropped. */ - size_t first = strlen("AIENOS-IMAC-KERNEL-0\n"); + size_t first = strlen("AIENOS-KERNEL-0\n"); CHECK(ck_x86_report_filter(raw, rl, out, first + 5) == first && memcmp(out, raw, first) == 0); CHECK(ck_x86_report_filter(raw, rl, out, first - 1) == 14 && memcmp(out, "kernel: alive\n", 14) == 0); CHECK(ck_x86_report_filter(0, rl, out, sizeof out) == 0); @@ -207,7 +216,7 @@ int main(int argc, char **argv) if (!d) continue; char want[128]; - int h = snprintf(want, sizeof want, "AIENOS-IMAC-REPORT v=2 auth=none run=0123456789abcdef part=%u/%u bytes=%zu\n", + int h = snprintf(want, sizeof want, "AIENOS-REPORT v=2 auth=none run=0123456789abcdef part=%u/%u bytes=%zu\n", p, parts, len); CHECK(pl > (size_t)h && memcmp(d, want, (size_t)h) == 0); diff --git a/native/kernel/tools/.crumb b/native/kernel/tools/.crumb index 2f6d1352..4d7af1e5 100644 --- a/native/kernel/tools/.crumb +++ b/native/kernel/tools/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-30T21:09:29Z", + "compiled_at": "2026-10-31T02:24:33Z", "compiler": "crumb-compile/1", - "digest": "sha256:e2b20996fe1250a8288abeb0e61cd9635e6da541384c5b5ba564c5f528e2a5f8", + "digest": "sha256:1dd8ed2150cfa3709d98eed188288b25edc8d94711ea36b4b846fe66b9ab224b", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 27, - "generated_at_commit": "2fd83c0871858a3ecbfe324dda301809644d7374", - "source_tree": "sha256:7ae92ea4760bd4362167142bc1a30ad00991dc67639448e2828283014e77e30a" + "generated_at_commit": "47faeddadfb49c9e84f9d1058547f7bb0ef45d1d", + "source_tree": "sha256:e1581918ac243eeee74d1083469f016abf72ccebeb791fb45eb402264585a28b" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/tools/ck_gpt_image.c b/native/kernel/tools/ck_gpt_image.c index 4ee5617d..45504cda 100644 --- a/native/kernel/tools/ck_gpt_image.c +++ b/native/kernel/tools/ck_gpt_image.c @@ -27,6 +27,8 @@ * two-aienos same, sentinel-b also has the AIENOS type * aienos-outside sentinel-a, AIENOS [9, M+1): ends past the disk * aienos-overlap sentinel-a [1,9), AIENOS [5,M-7), sentinel-b + * one-old sentinel-a only; the rest unused (Allen memory gate) + * one-whole one empty Linux partition [1, M-1): no unused gap * no-gpt sentinel fills only: no protective MBR, no GPT * esp-model ESP_MIB MODEL_FILE ESP + model in 3 out-of-order * extents (see esp_model below; model ingest gate) @@ -211,13 +213,18 @@ static int cmd_create(int argc, char **argv) n = 2; } else if (!strcmp(lay, "aienos-overlap")) { p[1].first = 5 * per; + } else if (!strcmp(lay, "one-old")) { + n = 1; /* sentinel-a only: the rest of the disk unused */ + } else if (!strcmp(lay, "one-whole")) { + p[0] = (gw_part){gw_linux_type, 1 * per, (mib - 1u) * per - 1u, "whole", 0}; + n = 1; } else if (!strcmp(lay, "no-gpt")) { flags |= GW_NO_GPT; } else { return usage(); } if (gw_write(argv[2], bs, blocks, p, n, flags)) return 1; - int has = strcmp(lay, "no-aienos") != 0; + int has = strcmp(lay, "no-aienos") && strcmp(lay, "one-old") && strcmp(lay, "one-whole"); printf("gpt_image bs=%u blocks=%llu aienos_first_lba=%llu aienos_last_lba=%llu\n", bs, (unsigned long long)blocks, has ? (unsigned long long)p[1].first : 0ull, has ? (unsigned long long)p[1].last : 0ull); diff --git a/native/kernel/tools/ck_imac_report_listen.c b/native/kernel/tools/ck_imac_report_listen.c index a16847a6..15049391 100644 --- a/native/kernel/tools/ck_imac_report_listen.c +++ b/native/kernel/tools/ck_imac_report_listen.c @@ -27,7 +27,7 @@ * ck_imac_report_listen PORT OUTDIR SECONDS * * Binds 0.0.0.0:PORT and collects datagrams of the form - * "AIENOS-IMAC-REPORT v=2 auth=none run=<16 hex> part=/ bytes=\n" + chunk + * "AIENOS-REPORT v=2 auth=none run=<16 hex> part=/ bytes=\n" + chunk * (the kernel broadcasts them from 0.0.0.0 to 255.255.255.255). Part i of n * carries bytes [i * CHUNK, ...) of a report of bytes. When every part * of a run is in, the report is written once to @@ -35,7 +35,8 @@ * "complete run=... auth=none bytes=... file=..." goes to OUTDIR/listen.log. * Spark reports use "AIENUX-SPARK-REPORT v=1 " (also unauthenticated). * Repeats of a finished run are counted, not rewritten. Anything else, - * including the retired iMac v=1 raw-console format, is logged as ignored. + * including every older header (the retired v=1 raw-console format and the + * older AIENOS-IMAC-REPORT name), is logged as ignored. * Exit 0 at the deadline, 2 usage, 3 socket/bind error. */ #define _POSIX_C_SOURCE 200809L #include @@ -50,8 +51,8 @@ #include #include -#define MAGIC "AIENOS-IMAC-REPORT v=2 auth=none " -#define LEGACY "AIENOS-IMAC-REPORT v=1 " +#define MAGIC "AIENOS-REPORT v=2 auth=none " +#define LEGACY "AIENOS-IMAC-REPORT " /* every older header, refused */ #define SPARK_MAGIC "AIENUX-SPARK-REPORT v=1 " #define UNAUTH_NOTE \ "note: iMac reports are UNAUTHENTICATED UDP broadcasts (auth=none); anyone on the LAN can read or " \ @@ -174,7 +175,7 @@ int main(int argc, char **argv) unsigned part, parts, total; int used = 0; if ((size_t)n >= sizeof LEGACY - 1 && memcmp(in, LEGACY, sizeof LEGACY - 1) == 0) { - fprintf(lg, "ignored from %s:%u len=%zd: retired v=1 raw-console report\n", fa, ntohs(from.sin_port), n); + fprintf(lg, "ignored from %s:%u len=%zd: retired older report header\n", fa, ntohs(from.sin_port), n); continue; } size_t ml = 0; diff --git a/native/kernel/ui/allen_font.c b/native/kernel/ui/allen_font.c new file mode 100644 index 00000000..78eab61e --- /dev/null +++ b/native/kernel/ui/allen_font.c @@ -0,0 +1,325 @@ +/* allen_font.c -- Allen's stroke typeface; see allen_font.h. */ +#include "allen_font.h" + +/* Each glyph: "wN" (advance in design units), then pen commands: + * Mx,y move the pen + * Lx,y line from the pen to x,y + * Acx,cy,rx,ry,a0,a1 elliptical arc from angle a0 to a1 (degrees; 0 is + * right, 90 is down), starting fresh; the pen ends at a1 + * Dx,y a dot + * Every stroke has round caps and joins (distance to the centre line). */ +static const char *const glyphs[CK_AF_COUNT] = { + /* */ "w6", + /* ! */ "w6 M3,0 L3,14 D3,20", + /* " */ "w10 M3,0 L3,5 M7,0 L7,5", + /* # */ "w15 M6,2 L4,20 M11,2 L9,20 M2,8 L13,8 M1,14 L12,14", + /* $ */ "w15 A8,5,5,5,-30,-270 A8,15,5,5,270,510 M8,-2 L8,22", + /* % */ "w16 A4,4,2,3,0,360 A12,16,2,3,0,360 M13,1 L3,19", + /* & */ "w16 M14,20 L5,9 A7,5,3,4,150,400 L3,14 A7,15,4,5,180,60 L13,11", + /* ' */ "w6 M3,0 L3,5", + /* ( */ "w9 A10,10,6,12,240,120", + /* ) */ "w9 A-1,10,6,12,-60,60", + /* * */ "w14 M7,2 L7,10 M3,4 L11,8 M11,4 L3,8", + /* + */ "w14 M2,12 L12,12 M7,7 L7,17", + /* , */ "w6 M3,19 L2,23", + /* - */ "w11 M2,13 L9,13", + /* . */ "w6 D3,20", + /* / */ "w12 M10,0 L2,20", + /* 0 */ "w14 A7,10,5,10,0,360", + /* 1 */ "w14 M3,4 L8,0 L8,20", + /* 2 */ "w14 A7,6,5,6,200,400 L2,20 L12,20", + /* 3 */ "w14 A7,5,5,5,200,450 A7,15,5,5,270,520", + /* 4 */ "w14 M10,20 L10,0 L1,14 L13,14", + /* 5 */ "w14 M12,0 L4,0 L4,9 A7,14,5,6,235,520", + /* 6 */ "w14 A7,14,5,6,0,360 M10,0 L3,11", + /* 7 */ "w14 M2,0 L12,0 L5,20", + /* 8 */ "w14 A7,5,4,5,0,360 A7,15,5,5,0,360", + /* 9 */ "w14 A7,6,5,6,0,360 M4,20 L11,9", + /* : */ "w6 D3,8 D3,20", + /* ; */ "w6 D3,8 M3,19 L2,23", + /* < */ "w14 M12,6 L2,12 L12,18", + /* = */ "w14 M2,10 L12,10 M2,15 L12,15", + /* > */ "w14 M2,6 L12,12 L2,18", + /* ? */ "w14 A7,5,5,5,190,450 L7,14 D7,20", + /* @ */ "w19 A9,12,3,4,0,360 M12,8 L12,14 A14,14,2,2,180,0 A9,11,7,9,0,-300", + /* A */ "w16 M2,20 L8,0 L14,20 M4,13 L12,13", + /* B */ "w15 M2,0 L2,20 M2,0 L8,0 A8,5,4,5,270,450 L2,10 M2,10 L9,10 A9,15,4,5,270,450 L2,20", + /* C */ "w17 A9,10,7,10,45,315", + /* D */ "w16 M2,0 L2,20 M2,0 L6,0 A6,10,8,10,270,450 L2,20", + /* E */ "w14 M12,0 L2,0 L2,20 L12,20 M2,10 L10,10", + /* F */ "w13 M12,0 L2,0 L2,20 M2,10 L10,10", + /* G */ "w18 A9,10,7,10,-45,-360 M11,10 L16,10", + /* H */ "w16 M2,0 L2,20 M14,0 L14,20 M2,10 L14,10", + /* I */ "w6 M3,0 L3,20", + /* J */ "w13 M10,0 L10,14 A6,14,4,6,0,180", + /* K */ "w15 M2,0 L2,20 M13,0 L2,12 M6,8 L14,20", + /* L */ "w13 M2,0 L2,20 L12,20", + /* M */ "w20 M2,20 L2,0 L10,14 L18,0 L18,20", + /* N */ "w16 M2,20 L2,0 L14,20 L14,0", + /* O */ "w20 A10,10,8,10,0,360", + /* P */ "w15 M2,20 L2,0 L8,0 A8,5,5,5,270,450 L2,10", + /* Q */ "w20 A10,10,8,10,0,360 M12,14 L18,21", + /* R */ "w15 M2,20 L2,0 L8,0 A8,5,5,5,270,450 L2,10 M8,10 L14,20", + /* S */ "w16 A8,5,5,5,-30,-270 A8,15,5,5,270,510", + /* T */ "w16 M1,0 L15,0 M8,0 L8,20", + /* U */ "w16 M2,0 L2,13 A8,13,6,7,180,0 L14,0", + /* V */ "w16 M1,0 L8,20 L15,0", + /* W */ "w22 M1,0 L6,20 L11,0 L16,20 L21,0", + /* X */ "w16 M2,0 L14,20 M14,0 L2,20", + /* Y */ "w16 M1,0 L8,10 L15,0 M8,10 L8,20", + /* Z */ "w16 M2,0 L14,0 L2,20 L14,20", + /* [ */ "w9 M7,-1 L3,-1 L3,21 L7,21", + /* \ */ "w12 M2,0 L10,20", + /* ] */ "w9 M2,-1 L6,-1 L6,21 L2,21", + /* ^ */ "w12 M2,8 L6,1 L10,8", + /* _ */ "w14 M1,23 L13,23", + /* ` */ "w7 M2,0 L4,4", + /* a */ "w15 A7,14,5,6,0,360 M12,8 L12,20", + /* b */ "w15 M2,0 L2,20 A7,14,5,6,0,360", + /* c */ "w13 A7,14,5,6,40,320", + /* d */ "w15 A7,14,5,6,0,360 M12,0 L12,20", + /* e */ "w14 M2,14 L12,14 A7,14,5,6,0,-320", + /* f */ "w11 M5,20 L5,4 A9,4,4,4,180,300 M2,8 L10,8", + /* g */ "w15 A7,14,5,6,0,360 M12,8 L12,22 A7,22,5,5,0,150", + /* h */ "w15 M2,0 L2,20 A7,13,5,5,180,360 L12,20", + /* i */ "w6 M3,8 L3,20 D3,3", + /* j */ "w7 M4,8 L4,22 A0,22,4,5,0,120 D4,3", + /* k */ "w13 M2,0 L2,20 M11,8 L2,15 M5,13 L12,20", + /* l */ "w6 M3,0 L3,20", + /* m */ "w21 M2,8 L2,20 A6,12,4,4,180,360 L10,20 A14,12,4,4,180,360 L18,20", + /* n */ "w15 M2,8 L2,20 A7,13,5,5,180,360 L12,20", + /* o */ "w14 A7,14,5,6,0,360", + /* p */ "w15 M2,8 L2,27 A7,14,5,6,0,360", + /* q */ "w15 A7,14,5,6,0,360 M12,8 L12,27", + /* r */ "w10 M2,8 L2,20 A7,13,5,5,180,290", + /* s */ "w14 A7,11,4,3,-30,-270 A7,17,4,3,270,510", + /* t */ "w11 M5,2 L5,17 A8,17,3,3,180,40 M2,8 L10,8", + /* u */ "w15 M2,8 L2,15 A7,15,5,5,180,0 M12,8 L12,20", + /* v */ "w14 M2,8 L7,20 L12,8", + /* w */ "w20 M2,8 L6,20 L10,8 L14,20 L18,8", + /* x */ "w14 M2,8 L12,20 M12,8 L2,20", + /* y */ "w14 M2,8 L7,20 M12,8 L4,27", + /* z */ "w14 M2,8 L12,8 L2,20 L12,20", + /* { */ "w10 M8,-1 L6,0 L6,8 L4,10 L6,12 L6,20 L8,21", + /* | */ "w6 M3,-1 L3,23", + /* } */ "w10 M2,-1 L4,0 L4,8 L6,10 L4,12 L4,20 L2,21", + /* ~ */ "w14 M2,13 L5,11 L9,14 L12,12", +}; + +static const uint16_t sin_q[91] = { + 0, 286, 572, 857, 1143, 1428, 1713, 1997, 2280, 2563, 2845, 3126, 3406, 3686, 3964, + 4240, 4516, 4790, 5063, 5334, 5604, 5872, 6138, 6402, 6664, 6924, 7182, 7438, 7692, 7943, + 8192, 8438, 8682, 8923, 9162, 9397, 9630, 9860, 10087, 10311, 10531, 10749, 10963, 11174, 11381, + 11585, 11786, 11982, 12176, 12365, 12551, 12733, 12911, 13085, 13255, 13421, 13583, 13741, 13894, 14044, + 14189, 14330, 14466, 14598, 14726, 14849, 14968, 15082, 15191, 15296, 15396, 15491, 15582, 15668, 15749, + 15826, 15897, 15964, 16026, 16083, 16135, 16182, 16225, 16262, 16294, 16322, 16344, 16362, 16374, 16382, + 16384, +}; + +int32_t ck_af_sin(int32_t deg) +{ + deg %= 360; + if (deg < 0) + deg += 360; + if (deg <= 90) + return sin_q[deg]; + if (deg <= 180) + return sin_q[180 - deg]; + if (deg <= 270) + return -(int32_t)sin_q[deg - 180]; + return -(int32_t)sin_q[360 - deg]; +} + +int32_t ck_af_cos(int32_t deg) { return ck_af_sin(deg + 90); } + +uint64_t ck_af_isqrt(uint64_t v) +{ + uint64_t r = 0, bit = (uint64_t)1 << 62; + while (bit > v) + bit >>= 2; + while (bit) { + if (v >= r + bit) { + v -= r + bit; + r = (r >> 1) + bit; + } else { + r >>= 1; + } + bit >>= 2; + } + return r; +} + +static int idx(char c) +{ + unsigned char u = (unsigned char)c; + return u >= CK_AF_FIRST && u <= CK_AF_LAST ? u - CK_AF_FIRST : '?' - CK_AF_FIRST; +} + +void ck_af_face_init(ck_af_face *f, unsigned cap_px, unsigned weight, uint8_t *pool, size_t pool_len) +{ + f->s256 = cap_px * 256u / 20u; + f->hw256 = (uint32_t)((uint64_t)weight * f->s256 / 1000u); + f->pool = pool; + f->pool_len = pool_len; + f->pool_used = 0; + for (unsigned i = 0; i < CK_AF_COUNT; i++) + f->g[i] = (ck_af_glyph){0}; +} + +/* Reads a signed integer at *p; advances past it and one ',' if present. */ +static int num(const char **p) +{ + int neg = 0, v = 0; + if (**p == '-') { + neg = 1; + (*p)++; + } + while (**p >= '0' && **p <= '9') + v = v * 10 + (*(*p)++ - '0'); + if (**p == ',') + (*p)++; + return neg ? -v : v; +} + +uint32_t ck_af_advance(const ck_af_face *f, char c) +{ + const char *p = glyphs[idx(c)] + 1; /* past 'w' */ + return (uint32_t)num(&p) * f->s256; +} + +uint32_t ck_af_measure(const ck_af_face *f, const char *s, size_t n) +{ + uint64_t w = 0; + for (size_t i = 0; i < n && s[i]; i++) + w += ck_af_advance(f, s[i]); + return (uint32_t)((w + 255) / 256); +} + +#define SEG_MAX 160 +struct seg { + int32_t x0, y0, x1, y1; /* 1/256 px, relative to the pen; y up from the baseline is negative */ +}; + +/* Turns one glyph's commands into segments. Returns the count. */ +static unsigned segments(const ck_af_face *f, const char *p, struct seg *out) +{ + int32_t s = (int32_t)f->s256; + unsigned n = 0; + int32_t px = 0, py = 0; +#define PT_X(u) ((int32_t)(u) * s) +#define PT_Y(u) (((int32_t)(u) - 20) * s) + while (*p) { + char cmd = *p++; + if (cmd == ' ') + continue; + if (cmd == 'w') { + (void)num(&p); + } else if (cmd == 'M') { + int x = num(&p), y = num(&p); + px = PT_X(x); + py = PT_Y(y); + } else if (cmd == 'L' || cmd == 'D') { + int x = num(&p), y = num(&p); + int32_t nx = PT_X(x), ny = PT_Y(y); + if (cmd == 'D') + px = nx, py = ny; + if (n < SEG_MAX) + out[n++] = (struct seg){px, py, nx, ny}; + px = nx; + py = ny; + } else if (cmd == 'A') { + int cx = num(&p), cy = num(&p), rx = num(&p), ry = num(&p), a0 = num(&p), a1 = num(&p); + int span = a1 > a0 ? a1 - a0 : a0 - a1; + int steps = span / 9 < 2 ? 2 : span / 9; + int32_t lx = 0, ly = 0; + for (int k = 0; k <= steps; k++) { + int32_t a = a0 + (a1 - a0) * k / steps; + int32_t x = PT_X(cx) + (int32_t)((int64_t)rx * s * ck_af_cos(a) / 16384); + int32_t y = PT_Y(cy) + (int32_t)((int64_t)ry * s * ck_af_sin(a) / 16384); + if (k && n < SEG_MAX) + out[n++] = (struct seg){lx, ly, x, y}; + lx = x; + ly = y; + } + px = lx; + py = ly; + } + } +#undef PT_X +#undef PT_Y + return n; +} + +static int32_t floor_px(int32_t v) { return v >= 0 ? v / 256 : -((-v + 255) / 256); } + +const ck_af_glyph *ck_af_glyph_get(ck_af_face *f, char c) +{ + ck_af_glyph *g = &f->g[idx(c)]; + if (g->alpha || (g->w == 0 && g->h == 1)) /* h == 1, w == 0: an empty glyph already done */ + return g; + struct seg sg[SEG_MAX]; + unsigned n = segments(f, glyphs[idx(c)], sg); + if (n == 0) { + g->w = 0; + g->h = 1; + return g; + } + int32_t minx = sg[0].x0, maxx = minx, miny = sg[0].y0, maxy = miny; + for (unsigned i = 0; i < n; i++) { + int32_t xs[2] = {sg[i].x0, sg[i].x1}, ys[2] = {sg[i].y0, sg[i].y1}; + for (int k = 0; k < 2; k++) { + if (xs[k] < minx) minx = xs[k]; + if (xs[k] > maxx) maxx = xs[k]; + if (ys[k] < miny) miny = ys[k]; + if (ys[k] > maxy) maxy = ys[k]; + } + } + int32_t pad = (int32_t)f->hw256 + 256; + int32_t x0 = floor_px(minx - pad), y0 = floor_px(miny - pad); + int32_t x1 = floor_px(maxx + pad) + 1, y1 = floor_px(maxy + pad) + 1; + size_t w = (size_t)(x1 - x0), h = (size_t)(y1 - y0); + if (f->pool_len - f->pool_used < w * h) + return 0; + uint8_t *a = f->pool + f->pool_used; + int64_t hw = f->hw256; + for (size_t yy = 0; yy < h; yy++) { + int64_t py = (int64_t)(y0 + (int32_t)yy) * 256 + 128; + for (size_t xx = 0; xx < w; xx++) { + int64_t pxc = (int64_t)(x0 + (int32_t)xx) * 256 + 128; + int64_t best = INT64_MAX; + for (unsigned i = 0; i < n; i++) { + int64_t ax = sg[i].x0, ay = sg[i].y0, dx = sg[i].x1 - ax, dy = sg[i].y1 - ay; + int64_t qx = pxc - ax, qy = py - ay, len2 = dx * dx + dy * dy, ex, ey; + if (len2 == 0) { + ex = qx; + ey = qy; + } else { + int64_t t = qx * dx + qy * dy; /* projection, scaled by len2 */ + if (t <= 0) { + ex = qx; + ey = qy; + } else if (t >= len2) { + ex = qx - dx; + ey = qy - dy; + } else { + ex = qx - dx * t / len2; + ey = qy - dy * t / len2; + } + } + int64_t d2 = ex * ex + ey * ey; + if (d2 < best) + best = d2; + } + int64_t d = (int64_t)ck_af_isqrt((uint64_t)best); + int64_t cov = hw + 128 - d; /* 1/256 px of the pixel inside the stroke */ + a[yy * w + xx] = cov <= 0 ? 0 : cov >= 256 ? 255 : (uint8_t)(cov * 255 / 256); + } + } + f->pool_used += w * h; + g->w = (uint16_t)w; + g->h = (uint16_t)h; + g->ox = (int16_t)x0; + g->oy = (int16_t)y0; + g->alpha = a; + return g; +} diff --git a/native/kernel/ui/allen_font.h b/native/kernel/ui/allen_font.h new file mode 100644 index 00000000..13c3c0a2 --- /dev/null +++ b/native/kernel/ui/allen_font.h @@ -0,0 +1,48 @@ +/* allen_font.h -- Allen's typeface: every printable ASCII character drawn as + * round-capped pen strokes (lines and elliptical arcs) on a design grid, and + * rasterized on demand into anti-aliased alpha masks at any size. Integer math + * only (the kernel builds -mgeneral-regs-only); no font files, no outside + * data. Pure: no MMIO, host tested in ui/tests/allen_ui_test.c. + * + * Design grid: cap height and ascenders at y=0, lowercase x-height at y=8, + * baseline at y=20, descenders to y=27; x grows right, y grows down. */ +#ifndef AIENOS_ALLEN_FONT_H +#define AIENOS_ALLEN_FONT_H +#include +#include + +#define CK_AF_FIRST 32 +#define CK_AF_LAST 126 +#define CK_AF_COUNT (CK_AF_LAST - CK_AF_FIRST + 1) + +typedef struct { + uint8_t *alpha; /* w*h coverage, 0..255; NULL when not rasterized yet */ + uint16_t w, h; + int16_t ox, oy; /* mask top-left relative to the pen on the baseline, px */ +} ck_af_glyph; + +typedef struct { + uint32_t s256; /* 1/256 px per design unit */ + uint32_t hw256; /* half the stroke width, 1/256 px */ + uint8_t *pool; /* mask storage, filled as glyphs are first used */ + size_t pool_len, pool_used; + ck_af_glyph g[CK_AF_COUNT]; +} ck_af_face; + +/* cap_px: cap height in pixels; weight: half the stroke width in + * thousandths of a design unit (1250 = regular). pool holds the masks. */ +void ck_af_face_init(ck_af_face *f, unsigned cap_px, unsigned weight, uint8_t *pool, size_t pool_len); +/* The mask for c (anything outside 32..126 draws as '?'); NULL only when the + * pool is full. Rasterized on first use. */ +const ck_af_glyph *ck_af_glyph_get(ck_af_face *f, char c); +/* Advance after c, 1/256 px. */ +uint32_t ck_af_advance(const ck_af_face *f, char c); +/* Width of the first n characters of s, whole px (rounded up). */ +uint32_t ck_af_measure(const ck_af_face *f, const char *s, size_t n); +/* Integer square root (floor). */ +uint64_t ck_af_isqrt(uint64_t v); +/* sin and cos of whole degrees (any sign), scaled by 16384. */ +int32_t ck_af_sin(int32_t deg); +int32_t ck_af_cos(int32_t deg); + +#endif diff --git a/native/kernel/ui/allen_ui.c b/native/kernel/ui/allen_ui.c new file mode 100644 index 00000000..ca105132 --- /dev/null +++ b/native/kernel/ui/allen_ui.c @@ -0,0 +1,944 @@ +/* allen_ui.c -- Allen's home; see allen_ui.h. + * + * Layers: the night (ui/night.c) keeps the sky in its own full-screen + * buffer; `back` is where a frame is put together: for each changed part of + * the screen the sky as it looks now, then the lights in it, Allen, his + * words, the bar, all added in order and clipped to that part, which is + * then copied to the screen. Colours are 0x00RRGGBB in RAM; the copy swaps + * red and blue for an RGBX framebuffer. + * + * Which parts change is kept on a grid of tiles (64 x 32 px): each frame + * marks the tiles under anything that moved, and each row of marked tiles + * becomes a strip. Strips never overlap, so they can be drawn by any core in + * any order: a frame publishes its strips in one word (count and next index) + * that cores claim one at a time. + * + * Calls from the keyboard side (input, said, map, wake) only leave a note + * under a short lock; the next frame picks it up. The layout is designed on + * a 1920 x 1080 grid and scaled to the screen (k, 1/256). */ +#include "allen_ui.h" +#include "allen_font.h" +#include "mind.h" +#include "night.h" +#include "paint.h" + +#define TEXT_MAX 160 +#define LINES_MAX 5 +#define TW 64 +#define TH 32 +#define TILES_MAX 16384u +#define JOBS_MAX 1200u +#define FRAME_MS 16u + +#define BORN_MS (CK_NIGHT_MERGE_MS + 300u) /* Allen starts to gather */ +#define FORMED_MS (BORN_MS + CK_MIND_FORM_MS) +#define LETTER_MS 35u +#define BAR_REST_MS 9000u /* the bar fades this long after the last thing happened */ +#define MAP_SHOW_MS 9000u + +struct words { + char text[TEXT_MAX]; + unsigned len, lines, st[LINES_MAX], ln[LINES_MAX]; + int32_t x[LINES_MAX]; /* where each line starts, px */ + uint32_t from; /* the first letter's start, ms */ + uint32_t done; /* the last letter settled */ + uint32_t fade; /* fading from here (0: not yet) */ + ck_rect box; +}; + +/* what the keyboard side has left for the next frame */ +static struct { + volatile char lock; + volatile int refresh; + unsigned input_gen, said_gen, map_gen, wake_gen; + char input[TEXT_MAX]; + unsigned input_len; + char line[TEXT_MAX], reply[TEXT_MAX]; + int has_line; + const char *footer; + unsigned n, ne, total, links; + int lit; + uint8_t ea[CK_ALLEN_UI_MAP_LINKS], eb[CK_ALLEN_UI_MAP_LINKS]; + char label[TEXT_MAX]; +} note; + +static struct { + int started, on; + volatile uint32_t *fb; + int32_t w, h; + uint32_t pitch, format, k; + uint32_t *back; + ck_canvas cv; + ck_night night; + ck_mind mind; + ck_af_face voice, body, small; + uint64_t hz, t0; + uint64_t (*clock)(void); + uint32_t t, last; /* this frame's time and the last frame's, ms */ + int32_t cx, cy; + /* the bar */ + const char *footer; + ck_rect bar, bar_box; + uint32_t bar_a, bar_was, wake_t, quiet_t; /* bar_a: 0..256; quiet_t: when things last happened */ + char input[TEXT_MAX]; + unsigned input_len; + uint32_t key_t; + unsigned seen_input, seen_said, seen_map, seen_wake; + int input_moved; + /* the conversation */ + struct words now, next; /* now: on screen; next: what Allen will say */ + uint32_t speak_t; /* when next starts (0: nothing waiting) */ + char guest[TEXT_MAX]; + unsigned guest_len; + int32_t guest_x; + uint32_t guest_t; /* when the guest's line began to rise (0: none) */ + uint32_t shimmer, shimmer_was, level, word_t; /* level: the voice, 0..256 */ + ck_rect guest_box, words_was; + /* the notes constellation */ + unsigned n, ne, total, links; + int lit; + uint8_t ea[CK_ALLEN_UI_MAP_LINKS], eb[CK_ALLEN_UI_MAP_LINKS]; + char label[TEXT_MAX]; + unsigned label_len; + int32_t mx, my, mr; + uint32_t map_t, map_a, map_was; /* map_t: when it was last shown (0: never) */ + ck_rect map_box; + /* the frame */ + uint8_t tiles[TILES_MAX]; + int32_t tx, ty; + ck_rect jobs[JOBS_MAX]; + volatile uint64_t ticket; /* count << 16 | next; claimed with compare-and-swap */ + volatile uint32_t done; + unsigned twinkle_turn; + ck_rect flash_was, lens_was; + int32_t ripple_was; + uint32_t frames, slowest, total_ticks; +} ui; + +#define S(v) ((int32_t)(((int64_t)(v) * (int64_t)ui.k + 128) / 256)) + +static void relax(void) +{ +#if defined(__x86_64__) + __builtin_ia32_pause(); +#elif defined(__aarch64__) + __asm__ volatile("yield"); +#endif +} + +static void lock(void) +{ + while (__atomic_test_and_set(¬e.lock, __ATOMIC_ACQUIRE)) + relax(); +} +static void unlock(void) { __atomic_clear(¬e.lock, __ATOMIC_RELEASE); } + +static uint32_t ms(uint64_t now) { return (uint32_t)((now - ui.t0) * 1000u / ui.hz); } + +static unsigned copy(char *d, const char *s, unsigned max) +{ + unsigned n = 0; + while (s && n < max - 1 && s[n]) + d[n] = s[n], n++; + d[n] = 0; + return n; +} + +/* ---- text ---- */ + +/* Word-wraps s (n letters) to width px with face f: line starts and lengths. */ +static unsigned wrap(ck_af_face *f, const char *s, unsigned n, int32_t width, unsigned *st, unsigned *ln) +{ + unsigned lines = 0, i = 0; + while (i < n && lines < LINES_MAX) { + while (i < n && s[i] == ' ') + i++; + unsigned start = i, last_space = 0, j = i; + int32_t w = 0; + while (j < n) { + int32_t aw = (int32_t)((ck_af_advance(f, s[j]) + 255) / 256); + if (w + aw > width && j > start) + break; + if (s[j] == ' ') + last_space = j; + w += aw; + j++; + } + if (j < n && last_space > start) + j = last_space; + st[lines] = start; + ln[lines] = j - start; + lines++; + i = j; + } + return lines; +} + +static int32_t text(ck_canvas *cv, const ck_rect *cl, ck_af_face *f, int32_t x, int32_t y, const char *s, unsigned n, + uint32_t color, uint32_t a) +{ + uint64_t pen = (uint64_t)x * 256; + for (unsigned i = 0; i < n; i++) + pen = ck_letter(cv, cl, f, pen, y, s[i], color, a, 0); + return (int32_t)((pen + 255) / 256); +} + +static int32_t line_h(void) { return S(40); } +static int32_t words_top(void) { return ui.cy + S(250); } + +static void lay_out(struct words *w) +{ + w->lines = wrap(&ui.voice, w->text, w->len, S(900), w->st, w->ln); + int32_t top = words_top(), x0 = ui.w, x1 = 0; + for (unsigned i = 0; i < w->lines; i++) { + int32_t lw = (int32_t)ck_af_measure(&ui.voice, w->text + w->st[i], w->ln[i]); + w->x[i] = (ui.w - lw) / 2; + x0 = ck_min(x0, w->x[i]), x1 = ck_max(x1, w->x[i] + lw); + } + w->box = w->lines ? (ck_rect){x0 - S(8), top - S(34), x1 - x0 + S(16), (int32_t)w->lines * line_h() + S(30)} + : (ck_rect){0, 0, 0, 0}; + unsigned last = w->lines ? w->st[w->lines - 1] + w->ln[w->lines - 1] : 0; + w->done = w->from + last * LETTER_MS + 700; +} + +/* how long words stay once said: time to read them */ +static uint32_t read_ms(const struct words *w) { return 6000u + w->len * 70u; } + +static uint32_t words_alpha(const struct words *w, uint32_t t) +{ + if (!w->len) + return 0; + uint32_t out = w->fade ? w->fade : w->done + read_ms(w); + return 256 - ck_smooth(ck_prog(t, out, out + 450)); +} + +static void draw_words(const struct words *w, const ck_rect *r, uint32_t t) +{ + uint32_t all = words_alpha(w, t); + if (!all || !ck_meets(w->box, r)) + return; + int32_t top = words_top(); + for (unsigned li = 0; li < w->lines; li++) { + uint64_t pen = (uint64_t)w->x[li] * 256; + int32_t y = top + (int32_t)li * line_h(); + for (unsigned j = 0; j < w->ln[li]; j++) { + unsigned i = w->st[li] + j; + uint32_t at = w->from + i * LETTER_MS; + if (t <= at) /* not yet: but keep the pen moving so the line stays centred */ + break; + uint32_t age = t - at, a = ck_smooth(ck_prog(age, 0, 260)); + uint32_t c = ck_mix(CK_RGB(255, 212, 150), CK_RGB(234, 238, 252), ck_smooth(ck_prog(age, 0, 900))); + int32_t rise = (int32_t)((int64_t)S(6) * (256 - ck_ease_out(ck_prog(age, 0, 360))) >> 8); + pen = ck_letter(&ui.cv, r, &ui.voice, pen, y + rise, w->text[i], c, a * all >> 8, 0); + } + } +} + +/* ---- the bar ---- */ + +static void draw_bar(const ck_rect *r, uint32_t t) +{ + uint32_t A = ui.bar_a; + if (!A || !ck_meets(ui.bar_box, r)) + return; + ck_rect b = ui.bar, d = ck_grow(b, S(14)); + if (!ck_clip(&d, r)) + d.w = 0; + int32_t rad = b.h / 2, typing = ui.input_len > 0; + for (int32_t y = d.y; d.w && y < d.y + d.h; y++) { + uint32_t *row = ui.back + (size_t)y * (size_t)ui.w; + for (int32_t x = d.x; x < d.x + d.w; x++) { + int32_t sd = ck_sd_rrect(x, y, &b, rad); + uint32_t in = ck_cover(sd); + if (in) + row[x] = ck_mix(row[x], CK_RGB(6, 8, 18), (in * 150 >> 8) * A >> 8); + int32_t edge = ck_abs(sd + 8); + if (edge < 16) + row[x] = ck_add(row[x], CK_RGB(255, 255, 255), (uint32_t)(16 - edge) * (typing ? 4u : 3u) * A >> 8); + if (typing && sd > 0 && sd < S(14) * 16) { /* a soft blue glow round it while typing */ + uint32_t g = 256 - (uint32_t)(sd * 256 / (S(14) * 16)); + row[x] = ck_add(row[x], CK_RGB(110, 130, 255), ((g * g >> 8) * 34 >> 8) * A >> 8); + } + } + } + int32_t pad = S(30), base = b.y + b.h / 2 + S(7); + ck_rect tc = {b.x + pad, b.y, b.w - 2 * pad, b.h}; + if (!ck_clip(&tc, r)) + tc.w = 0; + int32_t x = b.x + pad; + if (!ui.input_len) { + if (tc.w) + text(&ui.cv, &tc, &ui.body, x, base, "Speak to Allen", 14, CK_RGB(150, 160, 196), 150 * A >> 8); + } else { + int32_t avail = b.w - 2 * pad - S(12); + unsigned from = 0; + while (from < ui.input_len && + (int32_t)ck_af_measure(&ui.body, ui.input + from, ui.input_len - from) > avail) + from++; + if (tc.w) + x = text(&ui.cv, &tc, &ui.body, x, base, ui.input + from, ui.input_len - from, CK_RGB(236, 240, 252), + A); + else + x += (int32_t)ck_af_measure(&ui.body, ui.input + from, ui.input_len - from); + } + /* the caret breathes rather than blinks */ + uint32_t ca = (uint32_t)(16384 + ck_sin((t - ui.key_t) * 65536u / 1100u + 16384u)) * 200 >> 15; + if (t - ui.key_t < 500) + ca = 200; + ck_rect caret = {x + S(3), b.y + b.h / 2 - S(12), ck_max(S(2), 2), S(24)}; + if (ck_clip(&caret, r)) + for (int32_t y = caret.y; y < caret.y + caret.h; y++) + for (int32_t xx = caret.x; xx < caret.x + caret.w; xx++) { + uint32_t *p = ui.back + (size_t)y * (size_t)ui.w + xx; + *p = ck_add(*p, CK_RGB(150, 170, 255), (40 + ca) * A >> 8); + } + if (ui.footer && !ui.input_len) { + unsigned n = 0; + while (ui.footer[n]) + n++; + int32_t fw = (int32_t)ck_af_measure(&ui.small, ui.footer, n); + text(&ui.cv, r, &ui.small, (ui.w - fw) / 2, b.y + b.h + S(34), ui.footer, n, CK_RGB(130, 140, 176), + 110 * A >> 8); + } +} + +/* ---- the guest's line rising into Allen, and the thoughts it becomes ---- */ + +static void curve(unsigned i, uint32_t t, int32_t *x, int32_t *y, uint32_t *a) +{ + /* thought i leaves the line at its own place and flies on a curve to the heart */ + uint32_t start = ui.guest_t + 150 + i * 40, dur = 850 + ck_hash((int32_t)i, 1, 5) % 300; + int32_t p = ck_prog(t, start, start + dur); + *a = t < start || p >= 256 ? 0 : 230; + int32_t gw = (int32_t)ck_af_measure(&ui.body, ui.guest, ui.guest_len); + int32_t x0 = (ui.guest_x + gw * (int32_t)(2 * i + 1) / 18) * 16, y0 = (ui.bar.y + ui.bar.h / 2 - S(60)) * 16; + int32_t x2 = ui.mind.hx, y2 = ui.mind.hy; + int32_t side = (int32_t)(ck_hash((int32_t)i, 2, 5) % 2u) ? 1 : -1; + int32_t x1 = (x0 + x2) / 2 + side * S(160 + (int32_t)(ck_hash((int32_t)i, 3, 5) % 140u)) * 16, y1 = (y0 + y2) / 2; + uint32_t e = ck_smooth(p), f = 256 - e; + *x = (int32_t)(((int64_t)x0 * f * f + 2 * (int64_t)x1 * f * e + (int64_t)x2 * e * e) >> 16); + *y = (int32_t)(((int64_t)y0 * f * f + 2 * (int64_t)y1 * f * e + (int64_t)y2 * e * e) >> 16); + if (p > 200) + *a = *a * (uint32_t)(256 - p) / 56; +} + +static ck_rect guest_area(void) +{ + if (!ui.guest_t) + return (ck_rect){0, 0, 0, 0}; + int32_t y0 = ui.cy - S(40), y1 = ui.bar.y + ui.bar.h; + return (ck_rect){ui.w / 2 - S(720), y0, S(1440), y1 - y0}; +} + +static void draw_guest(const ck_rect *r, uint32_t t) +{ + if (!ui.guest_t || t - ui.guest_t > 2400 || !ck_meets(ui.guest_box, r)) + return; + uint32_t p = (uint32_t)ck_prog(t, ui.guest_t, ui.guest_t + 900); + if (p < 256) { + int32_t y = ui.bar.y + ui.bar.h / 2 + S(7) - (int32_t)((int64_t)S(90) * ck_ease_out((int32_t)p) >> 8); + text(&ui.cv, r, &ui.body, ui.guest_x, y, ui.guest, ui.guest_len, CK_RGB(196, 208, 255), (256 - p) * 210 >> 8); + } + for (unsigned i = 0; i < 9; i++) { + int32_t x, y; + uint32_t a; + curve(i, t, &x, &y, &a); + if (!a) + continue; + ck_glow(&ui.cv, r, x, y, S(9) * 16, CK_RGB(150, 170, 255), a / 4); + ck_glow(&ui.cv, r, x, y, S(3) * 16, CK_RGB(255, 236, 210), a); + } +} + +/* ---- the notes constellation ---- */ + +static unsigned put_num(char *s, unsigned v) +{ + char t[10]; + unsigned n = 0, k = 0; + do + t[n++] = (char)('0' + v % 10); + while ((v /= 10) && n < sizeof t); + while (n) + s[k++] = t[--n]; + return k; +} + +/* where star j sits, 16ths of a pixel: the newest at the centre, the rest on + * a golden-angle spiral spread by the square root of the order */ +static void map_point(unsigned j, int32_t *x, int32_t *y) +{ + unsigned spread = ui.n > 7 ? ui.n - 1 : 6; + int64_t rad = (int64_t)ui.mr * 16 * (int64_t)ck_isqrt((uint64_t)j * 65536u / spread) / 256; + uint32_t ang = j * 25033u; + *x = ui.mx * 16 + 8 + (int32_t)(rad * ck_cos(ang) >> 14); + *y = ui.my * 16 + 8 + (int32_t)(rad * ck_sin(ang) >> 14); +} + +static void draw_map(const ck_rect *r, uint32_t t) +{ + uint32_t A = ui.map_a; + if (!A || !ui.n || !ck_meets(ui.map_box, r)) + return; + for (unsigned i = 0; i < ui.ne; i++) { + int32_t x0, y0, x1, y1; + map_point(ui.ea[i], &x0, &y0); + map_point(ui.eb[i], &x1, &y1); + ck_thread(&ui.cv, r, x0, y0, x1, y1, CK_RGB(130, 150, 255), 70 * A >> 8, 70 * A >> 8); + } + for (unsigned j = 0; j < ui.n; j++) { + int32_t x, y; + map_point(j, &x, &y); + int lit = (int)j == ui.lit; + uint32_t pulse = lit ? (uint32_t)(16384 + ck_sin((t - ui.map_t) * 65536u / 1400u)) * 60 >> 15 : 0; + uint32_t c = lit ? CK_RGB(255, 214, 160) : CK_RGB(206, 220, 255); + ck_glow(&ui.cv, r, x, y, S(lit ? 16 : 8) * 16, c, (lit ? 70 + pulse : 30) * A >> 8); + ck_glow(&ui.cv, r, x, y, S(lit ? 4 : 3) * 16, c, (lit ? 255 : 190) * A >> 8); + } + /* the spark that carried the note out from Allen */ + if (ui.lit >= 0 && t - ui.map_t < 1100) { + int32_t lx, ly; + map_point((unsigned)ui.lit, &lx, &ly); + int32_t p = ck_prog(t, ui.map_t, ui.map_t + 900); + for (int k = 0; k < 4 && p < 256; k++) { + uint32_t e = ck_smooth(ck_clamp(p - k * 18, 0, 256)); + int32_t x = ui.mind.hx + (int32_t)((int64_t)(lx - ui.mind.hx) * e >> 8); + int32_t y = ui.mind.hy + (int32_t)((int64_t)(ly - ui.mind.hy) * e >> 8) - + (int32_t)((int64_t)S(60) * 16 * (e * (256 - e) >> 6) >> 8); + ck_glow(&ui.cv, r, x, y, S(5) * 16, CK_RGB(255, 222, 176), 220u >> k); + } + } + char line[48]; + unsigned n = put_num(line, ui.total); + n += copy(line + n, ui.total == 1 ? " note, " : " notes, ", 16); + n += put_num(line + n, ui.links); + n += copy(line + n, ui.links == 1 ? " link" : " links", 16); + int32_t hw = (int32_t)ck_af_measure(&ui.small, "Notes", 5); + text(&ui.cv, r, &ui.small, ui.mx - hw / 2, ui.my - ui.mr - S(34), "Notes", 5, CK_RGB(170, 180, 214), 170 * A >> 8); + int32_t lw = (int32_t)ck_af_measure(&ui.small, line, n); + text(&ui.cv, r, &ui.small, ui.mx - lw / 2, ui.my + ui.mr + S(40), line, n, CK_RGB(150, 160, 196), 150 * A >> 8); + if (ui.lit >= 0 && ui.label_len) { + char cut[TEXT_MAX + 4]; + unsigned m = ui.label_len; + int32_t room = S(300); + while (m > 0 && (int32_t)ck_af_measure(&ui.small, ui.label, m) + (m < ui.label_len ? S(14) : 0) > room) + m--; + for (unsigned i = 0; i < m; i++) + cut[i] = ui.label[i]; + if (m < ui.label_len) + cut[m++] = '.', cut[m++] = '.', cut[m++] = '.'; + int32_t cw = (int32_t)ck_af_measure(&ui.small, cut, m); + text(&ui.cv, r, &ui.small, ui.mx - cw / 2, ui.my + ui.mr + S(68), cut, m, CK_RGB(255, 222, 180), 200 * A >> 8); + } +} + +/* ---- the flash of the merger ---- */ + +static int flash(uint32_t t, int32_t *rad, uint32_t *a) +{ + if (t < CK_NIGHT_MERGE_MS || t >= CK_NIGHT_MERGE_MS + 1600) + return 0; + uint32_t tm = t - CK_NIGHT_MERGE_MS; + *rad = (S(40) + (int32_t)((int64_t)S(220) * ck_ease_out(ck_prog(tm, 0, 1200)) >> 8)) * 16; + uint32_t rise = ck_smooth(ck_prog(tm, 0, 120)); + *a = rise * (ck_exp_neg(tm > 120 ? (tm - 120) * 256 / 450 : 0) >> 8) * 230 >> 16; + return *a > 0; +} + +/* The flash fills everything at its height; then the remaining hole's shadow + * takes its black back (within 300 ms), so the light rings it instead of + * filling it. */ +static void unflash(const ck_rect *r, uint32_t t) +{ + uint32_t tm = t - CK_NIGHT_MERGE_MS; + if (ui.night.holes != 1 || tm < 100) + return; + uint32_t keep = 256 - ck_smooth(ck_prog(tm, 100, 400)); /* of the flash, inside the shadow */ + int32_t hx = ui.night.hole[0].x, hy = ui.night.hole[0].y, rs = ui.night.hole[0].rs; + ck_rect box = {(hx - rs) >> 4, (hy - rs) >> 4, (2 * rs >> 4) + 2, (2 * rs >> 4) + 2}; + if (rs <= 16 || !ck_clip(&box, r)) + return; + for (int32_t y = box.y; y < box.y + box.h; y++) + for (int32_t x = box.x; x < box.x + box.w; x++) { + int32_t dx = x * 16 + 8 - hx, dy = y * 16 + 8 - hy; + uint32_t d = ck_isqrt((uint32_t)(dx * dx + dy * dy)); /* 16ths of a pixel */ + if (d >= (uint32_t)rs) + continue; + uint32_t in = (uint32_t)rs - d >= 16 ? 256 : ((uint32_t)rs - d) * 16; /* a pixel's soft edge */ + uint32_t k = 256 - (in * (256 - keep) >> 8); + ui.back[(size_t)y * (size_t)ui.w + x] = ck_scale(ui.back[(size_t)y * (size_t)ui.w + x], k); + } +} + +static ck_rect flash_box(uint32_t t) +{ + int32_t rad; + uint32_t a; + if (!flash(t, &rad, &a)) + return (ck_rect){0, 0, 0, 0}; + int32_t r = (rad >> 4) + 2; + return (ck_rect){ui.cx - r, ui.cy - r, 2 * r + 1, 2 * r + 1}; +} + +/* ---- putting a part of the screen together ---- */ + +static void present(const ck_rect *r) +{ + for (int32_t y = r->y; y < r->y + r->h; y++) { + const uint32_t *src = ui.back + (size_t)y * (size_t)ui.w + r->x; + volatile uint32_t *dst = ui.fb + (size_t)y * ui.pitch + r->x; + if (ui.format == 1) + for (int32_t x = 0; x < r->w; x++) + dst[x] = src[x]; + else + for (int32_t x = 0; x < r->w; x++) { + uint32_t c = src[x]; + dst[x] = (c & 0xff00u) | (c >> 16 & 0xffu) | (c & 0xffu) << 16; + } + } +} + +static void compose(const ck_rect *r) +{ + uint32_t t = ui.t; + ck_night_base(&ui.night, &ui.cv, r); + ck_night_lights(&ui.night, &ui.cv, r, ui.shimmer, ui.level * ui.shimmer >> 9); + int32_t rad; + uint32_t a; + if (flash(t, &rad, &a)) { + ck_glow(&ui.cv, r, ui.cx * 16 + 8, ui.cy * 16 + 8, rad, CK_RGB(200, 210, 255), a / 3); + ck_glow(&ui.cv, r, ui.cx * 16 + 8, ui.cy * 16 + 8, rad / 3, CK_RGB(255, 240, 224), a); + unflash(r, t); + } + draw_map(r, t); + ck_mind_draw(&ui.mind, &ui.cv, r); + draw_guest(r, t); + draw_words(&ui.now, r, t); + draw_bar(r, t); + present(r); +} + +/* ---- the tiles that changed ---- */ + +static void mark(ck_rect r) +{ + ck_rect all = {0, 0, ui.w, ui.h}; + if (r.w <= 0 || r.h <= 0 || !ck_clip(&r, &all)) + return; + for (int32_t ty = r.y / TH; ty <= (r.y + r.h - 1) / TH; ty++) + for (int32_t tx = r.x / TW; tx <= (r.x + r.w - 1) / TW; tx++) + ui.tiles[ty * ui.tx + tx] = 1; +} + +static void mark_all(void) +{ + for (int32_t i = 0; i < ui.tx * ui.ty; i++) + ui.tiles[i] = 1; +} + +/* the tiles the ripple's band crosses, between radius lo and hi */ +static void mark_ring(int32_t lo, int32_t hi) +{ + if (hi <= 0) + return; + lo = ck_max(lo, 0); + int64_t lo2 = (int64_t)lo * lo, hi2 = (int64_t)hi * hi; + for (int32_t ty = 0; ty < ui.ty; ty++) + for (int32_t tx = 0; tx < ui.tx; tx++) { + int32_t x0 = tx * TW, y0 = ty * TH, x1 = x0 + TW, y1 = y0 + TH; + int64_t nx = ck_clamp(ui.cx, x0, x1) - ui.cx, ny = ck_clamp(ui.cy, y0, y1) - ui.cy; + int64_t fx = ck_max(ck_abs(x0 - ui.cx), ck_abs(x1 - ui.cx)), + fy = ck_max(ck_abs(y0 - ui.cy), ck_abs(y1 - ui.cy)); + if (nx * nx + ny * ny <= hi2 && fx * fx + fy * fy >= lo2) + ui.tiles[ty * ui.tx + tx] = 1; + } +} + +static unsigned strips(void) +{ + unsigned n = 0; + for (int32_t ty = 0; ty < ui.ty; ty++) { + uint8_t *row = ui.tiles + ty * ui.tx; + int32_t runs = 0, first = -1, last = -1; + for (int32_t tx = 0; tx < ui.tx; tx++) + if (row[tx]) { + if (first < 0) + first = tx; + if (tx == 0 || !row[tx - 1]) + runs++; + last = tx; + } + if (first < 0) + continue; + int32_t y = ty * TH, h = ck_min(TH, ui.h - y); + if (runs > 6 || n + (unsigned)runs > JOBS_MAX) { /* one strip for the row */ + int32_t x = first * TW; + ui.jobs[n++] = (ck_rect){x, y, ck_min((last + 1) * TW, ui.w) - x, h}; + } else + for (int32_t tx = 0; tx < ui.tx; tx++) { + if (!row[tx] || (tx > 0 && row[tx - 1])) + continue; + int32_t end = tx; + while (end + 1 < ui.tx && row[end + 1]) + end++; + ui.jobs[n++] = (ck_rect){tx * TW, y, ck_min((end + 1) * TW, ui.w) - tx * TW, h}; + } + for (int32_t tx = 0; tx < ui.tx; tx++) + row[tx] = 0; + if (n >= JOBS_MAX) + break; + } + return n; +} + +int ck_allen_ui_help(void) +{ + for (;;) { + uint64_t v = __atomic_load_n(&ui.ticket, __ATOMIC_ACQUIRE); + uint32_t next = (uint32_t)(v & 0xffffu), count = (uint32_t)(v >> 16 & 0xffffu); + if (next >= count) + return 0; + if (__atomic_compare_exchange_n(&ui.ticket, &v, v + 1, 0, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) { + compose(&ui.jobs[next]); + __atomic_fetch_add(&ui.done, 1, __ATOMIC_RELEASE); + return 1; + } + } +} + +/* ---- the frame ---- */ + +/* what the keyboard side left, taken under the lock */ +static void take_notes(uint32_t t) +{ + lock(); + if (note.refresh) + note.refresh = 0, mark_all(); + if (note.wake_gen != ui.seen_wake) { + ui.seen_wake = note.wake_gen; + ui.footer = note.footer; + if (!ui.on) + ui.on = 1, ui.wake_t = t, ui.quiet_t = ck_max((int32_t)t, (int32_t)FORMED_MS); + } + if (note.input_gen != ui.seen_input) { + ui.seen_input = note.input_gen; + if (note.input_len > ui.input_len) + ck_mind_key(&ui.mind, t); + ui.input_len = note.input_len; + for (unsigned i = 0; i < ui.input_len; i++) + ui.input[i] = note.input[i]; + ui.key_t = t, ui.quiet_t = t, ui.input_moved = 1; + } + if (note.said_gen != ui.seen_said) { + ui.seen_said = note.said_gen; + if (note.has_line) { + ui.guest_len = copy(ui.guest, note.line, TEXT_MAX); + ui.guest_x = ui.bar.x + S(30); + ui.guest_t = t; + } + /* what is on screen fades; Allen thinks, then speaks */ + if (ui.now.len && !ui.now.fade) + ui.now.fade = t; + ui.next = (struct words){0}; + ui.next.len = copy(ui.next.text, note.reply, TEXT_MAX); + uint32_t think = note.has_line ? 900u + ck_min((int32_t)ui.next.len * 6, 700) : 500u; + ui.speak_t = ck_max((int32_t)(t + think), (int32_t)FORMED_MS + 300); + ui.input_len = 0; + ui.input_moved = 1; + ui.quiet_t = t; + ck_mind_mode(&ui.mind, CK_MIND_THINK, t); + } + if (note.map_gen != ui.seen_map) { + ui.seen_map = note.map_gen; + ui.n = note.n, ui.ne = note.ne, ui.total = note.total, ui.links = note.links, ui.lit = note.lit; + for (unsigned i = 0; i < ui.ne; i++) + ui.ea[i] = note.ea[i], ui.eb[i] = note.eb[i]; + ui.label_len = copy(ui.label, note.label, TEXT_MAX); + if (ui.lit >= 0 && ui.n) + ui.map_t = t ? t : 1; + mark(ui.map_box); + } + unlock(); +} + +static uint32_t toward(uint32_t cur, uint32_t want, uint32_t dt, uint32_t full_ms) +{ + uint32_t step = (uint32_t)((uint64_t)256 * dt / full_ms); + step = step || !dt ? step : 1; + if (cur < want) + return cur + step < want ? cur + step : want; + return cur > want + step ? cur - step : want; +} + +/* moves everything to t and marks what changed */ +static void advance(uint32_t t) +{ + uint32_t prev = ui.last, dt = t - prev; + take_notes(t); + /* the sky */ + ck_night_at(&ui.night, t); + if (t < CK_NIGHT_FADE_END_MS + FRAME_MS * 2) + mark_all(); + mark(ui.lens_was); + mark(ui.night.lens); + ui.lens_was = ui.night.lens; + if (ui.night.ripple_w || ui.ripple_was >= 0) { + int32_t reach = ui.night.ripple_w * 22 / 10 + 2; + if (ui.ripple_was >= 0) + mark_ring(ui.ripple_was - reach - 8, ui.ripple_was + reach + 8); + if (ui.night.ripple_w) + mark_ring(ui.night.ripple_r - reach - 8, ui.night.ripple_r + reach + 8); + ui.ripple_was = ui.night.ripple_w ? ui.night.ripple_r : -1; + } + ck_rect fb = flash_box(t); + mark(ui.flash_was); + mark(fb); + ui.flash_was = fb; + for (unsigned i = ui.twinkle_turn % 3; i < ui.night.ntw; i += 3) + mark(ck_night_star_box(&ui.night, i)); + ui.twinkle_turn++; + + /* the conversation: speaking starts, words reach the mind and the galaxies */ + if (ui.speak_t && t >= ui.speak_t) { + ui.now = ui.next; + ui.now.from = ui.speak_t; + lay_out(&ui.now); + ui.speak_t = 0; + ck_mind_mode(&ui.mind, CK_MIND_SPEAK, t); + } + struct words *w = &ui.now; + if (w->len && t >= w->from && prev < w->done) { + for (unsigned i = 0; i < w->len; i++) { + uint32_t at = w->from + i * LETTER_MS; + if (at > prev && at <= t && w->text[i] != ' ' && (i == 0 || w->text[i - 1] == ' ')) + ck_mind_word(&ui.mind, t), ui.word_t = t; + } + } + uint32_t last_letter = w->len ? w->from + w->len * LETTER_MS : 0; + int speaking = w->len && t >= w->from && t < last_letter + 300; + ui.level = speaking ? ck_exp_neg((t - ui.word_t) * 256 / 200) >> 8 : 0; + ck_mind_voice(&ui.mind, ui.level); + if (!speaking && !ui.speak_t && (ui.mind.mode == CK_MIND_SPEAK || ui.mind.mode == CK_MIND_THINK) && + w->len && t >= w->from) { + ck_mind_mode(&ui.mind, CK_MIND_IDLE, t); + ui.quiet_t = t; + } + if (ui.mind.mode != CK_MIND_THINK && ui.mind.mode != CK_MIND_SPEAK) + ck_mind_mode(&ui.mind, ui.input_len && t - ui.key_t < 4000 ? CK_MIND_LISTEN : CK_MIND_IDLE, t); + uint32_t rise = w->len ? ck_smooth(ck_prog(t, w->from, w->from + 600)) : 0; + uint32_t fall = w->len ? 256 - ck_smooth(ck_prog(t, last_letter + 300, last_letter + 2800)) : 0; + ui.shimmer = rise < fall ? rise : fall; + if (ui.shimmer || ui.shimmer_was) + for (unsigned i = 0; i < CK_NIGHT_GALAXIES; i++) + mark(ui.night.gal[i].box); + ui.shimmer_was = ui.shimmer; + if (w->len && (t < w->done + 40 || words_alpha(w, t) != words_alpha(w, prev))) + mark(w->box); + if (ui.words_was.w && (ui.words_was.x != w->box.x || ui.words_was.w != w->box.w || ui.words_was.h != w->box.h)) + mark(ui.words_was); + ui.words_was = w->box; + if (w->len && !words_alpha(w, t) && t > w->from) + *w = (struct words){0}; + + /* Allen */ + ck_mind_at(&ui.mind, t); + mark(ck_mind_dirty(&ui.mind)); + if (ui.guest_t) { + ck_rect g = guest_area(); + mark(g); + ui.guest_box = g; + if (t - ui.guest_t > 2400) + ui.guest_t = 0; + } + + /* the bar: up once Allen has formed and while in use; down when things rest */ + int want = ui.on && t >= FORMED_MS && (ui.input_len || t - ui.quiet_t < BAR_REST_MS || speaking || ui.speak_t); + ui.bar_a = toward(ui.bar_a, want ? 256 : 0, dt, want ? (t - ui.key_t < 300 ? 250 : 900) : 1400); + if (ui.bar_a || ui.bar_was || ui.input_moved) + mark(ui.bar_box); + ui.bar_was = ui.bar_a; + ui.input_moved = 0; + + /* the notes: shown a while after a note is saved or handed back */ + int show = ui.map_t && t - ui.map_t < MAP_SHOW_MS && ui.n; + ui.map_a = toward(ui.map_a, show ? 256 : 0, dt, show ? 700 : 1500); + if (ui.map_a || ui.map_was) + mark(ui.map_box); + ui.map_was = ui.map_a; + if (ui.lit >= 0 && ui.map_t && t - ui.map_t < 1200) /* the spark's path, Allen to the star */ + mark(ck_union(ck_mind_dirty(&ui.mind), ui.map_box)); +} + +int ck_allen_ui_tick(uint64_t now) +{ + if (!ui.started) + return 0; + uint32_t t = ms(now); + if (ui.frames && t - ui.last < FRAME_MS && !__atomic_load_n(¬e.refresh, __ATOMIC_ACQUIRE)) + return 0; + uint64_t c0 = ui.clock ? ui.clock() : 0; + ui.t = t; + advance(t); + unsigned n = strips(); + ui.done = 0; + __atomic_store_n(&ui.ticket, (uint64_t)n << 16, __ATOMIC_RELEASE); + while (ck_allen_ui_help()) + ; + while (__atomic_load_n(&ui.done, __ATOMIC_ACQUIRE) < n) + relax(); + ui.last = t; + ui.frames++; + if (ui.clock) { + uint64_t c = ui.clock() - c0; + uint32_t us = (uint32_t)(c * 1000000u / ui.hz); + ui.total_ticks += us; + if (us > ui.slowest) + ui.slowest = us; + } + return 1; +} + +void ck_allen_ui_stats(uint32_t *frames, uint32_t *slowest_us, uint32_t *average_us) +{ + *frames = ui.frames; + *slowest_us = ui.slowest; + *average_us = ui.frames ? ui.total_ticks / ui.frames : 0; +} + +/* ---- the interface ---- */ + +static size_t face_bytes(uint32_t cap) +{ + size_t s = cap * 256u / 20u; /* as ck_af_face_init */ + size_t w = (26 * s + 2 * 1024) / 256 + 6, h = (33 * s + 2 * 1024) / 256 + 6; + return CK_AF_COUNT * w * h; +} + +static uint32_t scale_for(uint32_t w, uint32_t h) +{ + uint32_t kw = w * 256u / 1920u, kh = h * 256u / 1080u; + return kw < kh ? kw : kh; +} + +#define CAP_VOICE 19 +#define CAP_BODY 15 +#define CAP_SMALL 11 + +size_t ck_allen_ui_mem_bytes(uint32_t w, uint32_t h) +{ + uint32_t k = scale_for(w, h); + return (size_t)w * h * 4 + ck_night_mem_bytes(w, h, k) + face_bytes(CAP_VOICE * k / 256) + + face_bytes(CAP_BODY * k / 256) + face_bytes(CAP_SMALL * k / 256) + 64; +} + +int ck_allen_ui_started(void) { return ui.started; } +int ck_allen_ui_on(void) { return ui.on; } + +int ck_allen_ui_start(volatile uint32_t *fb, uint32_t w, uint32_t h, uint32_t pitch, uint32_t format, void *mem, + size_t mem_len, uint64_t hz, uint64_t now, uint64_t (*clock)(void)) +{ + if (!fb || w < 640 || h < 400 || pitch < w || format > 1 || hz == 0 || !mem || + mem_len < ck_allen_ui_mem_bytes(w, h) || ((w + TW - 1) / TW) * ((h + TH - 1) / TH) > TILES_MAX) + return -1; + ui = (__typeof__(ui)){0}; + ui.fb = fb; + ui.w = (int32_t)w, ui.h = (int32_t)h; + ui.pitch = pitch, ui.format = format, ui.hz = hz, ui.t0 = now, ui.clock = clock; + ui.k = scale_for(w, h); + ui.tx = (int32_t)((w + TW - 1) / TW), ui.ty = (int32_t)((h + TH - 1) / TH); + uint8_t *p = mem; + ui.back = (uint32_t *)p; + p += (size_t)w * h * 4; + ui.cv = (ck_canvas){ui.back, ui.w, ui.h}; + ui.cx = ui.w / 2, ui.cy = ui.h * 40 / 100; + size_t nb = ck_night_mem_bytes(w, h, ui.k); + if (ck_night_init(&ui.night, w, h, ui.k, ui.cx, ui.cy, p, nb, ui.back)) + return -1; + p += nb; + uint32_t caps[3] = {CAP_VOICE * ui.k / 256, CAP_BODY * ui.k / 256, CAP_SMALL * ui.k / 256}; + ck_af_face *faces[3] = {&ui.voice, &ui.body, &ui.small}; + unsigned weights[3] = {1000, 1150, 1250}; + for (int i = 0; i < 3; i++) { + size_t n = face_bytes(caps[i]); + ck_af_face_init(faces[i], caps[i], weights[i], p, n); + p += n; + /* every letter now, so drawing never writes to the face (other cores read it) */ + for (int c = CK_AF_FIRST; c <= CK_AF_LAST; c++) + (void)ck_af_glyph_get(faces[i], (char)c); + } + ck_mind_init(&ui.mind, ui.cx, ui.cy, ui.k, BORN_MS); + /* layout (design px on 1920 x 1080, centred) */ + int32_t bw = S(720), bh = S(54); + ui.bar = (ck_rect){(ui.w - bw) / 2, ui.h - S(150), bw, bh}; + ui.bar_box = (ck_rect){ui.bar.x - S(20), ui.bar.y - S(20), bw + S(40), bh + S(80)}; + ui.bar_box.x = ck_min(ui.bar_box.x, ui.w / 2 - S(360)); + ui.bar_box.w = ck_max(ui.bar_box.w, S(720)); + ui.mx = ui.w * 84 / 100, ui.my = ui.h * 42 / 100, ui.mr = S(130); + ui.map_box = (ck_rect){ui.mx - S(190), ui.my - ui.mr - S(64), S(380), 2 * ui.mr + S(150)}; + ui.lit = -1; + ui.ripple_was = -1; + ui.seen_input = note.input_gen, ui.seen_said = note.said_gen, ui.seen_wake = note.wake_gen; + ui.seen_map = note.map_gen - 1; /* the map kept from before is taken by the first frame */ + ui.started = 1; + ui.ticket = 0; + return 0; +} + +void ck_allen_ui_refresh(void) +{ + lock(); + note.refresh = 1; + unlock(); +} + +void ck_allen_ui_wake(const char *footer, uint64_t now) +{ + (void)now; + lock(); + note.footer = footer; + note.wake_gen++; + unlock(); +} + +void ck_allen_ui_input(const char *buf, unsigned len, uint64_t now) +{ + (void)now; + if (len > TEXT_MAX - 1) + len = TEXT_MAX - 1; + lock(); + for (unsigned i = 0; i < len; i++) + note.input[i] = buf[i]; + note.input_len = len; + note.input_gen++; + unlock(); +} + +void ck_allen_ui_said(const char *line, const char *reply, uint64_t now) +{ + (void)now; + lock(); + note.has_line = line != 0; + copy(note.line, line, TEXT_MAX); + copy(note.reply, reply, TEXT_MAX); + note.said_gen++; + unlock(); +} + +void ck_allen_ui_map(unsigned n, const uint8_t *ea, const uint8_t *eb, unsigned ne, int lit, const char *label, + unsigned total, unsigned links) +{ + lock(); + note.n = n < CK_ALLEN_UI_MAP_NODES ? n : CK_ALLEN_UI_MAP_NODES; + note.ne = 0; + for (unsigned i = 0; i < ne && note.ne < CK_ALLEN_UI_MAP_LINKS; i++) + if (ea[i] < note.n && eb[i] < note.n && ea[i] != eb[i]) { + note.ea[note.ne] = ea[i]; + note.eb[note.ne++] = eb[i]; + } + note.lit = lit >= 0 && (unsigned)lit < note.n ? lit : -1; + copy(note.label, label, TEXT_MAX); + note.total = total; + note.links = links; + note.map_gen++; + unlock(); +} diff --git a/native/kernel/ui/allen_ui.h b/native/kernel/ui/allen_ui.h new file mode 100644 index 00000000..685f9b78 --- /dev/null +++ b/native/kernel/ui/allen_ui.h @@ -0,0 +1,69 @@ +/* allen_ui.h -- Allen's home on the display. + * + * The screen opens on a dark night sky (ui/night.c): the stars come out, two + * black holes circle and merge, and from the light of the merger Allen + * gathers (ui/mind.c): a mind drawn as light, in the middle of the screen. + * The person is his guest. A quiet bar at the bottom takes what they type; + * Allen's answers appear under him, word by word, while the galaxies in the + * sky shimmer with his voice. Nothing else is on the screen unless it is in + * use: the bar fades away when the conversation rests (a key brings it + * back), Allen's words fade once they have been read, and the map of his + * notes (a small constellation) shows only when a note is saved or handed + * back. + * + * Drawing: every pixel is worked out from its position and the time, so a + * frame redraws only the parts of the screen that change, in strips that + * several processor cores can draw at once (ck_allen_ui_help). Integer + * math, no MMIO of its own (the caller hands in the framebuffer), host + * tested in ui/tests/allen_ui_test.c. Text uses Allen's own typeface + * (allen_font.h). */ +#ifndef AIENOS_ALLEN_UI_H +#define AIENOS_ALLEN_UI_H +#include +#include + +/* RAM for a w x h screen (two full-screen layers and the glyph masks). */ +size_t ck_allen_ui_mem_bytes(uint32_t w, uint32_t h); +/* Takes over the screen and starts the night: fb = the framebuffer (pitch in + * pixels; format 0 RGBX, 1 BGRX), mem = ck_allen_ui_mem_bytes(w, h) bytes, + * hz = ticks per second of the clock `now` counts in, clock = that clock + * (read to time each frame; NULL: frames are not timed). 0, or -1 (bad + * size or format, short mem). */ +int ck_allen_ui_start(volatile uint32_t *fb, uint32_t w, uint32_t h, uint32_t pitch, uint32_t format, void *mem, + size_t mem_len, uint64_t hz, uint64_t now, uint64_t (*clock)(void)); +int ck_allen_ui_started(void); +/* Allen is ready to talk: the bar comes up once he has formed. footer: one + * short line shown under the empty bar. */ +void ck_allen_ui_wake(const char *footer, uint64_t now); +int ck_allen_ui_on(void); +/* The line being typed changed (buf holds len characters). */ +void ck_allen_ui_input(const char *buf, unsigned len, uint64_t now); +/* A line was entered and Allen answered: the line rises from the bar into + * him, he thinks, then speaks the answer. line NULL: Allen speaks first (the + * welcome after a restart). */ +void ck_allen_ui_said(const char *line, const char *reply, uint64_t now); +/* Draws a frame when one is due (at most 60 a second) and returns 1, else + * 0. One caller at a time; ck_allen_ui_help may run on other cores. */ +int ck_allen_ui_tick(uint64_t now); +/* Another core's share of the frame in progress: draws strips while there + * are any; 1 if it drew one. */ +int ck_allen_ui_help(void); +/* The whole screen is drawn again by the next frame, at once (after + * something else wrote to it). */ +void ck_allen_ui_refresh(void); +/* Frames drawn, the slowest and the average (microseconds). */ +void ck_allen_ui_stats(uint32_t *frames, uint32_t *slowest_us, uint32_t *average_us); + +/* The notes map, a small constellation to the right of Allen: n notes as + * stars, 0 the newest at the centre, the older ones spiralling out (at most + * CK_ALLEN_UI_MAP_NODES); ne links, star ea[i] to star eb[i] (notes that + * share a key word; at most CK_ALLEN_UI_MAP_LINKS); lit the star of the note + * just saved or handed back (-1: none), with label its text; total and links + * count every live note and link. Shown for a while when lit >= 0: a spark + * flies from Allen to the star. */ +#define CK_ALLEN_UI_MAP_NODES 48u +#define CK_ALLEN_UI_MAP_LINKS 160u +void ck_allen_ui_map(unsigned n, const uint8_t *ea, const uint8_t *eb, unsigned ne, int lit, const char *label, + unsigned total, unsigned links); + +#endif diff --git a/native/kernel/ui/chirp.c b/native/kernel/ui/chirp.c new file mode 100644 index 00000000..d3e73290 --- /dev/null +++ b/native/kernel/ui/chirp.c @@ -0,0 +1,192 @@ +/* chirp.c -- the startup sound; see chirp.h. + * + * Every frame is worked out from where it sits on the night's timeline. + * With L the share of the inspiral left (1 at CK_CHIRP_START_MS, 0 at the + * merger), the holes' orbit goes as 1 - L^(5/8); so does the sound's + * phase, scaled so it starts at CK_CHIRP_FROM_HZ, which makes its pitch go + * as L^(-3/8). Once the pitch reaches CK_CHIRP_TO_HZ (the last few + * milliseconds) it holds there through the merger and the fade. Loudness + * goes as L^(-1/4), which is pitch^(2/3), reaching CK_CHIRP_PEAK where the + * pitch stops rising. Phases are in 2^32ths of a cycle; L and its powers in + * Q30. */ +#include "chirp.h" + +#define F0_FRAME (CK_CHIRP_RATE / 1000u * (CK_CHIRP_START_MS - CK_CHIRP_IN_MS)) /* the sound comes in */ +#define F1_FRAME (CK_CHIRP_RATE / 1000u * CK_CHIRP_START_MS) /* the sweep begins */ +#define F2_FRAME (CK_CHIRP_RATE / 1000u * CK_NIGHT_MERGE_MS) /* the merger */ +#define Q30 (1ull << 30) +#define DECAY 1072996429ull /* exp(-1 / (30 ms * 48 kHz)) in Q30: the fade's time constant is 30 ms */ + +static int16_t sin_t[4096]; /* Q14 */ +static uint32_t cap_frame; /* the pitch stops rising here */ +static uint64_t cap_l14; /* L^(1/4) there */ +static uint64_t cap_phase; /* the phase there */ +static int ready; + +static uint64_t isqrt(uint64_t x) +{ + uint64_t r = 0, bit = 1ull << 62; + while (bit > x) + bit >>= 2; + while (bit) { + if (x >= r + bit) { + x -= r + bit; + r = (r >> 1) + bit; + } else { + r >>= 1; + } + bit >>= 2; + } + return r; +} + +/* L at a frame of the inspiral, and its eighth root (both Q30) */ +static uint64_t left_q30(uint32_t f) { return ((uint64_t)(F2_FRAME - f) << 30) / (F2_FRAME - F1_FRAME); } + +static uint64_t root8(uint64_t l) +{ + for (int i = 0; i < 3; i++) + l = isqrt(l << 30); + return l; +} + +static uint64_t mul(uint64_t a, uint64_t b) { return a * b >> 30; } + +/* phase over the inspiral before the cap: P1 + K (1 - L^(5/8)), K chosen so + * the pitch starts at CK_CHIRP_FROM_HZ: K = FROM_HZ * 8/5 * inspiral seconds */ +static uint64_t inspiral_phase(uint32_t f) +{ + uint64_t r = root8(left_q30(f)), l58 = mul(mul(mul(mul(r, r), r), r), r); + uint64_t p1 = ((uint64_t)CK_CHIRP_FROM_HZ * (F1_FRAME - F0_FRAME) << 32) / CK_CHIRP_RATE; + uint64_t k = (uint64_t)CK_CHIRP_FROM_HZ * 8 * (F2_FRAME - F1_FRAME); /* K * 5 * RATE */ + return p1 + ((k * (Q30 - l58) << 2) / (5ull * CK_CHIRP_RATE)); +} + +static void setup(void) +{ + const int64_t C = 1073740561, S = 1647099; /* cos, sin of a 4096th of a turn, Q30 */ + int64_t c = 1ll << 30, s = 0; + for (unsigned k = 0; k <= 1024; k++) { + int16_t v = k == 1024 ? 16384 : (int16_t)((s + (1 << 15)) >> 16); + sin_t[k] = v; + sin_t[2048 - k] = v; + sin_t[(2048 + k) & 4095] = (int16_t)-v; + sin_t[(4096 - k) & 4095] = (int16_t)-v; + int64_t nc = (c * C - s * S) >> 30, ns = (s * C + c * S) >> 30; + c = nc, s = ns; + } + /* the first frame where FROM_HZ * L^(-3/8) reaches TO_HZ, i.e. where + * L^(3/8) falls to FROM_HZ / TO_HZ (L^(3/8) only falls) */ + uint64_t want = ((uint64_t)CK_CHIRP_FROM_HZ << 30) / CK_CHIRP_TO_HZ; + uint32_t lo = F1_FRAME, hi = F2_FRAME; + while (lo < hi) { + uint32_t mid = lo + (hi - lo) / 2; + uint64_t r = root8(left_q30(mid)); + if (mul(mul(r, r), r) <= want) + hi = mid; + else + lo = mid + 1; + } + cap_frame = lo; + uint64_t r = root8(left_q30(lo)); + cap_l14 = mul(r, r); + cap_phase = inspiral_phase(lo); + ready = 1; +} + +static uint64_t phase_at(uint32_t f) +{ + if (f < F1_FRAME) + return ((uint64_t)CK_CHIRP_FROM_HZ * (f - F0_FRAME) << 32) / CK_CHIRP_RATE; + if (f < cap_frame) + return inspiral_phase(f); + return cap_phase + ((uint64_t)CK_CHIRP_TO_HZ * (f - cap_frame) << 32) / CK_CHIRP_RATE; +} + +static uint64_t decay_pow(uint32_t k) /* DECAY^k, Q30 */ +{ + uint64_t r = Q30, b = DECAY; + while (k) { + if (k & 1) + r = mul(r, b); + b = mul(b, b); + k >>= 1; + } + return r; +} + +uint32_t ck_chirp_level(uint32_t f) +{ + if (!ready) + setup(); + if (f < F0_FRAME || f >= CK_CHIRP_FRAMES) + return 0; + uint64_t steady = (uint64_t)CK_CHIRP_PEAK * cap_l14 >> 30; /* the level at L = 1 */ + if (f < F1_FRAME) { /* comes in smoothly (smoothstep) */ + uint64_t x = ((uint64_t)(f - F0_FRAME) << 16) / (F1_FRAME - F0_FRAME), s = x * x * (3ull * 65536 - 2 * x); + return (uint32_t)(steady * s >> 48); + } + if (f < cap_frame) { + uint64_t r = root8(left_q30(f)); + return (uint32_t)((uint64_t)CK_CHIRP_PEAK * cap_l14 / mul(r, r)); + } + if (f < F2_FRAME) + return CK_CHIRP_PEAK; + return (uint32_t)((uint64_t)CK_CHIRP_PEAK * decay_pow(f - F2_FRAME) >> 30); +} + +uint32_t ck_chirp_hz(uint32_t f) +{ + if (!ready) + setup(); + if (f < F0_FRAME || f >= CK_CHIRP_FRAMES) + return 0; + if (f < F1_FRAME) + return CK_CHIRP_FROM_HZ; + if (f >= cap_frame) + return CK_CHIRP_TO_HZ; + uint64_t r = root8(left_q30(f)); + return (uint32_t)(((uint64_t)CK_CHIRP_FROM_HZ << 30) / mul(mul(r, r), r)); +} + +void ck_chirp_fill(int16_t *out, uint32_t from, uint32_t n) +{ + if (!ready) + setup(); + for (uint32_t i = 0; i < n; i++) { + uint32_t f = from + i, a = ck_chirp_level(f); + int32_t v = 0; + if (a) { + uint32_t ph = (uint32_t)phase_at(f), k = ph >> 20, frac = ph >> 4 & 0xffffu; + int32_t s0 = sin_t[k], s1 = sin_t[(k + 1) & 4095]; + int32_t s = s0 + (int32_t)(((int64_t)(s1 - s0) * frac) >> 16); /* Q14 */ + v = (int32_t)(((int64_t)s * a) >> 14); + } + out[2 * i] = out[2 * i + 1] = (int16_t)v; + } +} + +/* The same chirp at 44.1 kHz for converters that take only that rate: frame + * j sits at 48 kHz frame j * 160 / 147, drawn as a straight line between the + * two 48 kHz frames either side (the chirp stays under 1000 Hz, far below + * either rate's limit). Each sample goes in the top 16 bits of a 32-bit slot, + * the layout a 24-bit converter reads (Linux: S32_LE with 24 bits used). */ +void ck_chirp_fill_441(int32_t *out, uint32_t from, uint32_t n) +{ + int16_t src[2 * 144]; + while (n) { + uint32_t m = n < 128u ? n : 128u, s0 = (uint32_t)((uint64_t)from * 160u / 147u); + uint32_t s1 = (uint32_t)((uint64_t)(from + m - 1) * 160u / 147u) + 1; + ck_chirp_fill(src, s0, s1 - s0 + 1); + for (uint32_t i = 0; i < m; i++) { + uint64_t at = (uint64_t)(from + i) * 160u; + uint32_t s = (uint32_t)(at / 147u) - s0, frac = (uint32_t)(at % 147u); + int32_t a = src[2 * s], b = src[2 * s + 2]; + int32_t v = (a * (int32_t)(147u - frac) + b * (int32_t)frac) / 147; + out[2 * i] = out[2 * i + 1] = (int32_t)((uint32_t)v << 16); + } + out += 2 * m; + from += m; + n -= m; + } +} diff --git a/native/kernel/ui/chirp.h b/native/kernel/ui/chirp.h new file mode 100644 index 00000000..359f0f4e --- /dev/null +++ b/native/kernel/ui/chirp.h @@ -0,0 +1,42 @@ +/* chirp.h -- the startup sound: a quick "blirp", the last moment of the chirp + * two bodies make as they spiral into each other and merge (a gravitational + * wave), raised into hearing and timed to the night sky of the startup + * (ui/night.h). Silent until CK_CHIRP_RISE_MS before the merger; then it + * comes in over CK_CHIRP_IN_MS and sweeps up in pitch and loudness the way + * the real wave does (pitch as t^(-3/8), loudness as pitch^(2/3), t the time + * left), with its peak at the merger (CK_NIGHT_MERGE_MS); then a short + * ringing fade. Under a second in all. Made from that formula, no recorded + * sound. Integer only (the kernel builds with -mgeneral-regs-only), + * freestanding, no memory of its own beyond a sine table. Host tested in + * ui/tests/chirp_test.c. */ +#ifndef AIENOS_CHIRP_H +#define AIENOS_CHIRP_H +#include +#include "night.h" + +#define CK_CHIRP_RATE 48000u /* frames a second; each frame is a left and a right sample, 16 bits */ +#define CK_CHIRP_FROM_HZ 200u /* the pitch the sweep starts at */ +#define CK_CHIRP_TO_HZ 1000u /* the pitch at the merger, held through the fade */ +#define CK_CHIRP_PEAK 22937 /* 70% of full scale */ +#define CK_CHIRP_RISE_MS 600u /* the sweep up to the merger */ +#define CK_CHIRP_IN_MS 40u /* the sound comes in over this, just before the sweep */ +#define CK_CHIRP_START_MS (CK_NIGHT_MERGE_MS - CK_CHIRP_RISE_MS) +#define CK_CHIRP_END_MS (CK_NIGHT_MERGE_MS + 300u) /* the ring has died away */ +#define CK_CHIRP_FRAMES (CK_CHIRP_RATE / 1000u * CK_CHIRP_END_MS) + +/* Writes frames [from, from + n) as left, right pairs into out (2n samples), + * frame 0 being the night's 0 ms. Silent past CK_CHIRP_FRAMES. Any frame + * can be asked for in any order: each is worked out from the formula. */ +void ck_chirp_fill(int16_t *out, uint32_t from, uint32_t n); + +/* The pitch in Hz and the loudness (0..CK_CHIRP_PEAK) at a frame. */ +uint32_t ck_chirp_hz(uint32_t frame); +uint32_t ck_chirp_level(uint32_t frame); + +/* The chirp at 44.1 kHz instead: frames [from, from + n) of that rate, frame + * 0 the night's 0 ms, each sample in the top 16 bits of a 32-bit slot (a + * 24-bit converter's layout), left and right. */ +#define CK_CHIRP_RATE_441 44100u +#define CK_CHIRP_FRAMES_441 (CK_CHIRP_RATE_441 / 100u * CK_CHIRP_END_MS / 10u) +void ck_chirp_fill_441(int32_t *out, uint32_t from, uint32_t n); +#endif diff --git a/native/kernel/ui/mind.c b/native/kernel/ui/mind.c new file mode 100644 index 00000000..427136d1 --- /dev/null +++ b/native/kernel/ui/mind.c @@ -0,0 +1,266 @@ +/* mind.c -- Allen's presence; see mind.h. */ +#include "mind.h" + +#define S(v) ((int32_t)(((int64_t)(v) * (int64_t)m->k + 128) / 256)) +#define INNER 24u /* the last INNER points sit inside the sphere */ +#define TILT 3641u /* the upright axis leans toward the viewer by 20 degrees, in 65536ths */ + +static uint32_t rnd(ck_mind *m) +{ + m->rng ^= m->rng << 13; + m->rng ^= m->rng >> 17; + m->rng ^= m->rng << 5; + return m->rng; +} + +static int64_t dist2(const int16_t *a, const int16_t *b) +{ + int64_t dx = a[0] - b[0], dy = a[1] - b[1], dz = a[2] - b[2]; + return dx * dx + dy * dy + dz * dz; +} + +static int has_edge(const ck_mind *m, unsigned a, unsigned b) +{ + for (unsigned i = 0; i < m->ne; i++) + if ((m->ea[i] == a && m->eb[i] == b) || (m->ea[i] == b && m->eb[i] == a)) + return 1; + return 0; +} + +void ck_mind_init(ck_mind *m, int32_t cx, int32_t cy, uint32_t k, uint32_t born) +{ + *m = (ck_mind){0}; + m->cx = cx, m->cy = cy, m->k = k, m->born = born; + m->R = S(118); + m->rng = 0x9e3779b9u; + m->spin = 349; /* a turn in 48 s */ + unsigned outer = CK_MIND_NODES - INNER; + for (unsigned i = 0; i < CK_MIND_NODES; i++) { + int64_t y, rr, x, z, len; + if (i < outer) { /* evenly spread over the sphere: a Fibonacci lattice */ + y = 16384 - (int64_t)(2 * i + 1) * 16384 / outer; + rr = (int64_t)ck_isqrt((uint64_t)(16384 * 16384 - y * y)); + uint32_t th = (uint32_t)(i * 25033u); /* the golden angle */ + x = rr * ck_cos(th) >> 14, z = rr * ck_sin(th) >> 14; + len = 16384 - 2950 + (int64_t)(ck_hash((int32_t)i, 1, 31) % 5900u); /* +-18%: a cloud, not a ball */ + } else { + uint32_t h1 = ck_hash((int32_t)i, 2, 31), h2 = ck_hash((int32_t)i, 3, 31); + y = 16384 - (int64_t)(h1 % 32768u); + rr = (int64_t)ck_isqrt((uint64_t)(16384 * 16384 - y * y)); + x = rr * ck_cos(h2) >> 14, z = rr * ck_sin(h2) >> 14; + len = 4915 + (int64_t)(ck_hash((int32_t)i, 4, 31) % 5734u); /* 0.30 .. 0.65 */ + } + m->home[i][0] = (int16_t)(x * len >> 14); + m->home[i][1] = (int16_t)(y * len >> 14); + m->home[i][2] = (int16_t)(z * len >> 14); + } + /* each point joined to its nearest two (the inner ones to three) */ + for (unsigned i = 0; i < CK_MIND_NODES; i++) { + unsigned want = i < outer ? 2 : 3; + for (unsigned w = 0; w < want; w++) { + int best = -1; + int64_t bd = 0; + for (unsigned j = 0; j < CK_MIND_NODES; j++) { + if (j == i || has_edge(m, i, j)) + continue; + int64_t d = dist2(m->home[i], m->home[j]); + if (best < 0 || d < bd) + best = (int)j, bd = d; + } + if (best >= 0 && m->ne < CK_MIND_EDGES) + m->ea[m->ne] = (uint8_t)i, m->eb[m->ne] = (uint8_t)best, m->ne++; + } + } +} + +void ck_mind_mode(ck_mind *m, int mode, uint32_t t) +{ + (void)t; + m->mode = mode; +} + +static void push(uint32_t *ring, uint32_t t) +{ + for (unsigned i = 3; i > 0; i--) + ring[i] = ring[i - 1]; + ring[0] = t ? t : 1; +} + +void ck_mind_word(ck_mind *m, uint32_t t) { push(m->words, t); } +void ck_mind_key(ck_mind *m, uint32_t t) { push(m->keys, t); } +void ck_mind_voice(ck_mind *m, uint32_t level) { m->voice = level > 256 ? 256 : level; } + +static void spark(ck_mind *m, unsigned from) +{ + if (m->nspark >= CK_MIND_SPARKS || !m->ne) + return; + /* a thread leaving `from`, or any thread when from is out of range */ + unsigned e = rnd(m) % m->ne, tries = 0; + if (from < CK_MIND_NODES) + while (m->ea[e] != from && m->eb[e] != from && tries++ < m->ne) + e = (e + 1) % m->ne; + unsigned s = m->nspark++; + m->spark[s].e = (uint16_t)e; + m->spark[s].back = (uint8_t)(from < CK_MIND_NODES ? m->eb[e] == from : rnd(m) & 1); + m->spark[s].t0 = m->t; + m->spark[s].dur = (uint16_t)(m->mode == CK_MIND_THINK ? 240 + rnd(m) % 260 : 420 + rnd(m) % 480); +} + +static uint32_t toward(uint32_t cur, uint32_t want, uint32_t dt, uint32_t ms) +{ + int64_t d = (int64_t)want - cur, step = d * (int64_t)(dt < ms ? dt : ms) / (int64_t)ms; + if (step == 0 && d && dt) + step = d > 0 ? 1 : -1; + return (uint32_t)((int64_t)cur + step); +} + +static uint32_t pulse(int32_t off, int32_t width) /* (1 - (off/width)^2)^2, 0..256 */ +{ + if (off <= -width || off >= width) + return 0; + int64_t q = 256 - (int64_t)off * off * 256 / ((int64_t)width * width); + return (uint32_t)(q * q >> 8); +} + +void ck_mind_at(ck_mind *m, uint32_t t) +{ + uint32_t dt = t > m->t ? t - m->t : 0; + if (dt > 250) + dt = 250; /* a long pause is not a jump */ + m->t = t; + m->was = m->box; + if (t < m->born) { + m->alpha = 0; + m->box = (ck_rect){0, 0, 0, 0}; + return; + } + static const uint32_t spins[4] = {349, 520, 1400, 600}, squeezes[4] = {0, 4, 16, 0}, hearts[4] = {50, 70, 120, 80}, + rates[4] = {2, 6, 25, 12}; + int md = m->mode & 3; + m->spin = toward(m->spin, spins[md], dt, 700); + m->squeeze = toward(m->squeeze, squeezes[md], dt, 500); + uint32_t want_heart = hearts[md] + (md == CK_MIND_SPEAK ? m->voice * 120 / 256 : 0); + if (md == CK_MIND_THINK) + want_heart += (uint32_t)(16384 + ck_sin(t * 65536u / 900u)) * 30 >> 15; + m->heart = toward(m->heart, want_heart, dt, md == CK_MIND_SPEAK ? 80 : 400); + m->angle += m->spin * dt; + + /* sparks: born at the mode's rate; each that arrives lights its point, and while thinking may go on */ + uint32_t form = (uint32_t)ck_prog(t, m->born, m->born + CK_MIND_FORM_MS); + if (form >= 192) { + m->spawn += rates[md] * dt; + while (m->spawn >= 1000) { + m->spawn -= 1000; + spark(m, CK_MIND_NODES); + } + } + for (unsigned i = 0; i < m->nspark;) { + uint32_t age = t - m->spark[i].t0; + if (age < m->spark[i].dur) { + i++; + continue; + } + unsigned e = m->spark[i].e, to = m->spark[i].back ? m->ea[e] : m->eb[e]; + m->act[to] = 256; + m->spark[i] = m->spark[--m->nspark]; + if (md == CK_MIND_THINK ? rnd(m) % 100 < 70 : rnd(m) % 100 < 18) + spark(m, to); + } + for (unsigned i = 0; i < CK_MIND_NODES; i++) + m->act[i] = (uint16_t)(m->act[i] * (uint32_t)ck_exp_neg(dt * 256 / 260) >> 16); + + /* the shape: breathing, drawn in while thinking, and while being born gathered in from far out */ + int64_t scale = 65536 + ((int64_t)ck_sin(t * 65536u / 5500u) * 1966 >> 14) - (int64_t)m->squeeze * 65536 / 256; + uint32_t gather = ck_ease_out((int32_t)form); + scale = scale * (256 + (int64_t)(256 - gather) * 560 / 256) >> 8; /* 3.2 times out at the start */ + uint32_t swirl = (256 - gather) * (256 - gather) >> 8; /* an extra spiral turn that unwinds as it gathers */ + m->alpha = ck_smooth((int32_t)form * 3); + uint32_t a = (m->angle >> 8) + swirl * 256; + int64_t ca = ck_cos(a), sa = ck_sin(a), ct = ck_cos(TILT), st = ck_sin(TILT); + int64_t R16 = (int64_t)m->R * 16; + int32_t x0 = m->cx * 16, x1 = x0, y0 = m->cy * 16, y1 = y0; + for (unsigned i = 0; i < CK_MIND_NODES; i++) { + int64_t x = m->home[i][0], y = m->home[i][1], z = m->home[i][2]; + int64_t rx = (x * ca - z * sa) >> 14, rz = (x * sa + z * ca) >> 14; /* turn about the upright axis */ + int64_t ry = (y * ct - rz * st) >> 14, fz = (y * st + rz * ct) >> 14; /* lean toward the viewer */ + int64_t persp = 16384 + fz * 3 / 16; /* nearer is a little larger */ + m->px[i] = (int32_t)(m->cx * 16 + 8 + (rx * persp >> 14) * R16 / 16384 * scale / 65536); + m->py[i] = (int32_t)(m->cy * 16 + 8 + (ry * persp >> 14) * R16 / 16384 * scale / 65536); + uint32_t nr = (uint32_t)((fz + 16384) * 256 / 32768); + m->near[i] = (uint16_t)(nr > 256 ? 256 : nr); + /* light from the pulses: words outward from the heart, keys upward from below */ + int64_t rad = (int64_t)ck_isqrt((uint64_t)(x * x + y * y + z * z)) * 256 / 16384; + uint32_t extra = 0; + for (unsigned w = 0; w < 4; w++) { + if (m->words[w] && t - m->words[w] < 900) { + uint32_t age = t - m->words[w]; + extra += pulse((int32_t)rad - (int32_t)(age * 300 / 600), 70) * (900 - age) / 900 * 150 >> 8; + } + if (m->keys[w] && t - m->keys[w] < 600) { + uint32_t age = t - m->keys[w]; + int32_t ky = 300 - (int32_t)(age * 600 / 500), ny = (int32_t)(y * 256 / 16384); + extra += pulse(ny - ky, 60) * (600 - age) / 600 * 90 >> 8; + } + } + uint32_t l = 34 + m->near[i] * m->near[i] / 256 * 180 / 256 + extra + m->act[i] * 120 / 256; + m->lum[i] = (uint16_t)(l > 256 ? 256 : l); + x0 = ck_min(x0, m->px[i]), x1 = ck_max(x1, m->px[i]); + y0 = ck_min(y0, m->py[i]), y1 = ck_max(y1, m->py[i]); + } + m->hx = m->cx * 16 + 8, m->hy = m->cy * 16 + 8; + m->hr = (int32_t)(R16 * 52 / 100 * scale / 65536); + int32_t halo = (int32_t)(R16 * 17 / 10 * ck_min((int32_t)(scale >> 8), 256) / 256); + int32_t pad = S(8) * 16; + x0 = ck_min(x0 - pad, m->hx - halo), x1 = ck_max(x1 + pad, m->hx + halo); + y0 = ck_min(y0 - pad, m->hy - halo), y1 = ck_max(y1 + pad, m->hy + halo); + m->box = (ck_rect){(x0 >> 4) - 1, (y0 >> 4) - 1, ((x1 - x0) >> 4) + 3, ((y1 - y0) >> 4) + 3}; +} + +ck_rect ck_mind_dirty(const ck_mind *m) { return ck_union(m->was, m->box); } + +void ck_mind_draw(const ck_mind *m, ck_canvas *out, const ck_rect *r) +{ + if (!m->alpha || !ck_meets(m->box, r)) + return; + uint32_t A = m->alpha, form = (uint32_t)ck_prog(m->t, m->born, m->born + CK_MIND_FORM_MS); + int64_t R16 = (int64_t)m->R * 16; + /* the halo: a faint blue light round the whole mind, swelling a little with the heart */ + ck_glow(out, r, m->hx, m->hy, (int32_t)(R16 * 17 / 10), CK_RGB(60, 74, 210), (52 + m->heart / 8) * A >> 8); + ck_glow(out, r, m->hx, m->hy, (int32_t)R16, CK_RGB(112, 92, 255), (30 + m->heart / 8) * A >> 8); + /* the threads, fading in once the points have mostly gathered */ + uint32_t ta = ck_smooth(((int32_t)form - 128) * 2) * A >> 8; + if (ta) + for (unsigned i = 0; i < m->ne; i++) { + unsigned a = m->ea[i], b = m->eb[i]; + uint32_t a0 = (m->lum[a] * (16u + m->near[a] * 60u / 256u) >> 8) * ta >> 8, + a1 = (m->lum[b] * (16u + m->near[b] * 60u / 256u) >> 8) * ta >> 8; + ck_thread(out, r, m->px[a], m->py[a], m->px[b], m->py[b], CK_RGB(120, 140, 255), a0, a1); + if (m->k > 320) /* a second strand on big screens, so the thread keeps its weight */ + ck_thread(out, r, m->px[a], m->py[a] + 16, m->px[b], m->py[b] + 16, CK_RGB(120, 140, 255), a0 / 2, + a1 / 2); + } + /* the points: pale blue-white, warming as they light */ + for (unsigned i = 0; i < CK_MIND_NODES; i++) { + int32_t rad = (int32_t)((int64_t)S(3) * 16 * (160 + m->near[i] * 120 / 256) >> 8); + uint32_t c = ck_mix(CK_RGB(206, 222, 255), CK_RGB(255, 214, 160), m->act[i]); + ck_glow(out, r, m->px[i], m->py[i], rad * 3, c, (m->lum[i] * 50 >> 8) * A >> 8); + ck_glow(out, r, m->px[i], m->py[i], rad, c, m->lum[i] * A >> 8); + } + /* the sparks, each with a short fading tail */ + for (unsigned i = 0; i < m->nspark; i++) { + unsigned e = m->spark[i].e, a = m->ea[e], b = m->eb[e]; + if (m->spark[i].back) + a = m->eb[e], b = m->ea[e]; + int32_t f = (int32_t)((m->t - m->spark[i].t0) * 256u / m->spark[i].dur); + for (int k = 0; k < 3; k++) { + int32_t g = ck_clamp(f - k * 22, 0, 256); + int32_t x = m->px[a] + (int32_t)((int64_t)(m->px[b] - m->px[a]) * g >> 8); + int32_t y = m->py[a] + (int32_t)((int64_t)(m->py[b] - m->py[a]) * g >> 8); + ck_glow(out, r, x, y, S(5) * 16 - k * S(1) * 16, CK_RGB(255, 222, 176), (200 >> k) * A >> 8); + } + } + /* the heart: a warm light at the centre, and a small bright core */ + ck_glow(out, r, m->hx, m->hy, m->hr, CK_RGB(255, 210, 170), m->heart * 7 / 10 * A >> 8); + ck_glow(out, r, m->hx, m->hy, m->hr * 2 / 5, CK_RGB(255, 236, 214), (90 + m->heart) * A >> 8); + ck_glow(out, r, m->hx, m->hy, m->hr / 8, CK_RGB(255, 250, 240), 230 * A >> 8); +} diff --git a/native/kernel/ui/mind.h b/native/kernel/ui/mind.h new file mode 100644 index 00000000..ad99036e --- /dev/null +++ b/native/kernel/ui/mind.h @@ -0,0 +1,76 @@ +/* mind.h -- Allen's presence: no face and no body, a mind drawn as light. + * + * About a hundred points of light sit on and inside a sphere, joined by fine + * threads into a network, turning slowly in three dimensions round a warm + * heart. Small sparks run along the threads from point to point; each one + * that arrives lights its point for a moment. How it moves is how Allen is: + * idle it breathes (a slow swell) and turns slowly; a few sparks. + * listening each key typed sends a soft wave of light up through it. + * thinking it draws in a little, turns faster, the heart brightens and + * sparks cascade through the whole network. + * speaking every word sends a pulse out from the heart, and the heart + * follows the voice. + * It is born from the light of the black holes' merger: the points start + * scattered wide and gather, spiralling, into the network. + * + * Integer only, freestanding. ck_mind_at moves it to a time (one caller); + * ck_mind_draw then only reads, so several processor cores can draw + * different parts of the screen at once. Host tested in + * ui/tests/allen_ui_test.c. */ +#ifndef AIENOS_MIND_H +#define AIENOS_MIND_H +#include +#include + +#include "paint.h" + +#define CK_MIND_NODES 120u +#define CK_MIND_EDGES 300u +#define CK_MIND_SPARKS 64u +#define CK_MIND_FORM_MS 3000u /* from born to fully gathered */ + +enum { CK_MIND_IDLE, CK_MIND_LISTEN, CK_MIND_THINK, CK_MIND_SPEAK }; + +typedef struct { + /* the shape, fixed at init */ + int32_t cx, cy, R; /* px */ + uint32_t k; + int16_t home[CK_MIND_NODES][3]; /* unit sphere, Q14 */ + uint8_t ea[CK_MIND_EDGES], eb[CK_MIND_EDGES]; + unsigned ne; + uint32_t born; /* ms */ + /* how it is, moved on by ck_mind_at */ + uint32_t t, rng, spawn; + int mode; + uint32_t angle; /* the turn so far, 1/256 of a 65536th */ + uint32_t spin, squeeze; /* eased toward the mode's: per-ms turn (same units), and 0..256 drawn in */ + uint32_t heart, voice; /* 0..256 */ + uint32_t words[4], keys[4]; /* when the last pulses began (ms; 0 none) */ + uint16_t act[CK_MIND_NODES]; /* how lit each point is, 0..256 */ + struct { + uint16_t e, dur; + uint8_t back; /* runs eb to ea */ + uint32_t t0; + } spark[CK_MIND_SPARKS]; + unsigned nspark; + /* the frame, worked out by ck_mind_at for ck_mind_draw */ + int32_t px[CK_MIND_NODES], py[CK_MIND_NODES]; /* 16ths of a pixel */ + uint16_t lum[CK_MIND_NODES], near[CK_MIND_NODES]; /* brightness 0..256; nearness 0..256 */ + uint32_t alpha; /* the whole figure, 0..256 */ + int32_t hx, hy, hr; /* the heart: 16ths of a pixel */ + ck_rect box, was; /* where it is now, and was the frame before */ +} ck_mind; + +/* (cx, cy) its centre, px; k the scale (1/256 px per design px); born the + * time it starts to gather (ms). */ +void ck_mind_init(ck_mind *m, int32_t cx, int32_t cy, uint32_t k, uint32_t born); +void ck_mind_mode(ck_mind *m, int mode, uint32_t t); +void ck_mind_word(ck_mind *m, uint32_t t); /* a word was spoken */ +void ck_mind_key(ck_mind *m, uint32_t t); /* a key was typed */ +void ck_mind_voice(ck_mind *m, uint32_t level); /* 0..256 */ +void ck_mind_at(ck_mind *m, uint32_t t); +/* The figure into the part r of out (light added). */ +void ck_mind_draw(const ck_mind *m, ck_canvas *out, const ck_rect *r); +/* What needs redrawing for this frame: where it was and where it is. */ +ck_rect ck_mind_dirty(const ck_mind *m); +#endif diff --git a/native/kernel/ui/night.c b/native/kernel/ui/night.c new file mode 100644 index 00000000..3cbba2a0 --- /dev/null +++ b/native/kernel/ui/night.c @@ -0,0 +1,664 @@ +/* night.c -- the night sky and the merging black holes; see night.h. + * + * The sky is worked out at a quarter of the screen's resolution for the + * soft parts (the Milky Way, dust and nebulae: smooth anyway), scaled up + * with a 4 x 4 ordered dither so the faint gradients show no bands, and the + * stars and galaxies are then drawn at full resolution on top. + * + * Bent light: a point mass moves the image of a star seen at angle theta + * from it to where the star really is, beta = theta - E^2 / theta (E the + * Einstein radius). Each pixel shows the sky at its own beta (with both + * holes' pulls added), so stars behind a hole stretch into arcs round it and + * a second, inner image appears on the far side. The pull is eased to zero + * between 2.2 E and 4.4 E so the bent region has no edge. It is worked out + * exactly near the holes and on an 8-pixel grid (and interpolated) further + * out, where it is smooth. The ripple adds a displacement along the radius + * that stretches one way and squeezes the other (cos 2 theta), the pattern + * a gravitational wave makes. */ +#include "night.h" + +#define S(v) ((int32_t)(((int64_t)(v) * (int64_t)n->k + 128) / 256)) +#define Q30 (1ull << 30) + +/* ---- the galaxies ---- */ + +enum { SPIRAL, ROUND, EDGE }; +static const struct { + uint16_t fx, fy; /* thousandths of the width and height */ + uint16_t radius; /* design px */ + int16_t tilt, turn; /* degrees: how far it leans from face-on, and the angle of its long axis */ + uint8_t kind, bright; + uint32_t tint; + uint16_t period; +} gdef[CK_NIGHT_GALAXIES] = { + {150, 205, 112, 38, 30, SPIRAL, 160, CK_RGB(190, 205, 255), 3400}, + {805, 135, 76, 62, -25, SPIRAL, 140, CK_RGB(200, 212, 255), 2900}, + {265, 705, 42, 45, 60, ROUND, 130, CK_RGB(255, 228, 196), 2600}, + {870, 750, 88, 84, 15, EDGE, 150, CK_RGB(210, 216, 255), 3800}, + {60, 545, 40, 22, 0, SPIRAL, 120, CK_RGB(190, 205, 255), 3100}, + {600, 95, 28, 52, 70, SPIRAL, 110, CK_RGB(200, 212, 255), 2700}, +}; + +static uint8_t band_t[256]; /* the sweeping band: ((1 + cos) / 2)^6, 0..255 */ + +static int32_t half_box(uint32_t k, unsigned i) { return (int32_t)((gdef[i].radius * 13 / 10 * k + 128) / 256) + 1; } + +static void galaxy_box(uint32_t w, uint32_t h, uint32_t k, unsigned i, ck_rect *b) +{ + int32_t hb = half_box(k, i), gx = (int32_t)(w * gdef[i].fx / 1000), gy = (int32_t)(h * gdef[i].fy / 1000); + ck_rect all = {0, 0, (int32_t)w, (int32_t)h}; + *b = (ck_rect){gx - hb, gy - hb, 2 * hb + 1, 2 * hb + 1}; + if (!ck_clip(b, &all)) + *b = (ck_rect){0, 0, 0, 0}; +} + +size_t ck_night_mem_bytes(uint32_t w, uint32_t h, uint32_t k) +{ + size_t n = (size_t)w * h * 4 + (size_t)(w / 4 + 1) * (h / 4 + 1) + 64; + for (unsigned i = 0; i < CK_NIGHT_GALAXIES; i++) { + ck_rect b; + galaxy_box(w, h, k, i, &b); + n += (size_t)b.w * (size_t)b.h * 2; + } + return n; +} + +/* ---- the Milky Way's geometry, shared by the clouds and the stars ---- */ + +struct band { + int64_t x0, y0, dx, dy, len, half; +}; + +static struct band band_of(const ck_night *n) +{ + struct band b = {-(int64_t)n->w / 20, (int64_t)n->h * 90 / 100, (int64_t)n->w * 110 / 100, + -(int64_t)n->h * 92 / 100, 0, (int64_t)n->h * 16 / 100}; + b.len = (int64_t)ck_isqrt((uint64_t)(b.dx * b.dx + b.dy * b.dy)); + return b; +} + +/* signed distance across the band and distance along it, px */ +static void band_at(const struct band *b, int64_t x, int64_t y, int64_t *across, int64_t *along) +{ + *across = ((x - b->x0) * b->dy - (y - b->y0) * b->dx) / b->len; + *along = ((x - b->x0) * b->dx + (y - b->y0) * b->dy) / b->len; +} + +static uint32_t gauss(int64_t v, int64_t width) /* exp(-(v/width)^2), Q16 */ +{ + int64_t q = v * 256 / (width ? width : 1); + if (q > 4095 || q < -4095) + return 0; + return ck_exp_neg((uint32_t)(q * q >> 8)); +} + +/* ---- the soft layer: a quarter of the resolution, 16ths of a level ---- */ + +static void clouds(ck_night *n, uint16_t *q, int32_t qw, int32_t qh) +{ + struct band b = band_of(n); + int64_t H = n->h; + for (int32_t qy = 0; qy < qh; qy++) + for (int32_t qx = 0; qx < qw; qx++) { + int64_t x = (int64_t)qx * 4, y = (int64_t)qy * 4, across, along; + band_at(&b, x, y, &across, &along); + int32_t u3 = (int32_t)(x * 768 / H), v3 = (int32_t)(y * 768 / H); + uint64_t core = gauss(across, b.half), wide = gauss(across, b.half * 2); + uint64_t n1 = ck_fbm(u3, v3, 101, 5); + uint64_t n2 = ck_fbm((int32_t)(x * 1792 / H), (int32_t)(y * 1792 / H), 202, 4); + /* dark dust: a lane just off the middle of the band, broken up by noise */ + uint64_t lane = gauss(across - H * 2 / 100, H * 5 / 100); + uint64_t dust = lane * ck_smooth((int32_t)(((int64_t)n2 - 22000) * 256 / 26000)) >> 8; + uint64_t bright = gauss(along - b.len * 40 / 100, b.len * 38 / 100); + uint64_t mw = core * (32768 + n1 / 2) >> 16; + mw = mw * (65536 - dust * 52428 / 65536) >> 16; + mw = mw * (29491 + bright * 36045 / 65536) >> 16; + uint64_t halo = wide * (39321 + n1 * 26214 / 65536) >> 16; + /* nebulae: faint violet, blue and rose clouds where the noise runs high */ + uint32_t n4 = ck_fbm((int32_t)(x * 512 / H), (int32_t)(y * 512 / H), 404, 4); + uint32_t n5 = ck_fbm((int32_t)(x * 666 / H), (int32_t)(y * 666 / H), 505, 4); + uint32_t n6 = ck_fbm((int32_t)(x * 1024 / H), (int32_t)(y * 1024 / H), 606, 4); + uint64_t vi = ck_smooth((int32_t)(((int64_t)n4 - 36000) * 256 / 29535)); + uint64_t bl = ck_smooth((int32_t)(((int64_t)n5 - 35000) * 256 / 30535)); + uint64_t ro = (uint64_t)ck_smooth((int32_t)(((int64_t)n6 - 33000) * 256 / 32535)) * wide >> 16; + vi = vi * vi >> 8, bl = bl * bl >> 8; + /* level x 16 per channel */ + int64_t top = 256 - y * 256 / H; + int64_t r = 26 + top / 32 + (int64_t)(mw * 44 * 16 >> 16) + (int64_t)(halo * 6 * 16 >> 16) + + (int64_t)(vi * 22 * 16 >> 8) + (int64_t)(bl * 5 * 16 >> 8) + (int64_t)(ro * 22 * 16 >> 8); + int64_t g = 34 + top / 32 + (int64_t)(mw * 40 * 16 >> 16) + (int64_t)(halo * 8 * 16 >> 16) + + (int64_t)(vi * 8 * 16 >> 8) + (int64_t)(bl * 12 * 16 >> 8) + (int64_t)(ro * 7 * 16 >> 8); + int64_t bb = 92 + top / 16 + (int64_t)(mw * 46 * 16 >> 16) + (int64_t)(halo * 16 * 16 >> 16) + + (int64_t)(vi * 28 * 16 >> 8) + (int64_t)(bl * 30 * 16 >> 8) + (int64_t)(ro * 15 * 16 >> 8); + uint16_t *c = q + ((size_t)qy * (size_t)qw + (size_t)qx) * 3; + c[0] = (uint16_t)ck_clamp((int32_t)r, 0, 4080); + c[1] = (uint16_t)ck_clamp((int32_t)g, 0, 4080); + c[2] = (uint16_t)ck_clamp((int32_t)bb, 0, 4080); + } +} + +static void scale_up(ck_night *n, const uint16_t *q, int32_t qw) +{ + static const uint8_t bayer[16] = {0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5}; + for (int32_t y = 0; y < n->h; y++) { + int32_t qy = y >> 2, fy = y & 3; + const uint16_t *r0 = q + (size_t)qy * (size_t)qw * 3, *r1 = r0 + (size_t)qw * 3; + uint32_t *row = n->sky + (size_t)y * (size_t)n->w; + for (int32_t x = 0; x < n->w; x++) { + int32_t qx = x >> 2, fx = x & 3; + uint32_t d = bayer[(y & 3) * 4 + (x & 3)], c = 0; + for (int k = 0; k < 3; k++) { + uint32_t a = r0[qx * 3 + k] * (uint32_t)(4 - fx) + r0[qx * 3 + 3 + k] * (uint32_t)fx; + uint32_t b = r1[qx * 3 + k] * (uint32_t)(4 - fx) + r1[qx * 3 + 3 + k] * (uint32_t)fx; + uint32_t v = ((a * (uint32_t)(4 - fy) + b * (uint32_t)fy) / 16 + d) >> 4; + c = c << 8 | (v > 255 ? 255u : v); + } + row[x] = c; + } + } +} + +/* ---- stars ---- */ + +static uint32_t star_color(uint32_t h) +{ + uint32_t p = h % 100; + return p < 10 ? CK_RGB(170, 192, 255) : p < 55 ? CK_RGB(218, 228, 255) : p < 85 ? CK_RGB(255, 250, 242) + : p < 97 ? CK_RGB(255, 234, 196) : CK_RGB(255, 204, 160); +} + +static void stars(ck_night *n) +{ + ck_canvas cv = {n->sky, n->w, n->h}; + ck_rect all = {0, 0, n->w, n->h}; + struct band b = band_of(n); + uint32_t k = n->k, area = (uint32_t)n->w * (uint32_t)n->h; + /* field stars: many faint, few bright; more of them along the band */ + for (uint32_t i = 0; i < area / 800; i++) { + int32_t x = (int32_t)(ck_hash((int32_t)i, 1, 77) % (uint32_t)(n->w * 16)); + int32_t y = (int32_t)(ck_hash((int32_t)i, 2, 77) % (uint32_t)(n->h * 16)); + int64_t across, along; + band_at(&b, x >> 4, y >> 4, &across, &along); + if ((ck_hash((int32_t)i, 3, 77) & 65535u) > 36000u + gauss(across, b.half) * 29535u / 65536u) + continue; + uint64_t u = ck_hash((int32_t)i, 4, 77) & 255u; + uint32_t lv = 14u + (uint32_t)(241u * (u * u * u * u) >> 32); + int32_t r = (int32_t)((20u + 16u * lv / 255u) * k / 256u); + ck_glow(&cv, &all, x, y, r, star_color(ck_hash((int32_t)i, 5, 77)), lv); + } + /* star dust in the band: faint points where it is densest */ + for (uint32_t i = 0; i < area / 170; i++) { + int32_t x = (int32_t)(ck_hash((int32_t)i, 6, 78) % (uint32_t)(n->w * 16)); + int32_t y = (int32_t)(ck_hash((int32_t)i, 7, 78) % (uint32_t)(n->h * 16)); + int64_t across, along; + band_at(&b, x >> 4, y >> 4, &across, &along); + uint64_t c = gauss(across, b.half * 8 / 10); + if ((ck_hash((int32_t)i, 8, 78) & 65535u) > (c * c >> 16)) + continue; + ck_glow(&cv, &all, x, y, (int32_t)(20u * k / 256u), CK_RGB(226, 230, 255), + 10u + ck_hash((int32_t)i, 9, 78) % 44u); + } + /* the bright stars: a soft halo each; these twinkle */ + uint32_t nb = area / 50000u; + nb = nb < 24 ? 24 : nb > CK_NIGHT_TWINKLES ? CK_NIGHT_TWINKLES : nb; + for (uint32_t i = 0; i < nb; i++) { + ck_night_star *s = &n->tw[n->ntw++]; + s->x = (int32_t)(ck_hash((int32_t)i, 1, 91) % (uint32_t)(n->w * 16)); + s->y = (int32_t)(ck_hash((int32_t)i, 2, 91) % (uint32_t)(n->h * 16)); + s->color = star_color(ck_hash((int32_t)i, 3, 91) | 1u); + uint32_t lv = 190u + ck_hash((int32_t)i, 4, 91) % 66u; + int32_t r = (int32_t)(34u * k / 256u); + ck_glow(&cv, &all, s->x, s->y, r, s->color, lv); + ck_glow(&cv, &all, s->x, s->y, r * 5, s->color, 22); + s->r = r * 2; + s->period = (uint16_t)(2600u + ck_hash((int32_t)i, 5, 91) % 4200u); + s->phase = (uint16_t)(ck_hash((int32_t)i, 6, 91) % s->period); + } +} + +/* ---- galaxies: light added to the sky, and the maps the sweep follows ---- */ + +static void galaxy(ck_night *n, unsigned i, uint8_t **pool) +{ + ck_night_galaxy *g = &n->gal[i]; + galaxy_box((uint32_t)n->w, (uint32_t)n->h, n->k, i, &g->box); + g->light = *pool; + g->phase = *pool + (size_t)g->box.w * (size_t)g->box.h; + *pool += (size_t)g->box.w * (size_t)g->box.h * 2; + g->tint = gdef[i].tint; + g->period = gdef[i].period; + int64_t gx = (int64_t)n->w * gdef[i].fx / 1000 * 16 + 8, gy = (int64_t)n->h * gdef[i].fy / 1000 * 16 + 8; + int64_t rg = (int64_t)S(gdef[i].radius) * 16; + uint32_t turn = (uint32_t)((int32_t)gdef[i].turn * 65536 / 360); + int64_t ct = ck_cos(turn), st = ck_sin(turn), ci = ck_cos((uint32_t)(gdef[i].tilt * 65536 / 360)); + if (ci < 600) + ci = 600; + uint32_t kind = gdef[i].kind, bright = gdef[i].bright; + for (int32_t y = g->box.y; y < g->box.y + g->box.h; y++) + for (int32_t x = g->box.x; x < g->box.x + g->box.w; x++) { + size_t at = (size_t)(y - g->box.y) * (size_t)g->box.w + (size_t)(x - g->box.x); + int64_t dx = (int64_t)x * 16 + 8 - gx, dy = (int64_t)y * 16 + 8 - gy; + int64_t u = (dx * ct + dy * st) >> 14, v = (dy * ct - dx * st) >> 14; + int64_t vd = v * 16384 / ci; /* back to face-on */ + int64_t rq = (int64_t)ck_isqrt((uint64_t)(u * u + vd * vd)) * 256 / rg; /* radius, 256 = the galaxy's */ + g->light[at] = 0; + g->phase[at] = 0; + if (rq > 330) + continue; + uint32_t th = ck_atan2((int32_t)vd, (int32_t)u); + uint32_t nz = ck_fbm((int32_t)(u * 1536 / rg), (int32_t)(vd * 1536 / rg), 700 + i, 3); + uint32_t fine = ck_fbm((int32_t)(u * 5120 / rg), (int32_t)(vd * 5120 / rg), 750 + i, 2); + /* the bulge is rounder than the disc: flattened only half as much */ + int64_t vb = v * 32768 / (16384 + ci), rb = (int64_t)ck_isqrt((uint64_t)(u * u + vb * vb)) * 256 / rg; + int64_t lb, ld, knot = 0; /* bulge and disc light, Q16 of full */ + uint32_t ph; + if (kind == ROUND) { + lb = (int64_t)gauss(rb, 30) * 8 / 10; + ld = (int64_t)ck_exp_neg((uint32_t)(rb * 1075 / 256)) * 6 / 10; + ph = (uint32_t)(rb * 512); + } else { + int64_t lr = (int64_t)ck_log2_q16((uint64_t)(rq < 4 ? 4 : rq)) - 8 * 65536; /* log2(r) */ + ph = (uint32_t)(2 * th + (uint32_t)(lr * 30000 >> 16)); /* two arms, wound about a turn and a half */ + int64_t arm = (16384 + ck_cos(ph)) >> 1; + arm = arm * arm >> 14; /* Q14 */ + /* the arms begin outside the core; inside it the light is even */ + int64_t from = ck_smooth((int32_t)(rq - 34) * 256 / 90); + arm = 16384 - ((16384 - arm) * from >> 8); + int64_t clump = 32768 + (int64_t)nz * 22000 / 65536 + (int64_t)fine * 10768 / 65536; + lb = (int64_t)gauss(rb, 58) * 9 / 10; + ld = (int64_t)ck_exp_neg((uint32_t)(rq * 12 / 5)) * (8192 + (arm * 57344 >> 14) * clump / 65536) >> 16; + if (arm > 11468 && nz > 44000 && rq > 50) + knot = ld * (int64_t)(nz - 44000) / 21535; + if (kind == EDGE) { /* the dust lane along the middle of a disc seen edge-on */ + int64_t lane = gauss(v, rg * 5 / 100); + if (rq < 240) + ld = ld * (65536 - lane * 56000 / 65536) >> 16, lb = lb * (65536 - lane * 40000 / 65536) >> 16; + ph = (uint32_t)(u * 32768 / rg); + } + } + /* a soft edge at 1.3 radii */ + int64_t edge = 65536 - (int64_t)ck_smooth((int32_t)(rq - 250) * 256 / 80) * 256; + lb = lb * edge >> 16, ld = ld * edge >> 16, knot = knot * edge >> 16; + uint32_t ab = (uint32_t)(lb * bright >> 16), ad = (uint32_t)(ld * bright >> 16), + ak = (uint32_t)(knot * bright >> 16); + uint32_t *p = n->sky + (size_t)y * (size_t)n->w + x; + *p = ck_add(*p, CK_RGB(255, 222, 178), ab); + *p = ck_add(*p, CK_RGB(150, 170, 255), ad); + *p = ck_add(*p, CK_RGB(255, 140, 190), ak / 2); + uint32_t l = ab + ad; + g->light[at] = (uint8_t)(l > 255 ? 255 : l); + g->phase[at] = (uint8_t)(ph >> 8); + } +} + +/* ---- coming out of the dark ---- */ + +static void appear_map(ck_night *n) +{ + int32_t ah = n->h / 4 + 1; + int64_t far = 0; + int32_t cs[4][2] = {{0, 0}, {n->w, 0}, {0, n->h}, {n->w, n->h}}; + for (int i = 0; i < 4; i++) { + int64_t dx = cs[i][0] - n->cx, dy = cs[i][1] - n->cy, d = (int64_t)ck_isqrt((uint64_t)(dx * dx + dy * dy)); + far = d > far ? d : far; + } + for (int32_t y = 0; y < ah; y++) + for (int32_t x = 0; x < n->aw; x++) { + int64_t px = (int64_t)x * 4, py = (int64_t)y * 4, dx = px - n->cx, dy = py - n->cy; + uint32_t a = ck_fbm((int32_t)(px * 640 / n->h), (int32_t)(py * 640 / n->h), 909, 4) >> 8; + uint32_t r = (uint32_t)((int64_t)ck_isqrt((uint64_t)(dx * dx + dy * dy)) * 255 / (far ? far : 1)); + n->appear[(size_t)y * (size_t)n->aw + (size_t)x] = (uint8_t)((a * 6 + r * 4) / 10); + } +} + +uint32_t ck_night_faded(const ck_night *n, int32_t x, int32_t y, uint32_t l) +{ + if (n->t >= CK_NIGHT_FADE_END_MS) + return 256; + x = ck_clamp(x, 0, n->w - 1), y = ck_clamp(y, 0, n->h - 1); + int32_t from = 300 + n->appear[(size_t)(y >> 2) * (size_t)n->aw + (size_t)(x >> 2)] * 12 + (int32_t)(255 - l) * 8; + int32_t dt = (int32_t)n->t - from; + return dt <= 0 ? 0 : dt >= 1365 ? 256 : ck_smooth(dt * 48 >> 8); +} + +static uint32_t fade_px(const ck_night *n, uint32_t c, int32_t x, int32_t y) +{ + uint32_t r = c >> 16 & 255, g = c >> 8 & 255, b = c & 255, l = r > g ? r : g; + l = l > b ? l : b; + uint32_t f = ck_night_faded(n, x, y, l); + return f >= 256 ? c : ck_scale(c, f); +} + +int ck_night_init(ck_night *n, uint32_t w, uint32_t h, uint32_t k, int32_t cx, int32_t cy, void *mem, size_t len, + void *scratch) +{ + if (!mem || !scratch || w < 64 || h < 64 || len < ck_night_mem_bytes(w, h, k)) + return -1; + (void)ck_sin(0); /* the tables, before anything else could ask for them */ + for (unsigned i = 0; i < 256; i++) { + uint64_t c = (uint64_t)(16384 + ck_cos(i * 256u)) >> 1; /* Q14 */ + uint64_t c2 = c * c >> 14, c6 = (c2 * c2 >> 14) * c2 >> 14; + band_t[i] = (uint8_t)(c6 * 255 >> 14); + } + *n = (ck_night){0}; + n->w = (int32_t)w, n->h = (int32_t)h, n->k = k, n->cx = cx, n->cy = cy; + uint8_t *p = mem; + n->sky = (uint32_t *)p; + p += (size_t)w * h * 4; + n->appear = p; + n->aw = (int32_t)(w / 4 + 1); + p += (size_t)(w / 4 + 1) * (h / 4 + 1); + int32_t qw = (int32_t)(w / 4 + 2), qh = (int32_t)(h / 4 + 2); + clouds(n, scratch, qw, qh); + scale_up(n, scratch, qw); + stars(n); + for (unsigned i = 0; i < CK_NIGHT_GALAXIES; i++) + galaxy(n, i, &p); + appear_map(n); + ck_night_at(n, 0); + return 0; +} + +/* ---- the black holes and the ripple at a time ---- */ + +static uint64_t root8(uint64_t l) /* l^(1/8), Q30 */ +{ + for (int i = 0; i < 3; i++) + l = ck_isqrt(l << 30); + return l; +} + +#define ORBIT_MS 5200u /* one turn of the wide orbit */ + +static uint32_t orbit_angle(uint32_t t, int32_t *sep16, int32_t a0) +{ + uint32_t spiral_from = (CK_NIGHT_SPIRAL_MS - CK_NIGHT_HOLES_MS) * 65536u / ORBIT_MS; + if (t < CK_NIGHT_SPIRAL_MS) { + *sep16 = a0; + return (t - CK_NIGHT_HOLES_MS) * 65536u / ORBIT_MS; + } + uint64_t left = ((uint64_t)(CK_NIGHT_MERGE_MS - t) << 30) / (CK_NIGHT_MERGE_MS - CK_NIGHT_SPIRAL_MS); + uint64_t r = root8(left), r2 = r * r >> 30, r5 = (r2 * r2 >> 30) * r >> 30; + *sep16 = (int32_t)((uint64_t)a0 * r2 >> 30); + /* the spiral's angle carries on at the wide orbit's speed: K (1 - L^(5/8)), K = 8/5 x its turns */ + uint64_t turns = (uint64_t)65536 * 8 * (CK_NIGHT_MERGE_MS - CK_NIGHT_SPIRAL_MS) / (5ull * ORBIT_MS); + return spiral_from + (uint32_t)(turns * (Q30 - r5) >> 30); +} + +void ck_night_at(ck_night *n, uint32_t t) +{ + n->t = t; + n->holes = 0; + n->lens = (ck_rect){0, 0, 0, 0}; + n->ripple_w = 0; + int32_t e_full = S(60) * 16, rs_full = S(20) * 16, a0 = S(270) * 16; + int32_t cx = n->cx * 16 + 8, cy = n->cy * 16 + 8; + int32_t sep; + uint32_t last = orbit_angle(CK_NIGHT_MERGE_MS - 1, &sep, a0); + if (t >= CK_NIGHT_HOLES_MS && t < CK_NIGHT_MERGE_MS) { + uint32_t ang = orbit_angle(t, &sep, a0); + int32_t e = (int32_t)((int64_t)e_full * ck_smooth(ck_prog(t, CK_NIGHT_HOLES_MS, CK_NIGHT_HOLES_MS + 2600)) >> 8); + int32_t rs = (int32_t)((int64_t)rs_full * + ck_smooth(ck_prog(t, CK_NIGHT_HOLES_MS + 1400, CK_NIGHT_HOLES_MS + 3400)) >> 8); + int32_t hx = (int32_t)((int64_t)(sep / 2) * ck_cos(ang) >> 14); + int32_t hy = (int32_t)((int64_t)(sep / 2) * ck_sin(ang) >> 15); /* the orbit leans away: half as tall */ + n->hole[0] = (__typeof__(n->hole[0])){cx + hx, cy + hy, e, rs}; + n->hole[1] = (__typeof__(n->hole[1])){cx - hx, cy - hy, e, rs}; + n->holes = 2; + } else if (t >= CK_NIGHT_MERGE_MS && t < CK_NIGHT_GONE_MS) { + uint32_t tm = t - CK_NIGHT_MERGE_MS; + int32_t e = e_full * 362 / 256, rs0 = rs_full * 323 / 256, rs1 = rs_full * 2; + int32_t rs = rs0 + (int32_t)((int64_t)(rs1 - rs0) * ck_smooth(ck_prog(tm, 0, 180)) >> 8); + /* it rings: a quick wobble that dies away */ + int64_t wob = (int64_t)ck_sin(tm * 65536u / 95u) * ck_exp_neg(tm * 256u / 260u) >> 16; + rs += (int32_t)(rs * wob * 7 / 100 >> 14); + uint32_t keep = 256 - ck_smooth(ck_prog(t, CK_NIGHT_MERGE_MS + 900, CK_NIGHT_GONE_MS)); + n->hole[0] = (__typeof__(n->hole[0])){cx, cy, (int32_t)((int64_t)e * keep >> 8), + (int32_t)((int64_t)rs * (keep * keep >> 8) >> 8)}; + n->holes = 1; + } + for (unsigned i = 0; i < n->holes; i++) { + int32_t reach = (n->hole[i].e * 44 / 10 >> 4) + 2; + if (n->hole[i].e <= 0 && n->hole[i].rs <= 0) + continue; + reach = ck_max(reach, (n->hole[i].rs * 16 / 10 >> 4) + 2); + ck_rect b = {(n->hole[i].x >> 4) - reach, (n->hole[i].y >> 4) - reach, 2 * reach + 1, 2 * reach + 1}; + n->lens = ck_union(n->lens, b); + } + ck_rect all = {0, 0, n->w, n->h}; + if (n->lens.w && !ck_clip(&n->lens, &all)) + n->lens = (ck_rect){0, 0, 0, 0}; + if (t >= CK_NIGHT_MERGE_MS && t < CK_NIGHT_MERGE_MS + CK_NIGHT_RIPPLE_MS) { + uint32_t tr = t - CK_NIGHT_MERGE_MS; + int32_t w = ck_clamp(S(60), 4, 200), reach = w * 22 / 10; + int64_t far = 0; + int32_t cs[4][2] = {{0, 0}, {n->w, 0}, {0, n->h}, {n->w, n->h}}; + for (int i = 0; i < 4; i++) { + int64_t dx = cs[i][0] - n->cx, dy = cs[i][1] - n->cy, d = (int64_t)ck_isqrt((uint64_t)(dx * dx + dy * dy)); + far = d > far ? d : far; + } + far += reach; + n->ripple_r = (int32_t)(far * tr / CK_NIGHT_RIPPLE_MS); + n->ripple_w = w; + uint32_t env = ck_smooth(ck_prog(tr, 0, 220)) * + (256 - ck_smooth(ck_prog(tr, CK_NIGHT_RIPPLE_MS * 6 / 10, CK_NIGHT_RIPPLE_MS))) >> 8; + int64_t amp = (int64_t)S(6) * 16 * (256 - 150 * n->ripple_r / far) >> 8; + amp = amp * env >> 8; + int32_t lambda = ck_max(S(110), 8); + for (int32_t i = 0; i <= 2 * reach && i < 1024; i++) { + int32_t o = i - reach; + int64_t s = ck_sin((uint32_t)((int64_t)o * 65536 / lambda)); + n->ripple_disp[i] = (int32_t)((amp * s >> 14) * gauss(o, w) >> 16); + n->ripple_light[i] = (uint8_t)((uint64_t)gauss(o, w * 6 / 10) * env * 46 >> 24); + } + /* it stretches along the line the pair last lay on, and squeezes across it */ + n->ripple_c2 = ck_cos(2 * last); + n->ripple_s2 = ck_sin(2 * last); + } +} + +/* ---- drawing the base ---- */ + +static uint32_t lerp16(uint32_t a, uint32_t b, uint32_t f) /* f: 0..16 */ +{ + return ((((a & 0xff00ffu) * (16 - f) + (b & 0xff00ffu) * f) >> 4) & 0xff00ffu) | + ((((a & 0x00ff00u) * (16 - f) + (b & 0x00ff00u) * f) >> 4) & 0x00ff00u); +} + +/* the sky at (sx, sy), 16ths of a pixel (pixel i's centre at 16 i + 8) */ +static uint32_t sample(const ck_night *n, int32_t sx, int32_t sy) +{ + sx = ck_clamp(sx - 8, 0, (n->w - 1) * 16); + sy = ck_clamp(sy - 8, 0, (n->h - 1) * 16); + int32_t ix = sx >> 4, iy = sy >> 4, ix1 = ck_min(ix + 1, n->w - 1), iy1 = ck_min(iy + 1, n->h - 1); + const uint32_t *r0 = n->sky + (size_t)iy * (size_t)n->w, *r1 = n->sky + (size_t)iy1 * (size_t)n->w; + uint32_t fx = (uint32_t)sx & 15u, fy = (uint32_t)sy & 15u; + return lerp16(lerp16(r0[ix], r0[ix1], fx), lerp16(r1[ix], r1[ix1], fx), fy); +} + +/* where (X, Y) (16ths of a pixel) looks in the sky: offset (ax, ay), and the ripple's own faint light */ +static void warp(const ck_night *n, int64_t X, int64_t Y, int32_t *ax, int32_t *ay, uint32_t *light) +{ + int64_t sx = 0, sy = 0; + *light = 0; + for (unsigned i = 0; i < n->holes; i++) { + int64_t e = n->hole[i].e, dx = X - n->hole[i].x, dy = Y - n->hole[i].y, d2 = dx * dx + dy * dy; + int64_t out = e * e * 1936 / 100, in = e * e * 484 / 100; /* (4.4 E)^2, (2.2 E)^2 */ + if (e <= 0 || d2 >= out) + continue; + if (d2 < 64) + d2 = 64; + int64_t f = e * e * 65536 / d2; + if (d2 > in) { + int64_t w = (out - d2) * 65536 / (out - in); + f = f * (w * w >> 16) >> 16; + } + sx -= dx * f >> 16; + sy -= dy * f >> 16; + } + if (n->ripple_w) { + int64_t dx = X - (n->cx * 16 + 8), dy = Y - (n->cy * 16 + 8), d2 = dx * dx + dy * dy; + int64_t r16 = (int64_t)ck_isqrt((uint64_t)d2), reach = n->ripple_w * 22 / 10; + int64_t i = (r16 >> 4) - n->ripple_r + reach; + if (r16 > 0 && i >= 0 && i <= 2 * reach && i < 1024) { + int64_t q = ((dx * dx - dy * dy) * n->ripple_c2 + 2 * dx * dy * n->ripple_s2) / d2; /* cos 2(theta - psi), Q14 */ + int64_t m = (int64_t)n->ripple_disp[i] * (5734 + (q * 10650 >> 14)) >> 14; + sx -= m * dx / r16; + sy -= m * dy / r16; + *light = n->ripple_light[i]; + } + } + *ax = (int32_t)sx; + *ay = (int32_t)sy; +} + +static uint32_t finish(const ck_night *n, uint32_t c, int32_t x, int32_t y, uint32_t light) +{ + if (n->t < CK_NIGHT_FADE_END_MS) + c = fade_px(n, c, x, y); + return light ? ck_add(c, CK_RGB(86, 108, 176), light) : c; +} + +/* a pixel close to a hole: the pull worked out exactly, then the shadow and its thin ring of light */ +static uint32_t near_px(const ck_night *n, int32_t x, int32_t y) +{ + int64_t X = (int64_t)x * 16 + 8, Y = (int64_t)y * 16 + 8; + int32_t ax, ay; + uint32_t light; + warp(n, X, Y, &ax, &ay, &light); + uint32_t c = finish(n, sample(n, (int32_t)X + ax, (int32_t)Y + ay), x, y, light); + for (unsigned i = 0; i < n->holes; i++) { + int64_t rs = n->hole[i].rs, dx = X - n->hole[i].x, dy = Y - n->hole[i].y, d2 = dx * dx + dy * dy; + if (rs <= 0 || d2 >= rs * rs * 9 / 4) + continue; + int32_t r = (int32_t)ck_isqrt((uint64_t)d2); + c = ck_mix(c, 0, ck_cover(r - (int32_t)rs)); + int32_t ring = ck_abs(r - (int32_t)(rs * 104 / 100)); + uint32_t a = ring < 22 ? (uint32_t)(22 - ring) * 6 : 0; + if (r > rs) + a += (uint32_t)((rs * 3 / 2 - r) * 46 / (rs / 2 + 1)) * (r < rs * 3 / 2); + c = ck_add(c, CK_RGB(255, 228, 196), a); + } + return c; +} + +static int near_hole(const ck_night *n, int32_t x, int32_t y) +{ + int64_t X = (int64_t)x * 16 + 8, Y = (int64_t)y * 16 + 8; + for (unsigned i = 0; i < n->holes; i++) { + int64_t reach = ck_max(n->hole[i].e, n->hole[i].rs * 3 / 2) + 8 * 16; + int64_t dx = X - n->hole[i].x, dy = Y - n->hole[i].y; + if (dx * dx + dy * dy < reach * reach) + return 1; + } + return 0; +} + +/* does the 8 x 8 block at (bx, by) meet the band the ripple bends? */ +static int in_ripple(const ck_night *n, int32_t bx, int32_t by) +{ + if (!n->ripple_w) + return 0; + int64_t reach = n->ripple_w * 22 / 10 + 1, lo = ck_max(0, n->ripple_r - (int32_t)reach), hi = n->ripple_r + reach; + int64_t nx = ck_clamp(n->cx, bx, bx + 8) - n->cx, ny = ck_clamp(n->cy, by, by + 8) - n->cy; + int64_t fx = ck_max(ck_abs(bx - n->cx), ck_abs(bx + 8 - n->cx)), fy = ck_max(ck_abs(by - n->cy), ck_abs(by + 8 - n->cy)); + return nx * nx + ny * ny <= hi * hi && fx * fx + fy * fy >= lo * lo; +} + +void ck_night_base(const ck_night *n, ck_canvas *out, const ck_rect *r) +{ + ck_rect d = *r, all = {0, 0, n->w, n->h}; + if (!ck_clip(&d, &all)) + return; + int fading = n->t < CK_NIGHT_FADE_END_MS; + for (int32_t y = d.y; y < d.y + d.h; y++) { + const uint32_t *src = n->sky + (size_t)y * (size_t)n->w; + uint32_t *dst = out->px + (size_t)y * (size_t)out->w; + if (fading) + for (int32_t x = d.x; x < d.x + d.w; x++) + dst[x] = fade_px(n, src[x], x, y); + else + for (int32_t x = d.x; x < d.x + d.w; x++) + dst[x] = src[x]; + } + if (!n->lens.w && !n->ripple_w) + return; + /* the bent parts, in 8 x 8 blocks on a grid fixed to the screen, so any split of r draws the same */ + for (int32_t by = d.y & ~7; by < d.y + d.h; by += 8) + for (int32_t bx = d.x & ~7; bx < d.x + d.w; bx += 8) { + ck_rect b = {bx, by, 8, 8}; + int lens = n->lens.w && ck_meets(b, &n->lens); + if (!lens && !in_ripple(n, bx, by)) + continue; + if (!ck_clip(&b, &d)) + continue; + if (lens && near_hole(n, bx + 4, by + 4)) { + for (int32_t y = b.y; y < b.y + b.h; y++) + for (int32_t x = b.x; x < b.x + b.w; x++) + out->px[(size_t)y * (size_t)out->w + (size_t)x] = near_px(n, x, y); + continue; + } + int32_t ax[4], ay[4]; + uint32_t li[4]; + for (int c = 0; c < 4; c++) + warp(n, ((int64_t)bx + (c & 1) * 8) * 16, ((int64_t)by + (c >> 1) * 8) * 16, &ax[c], &ay[c], &li[c]); + for (int32_t y = b.y; y < b.y + b.h; y++) { + int32_t wy = 2 * (y - by) + 1; + for (int32_t x = b.x; x < b.x + b.w; x++) { + int32_t wx = 2 * (x - bx) + 1; + int32_t w00 = (16 - wx) * (16 - wy), w10 = wx * (16 - wy), w01 = (16 - wx) * wy, w11 = wx * wy; + int32_t sx = (ax[0] * w00 + ax[1] * w10 + ax[2] * w01 + ax[3] * w11) >> 8; + int32_t sy = (ay[0] * w00 + ay[1] * w10 + ay[2] * w01 + ay[3] * w11) >> 8; + uint32_t l = (uint32_t)((int32_t)li[0] * w00 + (int32_t)li[1] * w10 + (int32_t)li[2] * w01 + + (int32_t)li[3] * w11) >> 8; + uint32_t c = sample(n, x * 16 + 8 + sx, y * 16 + 8 + sy); + out->px[(size_t)y * (size_t)out->w + (size_t)x] = finish(n, c, x, y, l); + } + } + } +} + +/* ---- the lights on top ---- */ + +ck_rect ck_night_star_box(const ck_night *n, unsigned i) +{ + const ck_night_star *s = &n->tw[i]; + return (ck_rect){(s->x - s->r) >> 4, (s->y - s->r) >> 4, (2 * s->r >> 4) + 2, (2 * s->r >> 4) + 2}; +} + +void ck_night_lights(const ck_night *n, ck_canvas *out, const ck_rect *r, uint32_t shimmer, uint32_t voice) +{ + for (unsigned i = 0; i < n->ntw; i++) { + const ck_night_star *s = &n->tw[i]; + ck_rect b = ck_night_star_box(n, i); + if (!ck_meets(b, r) || (n->lens.w && ck_meets(b, &n->lens))) + continue; + uint32_t tw = (uint32_t)(16384 + ck_sin((n->t + s->phase) % s->period * 65536u / s->period)) >> 7; + uint32_t a = (tw * tw >> 8) * 120 >> 8; + a = a * ck_night_faded(n, s->x >> 4, s->y >> 4, 255) >> 8; + ck_glow(out, r, s->x, s->y, s->r, s->color, a); + } + if (!shimmer && !voice) + return; + for (unsigned i = 0; i < CK_NIGHT_GALAXIES; i++) { + const ck_night_galaxy *g = &n->gal[i]; + ck_rect b = g->box; + if (!g->box.w || !ck_clip(&b, r)) + continue; + uint32_t sweep = n->t % g->period * 256u / g->period; + for (int32_t y = b.y; y < b.y + b.h; y++) { + const uint8_t *lp = g->light + (size_t)(y - g->box.y) * (size_t)g->box.w - (size_t)g->box.x; + const uint8_t *pp = g->phase + (size_t)(y - g->box.y) * (size_t)g->box.w - (size_t)g->box.x; + uint32_t *row = out->px + (size_t)y * (size_t)out->w; + for (int32_t x = b.x; x < b.x + b.w; x++) { + uint32_t l = lp[x]; + if (!l) + continue; + uint32_t a = (l * band_t[(pp[x] - sweep) & 255u] >> 8) * shimmer >> 8; + a += (l * l >> 8) * voice >> 9; + if (a) + row[x] = ck_add(row[x], g->tint, a); + } + } + } +} diff --git a/native/kernel/ui/night.h b/native/kernel/ui/night.h new file mode 100644 index 00000000..6dafc8d1 --- /dev/null +++ b/native/kernel/ui/night.h @@ -0,0 +1,103 @@ +/* night.h -- the night sky AIENOS opens on, and the two black holes that + * merge in it. + * + * The sky is made once, into RAM: a near-black field, a faint Milky Way with + * dust lanes across the middle, faint coloured nebulae, some ten thousand + * stars and six galaxies. Each galaxy also keeps, per pixel, how bright it is + * and where along its spiral that pixel sits, so a band of light can later + * sweep along its arms (while Allen answers) without the galaxy itself + * changing. + * + * The startup, on the clock from ck_night_init (ms): + * 0 to CK_NIGHT_FADE_END_MS the eyes adjust to the dark: the brightest + * stars first, then the fainter ones, then the + * Milky Way, in slow patches across the sky. + * CK_NIGHT_HOLES_MS two black holes start to bend the starlight + * (gravitational lensing: stars behind them are + * pulled into arcs), then show their shadows, + * circling on a tilted orbit; + * CK_NIGHT_SPIRAL_MS they spiral in, faster and closer, the way a + * real pair does (separation as t^(1/4), angle + * as t^(5/8), t the time left); + * CK_NIGHT_MERGE_MS they merge; a ripple (the gravitational wave, + * stretching one way and squeezing the other) + * runs out through the stars; the one black + * hole left rings, then dissolves by + * CK_NIGHT_GONE_MS. + * + * Every pixel is a pure function of its position and the time, so a frame + * redraws only the regions that changed, in any order. Integer only, + * freestanding, no heap. Host tested in ui/tests/allen_ui_test.c. */ +#ifndef AIENOS_NIGHT_H +#define AIENOS_NIGHT_H +#include +#include + +#include "paint.h" + +#define CK_NIGHT_FADE_END_MS 6800u +#define CK_NIGHT_HOLES_MS 2600u +#define CK_NIGHT_SPIRAL_MS 6000u +#define CK_NIGHT_MERGE_MS 12000u +#define CK_NIGHT_RIPPLE_MS 3600u /* the ripple's run across the screen */ +#define CK_NIGHT_GONE_MS 15200u /* the last black hole has dissolved */ + +#define CK_NIGHT_GALAXIES 6u +#define CK_NIGHT_TWINKLES 256u + +typedef struct { + ck_rect box; + uint8_t *light, *phase; /* box.w * box.h each */ + uint32_t tint; /* the colour of the light that sweeps it */ + uint16_t period; /* ms for the sweep to come round */ +} ck_night_galaxy; + +typedef struct { + int32_t x, y, r; /* 16ths of a pixel */ + uint32_t color; + uint16_t period, phase; /* ms */ +} ck_night_star; + +typedef struct { + int32_t w, h; + uint32_t k; /* 1/256 px per design px (1920 x 1080 design) */ + int32_t cx, cy; /* where the black holes merge, px */ + uint32_t *sky; /* the night, w * h */ + uint8_t *appear; /* when each 4 x 4 cell comes out of the dark (0..255) */ + int32_t aw; + ck_night_galaxy gal[CK_NIGHT_GALAXIES]; + ck_night_star tw[CK_NIGHT_TWINKLES]; + unsigned ntw; + /* state at the time ck_night_at was last given */ + uint32_t t; + unsigned holes; + struct { + int32_t x, y, e, rs; /* 16ths of a pixel: centre, Einstein radius, shadow radius */ + } hole[2]; + ck_rect lens; /* where the light is bent (empty: nowhere) */ + int32_t ripple_r, ripple_w; /* px; ripple_w 0: no ripple */ + int32_t ripple_disp[1024]; /* 16ths of a pixel, by distance from the crest */ + uint8_t ripple_light[1024]; + int32_t ripple_c2, ripple_s2; /* the stretch direction, Q14 */ +} ck_night; + +/* Memory for a w x h night at scale k. */ +size_t ck_night_mem_bytes(uint32_t w, uint32_t h, uint32_t k); +/* Makes the sky into mem; scratch: at least w * h * 4 bytes of working + * memory, overwritten. (cx, cy): where the holes merge. 0, or -1. */ +int ck_night_init(ck_night *n, uint32_t w, uint32_t h, uint32_t k, int32_t cx, int32_t cy, void *mem, size_t len, + void *scratch); +/* Moves the night to t ms: the holes, the lens region, the ripple. */ +void ck_night_at(ck_night *n, uint32_t t); +/* The sky as seen at the current time (faded in, bent, rippled) into the + * rectangle r of out. */ +void ck_night_base(const ck_night *n, ck_canvas *out, const ck_rect *r); +/* Adds the twinkling and, with shimmer > 0 (0..256), the light sweeping the + * galaxies; voice (0..256) brightens their cores. */ +void ck_night_lights(const ck_night *n, ck_canvas *out, const ck_rect *r, uint32_t shimmer, uint32_t voice); +/* The rectangle a twinkling star needs redrawn. */ +ck_rect ck_night_star_box(const ck_night *n, unsigned i); +/* How far the sky has come out of the dark at (x, y) for light of level l + * (0..255): 0..256. */ +uint32_t ck_night_faded(const ck_night *n, int32_t x, int32_t y, uint32_t l); +#endif diff --git a/native/kernel/ui/paint.c b/native/kernel/ui/paint.c new file mode 100644 index 00000000..b85443b5 --- /dev/null +++ b/native/kernel/ui/paint.c @@ -0,0 +1,272 @@ +/* paint.c -- the drawing kit; see paint.h. */ +#include "paint.h" + +/* ---- tables, filled on first use ---- */ + +static int16_t sin_t[4097]; /* a full turn in 4096 steps, Q14; one extra for interpolation */ +static uint32_t exp_t[4096]; /* exp(-k/256), Q16 */ +static uint32_t log_t[257]; /* log2(1 + k/256), Q16 */ +static int ready; + +static void setup(void) +{ + /* sine: a rotation by a 4096th of a turn, applied over and over (Q30) */ + const int64_t C = 1073740561, S = 1647099; + int64_t c = 1ll << 30, s = 0; + for (unsigned k = 0; k <= 1024; k++) { + int16_t v = k == 1024 ? 16384 : (int16_t)((s + (1 << 15)) >> 16); + sin_t[k] = v; + sin_t[2048 - k] = v; + sin_t[(2048 + k) & 4095] = (int16_t)-v; + sin_t[(4096 - k) & 4095] = (int16_t)-v; + int64_t nc = (c * C - s * S) >> 30, ns = (s * C + c * S) >> 30; + c = nc, s = ns; + } + sin_t[4096] = sin_t[0]; + /* exp(-k/256): one factor of exp(-1/256) (Q30) per step */ + uint64_t e = 1ull << 30; + for (unsigned k = 0; k < 4096; k++) { + exp_t[k] = (uint32_t)((e + (1u << 13)) >> 14); + e = e * 1069555701ull >> 30; + } + /* log2(1 + k/256): square the value 16 times, taking a bit each time it passes 2 */ + for (unsigned k = 0; k <= 256; k++) { + uint64_t y = (256u + k) << 8; /* Q16, in [1, 2] */ + uint32_t r = 0; + if (k == 256) { + log_t[k] = 65536; + continue; + } + for (int b = 15; b >= 0; b--) { + y = y * y >> 16; + if (y >= 2u << 16) { + y >>= 1; + r |= 1u << b; + } + } + log_t[k] = r; + } + ready = 1; +} + +int32_t ck_sin(uint32_t a) +{ + if (!ready) + setup(); + a &= 65535u; + uint32_t i = a >> 4, f = a & 15u; + return sin_t[i] + (((int32_t)sin_t[i + 1] - sin_t[i]) * (int32_t)f >> 4); +} + +int32_t ck_cos(uint32_t a) { return ck_sin(a + 16384u); } + +uint32_t ck_atan2(int32_t y, int32_t x) +{ + static const uint16_t step[14] = {8192, 4836, 2555, 1297, 651, 326, 163, 81, 41, 20, 10, 5, 3, 1}; + int64_t X = x, Y = y; + uint32_t ang = 0; + if (X == 0 && Y == 0) + return 0; + if (X < 0) { /* turn half a turn into the right half-plane */ + X = -X, Y = -Y; + ang = 32768; + } + int64_t m = X > (Y < 0 ? -Y : Y) ? X : (Y < 0 ? -Y : Y); + while (m < (1 << 20)) + X <<= 1, Y <<= 1, m <<= 1; + while (m >= (1 << 22)) + X >>= 1, Y >>= 1, m >>= 1; + int32_t z = 0; + for (int i = 0; i < 14; i++) { + int64_t nx; + if (Y > 0) { + nx = X + (Y >> i); + Y -= X >> i; + z += step[i]; + } else { + nx = X - (Y >> i); + Y += X >> i; + z -= step[i]; + } + X = nx; + } + return (ang + (uint32_t)z) & 65535u; +} + +uint32_t ck_exp_neg(uint32_t x) +{ + if (!ready) + setup(); + return x < 4096 ? exp_t[x] : 0; +} + +uint32_t ck_log2_q16(uint64_t v) +{ + if (!ready) + setup(); + if (!v) + return 0; + int n = 63 - __builtin_clzll(v); + uint64_t m = n >= 16 ? v >> (n - 16) : v << (16 - n); /* Q16 in [1, 2) */ + uint32_t k = (uint32_t)(m >> 8 & 255u), f = (uint32_t)(m & 255u); + return (uint32_t)n * 65536u + log_t[k] + ((log_t[k + 1] - log_t[k]) * f >> 8); +} + +uint64_t ck_isqrt(uint64_t v) { return ck_af_isqrt(v); } + +uint32_t ck_hash(int32_t x, int32_t y, uint32_t seed) +{ + uint32_t h = (uint32_t)x * 0x8da6b343u ^ (uint32_t)y * 0xd8163841u ^ seed * 0xcb1ab31fu; + h ^= h >> 13; + h *= 0x5bd1e995u; + h ^= h >> 15; + h *= 0x27d4eb2du; + h ^= h >> 16; + return h; +} + +uint32_t ck_noise(int32_t x, int32_t y, uint32_t seed) +{ + int32_t ix = x >> 8, iy = y >> 8; + uint32_t fx = ck_smooth(x & 255), fy = ck_smooth(y & 255); + uint64_t v00 = ck_hash(ix, iy, seed) >> 16, v10 = ck_hash(ix + 1, iy, seed) >> 16; + uint64_t v01 = ck_hash(ix, iy + 1, seed) >> 16, v11 = ck_hash(ix + 1, iy + 1, seed) >> 16; + uint64_t a = v00 * (256 - fx) + v10 * fx, b = v01 * (256 - fx) + v11 * fx; + return (uint32_t)((a * (256 - fy) + b * fy) >> 16); +} + +uint32_t ck_fbm(int32_t x, int32_t y, uint32_t seed, int octaves) +{ + uint64_t sum = 0, total = 0; + for (int o = 0; o < octaves; o++) { + uint32_t w = 1u << (octaves - 1 - o); + sum += (uint64_t)ck_noise(x << o, y << o, seed + (uint32_t)o * 7919u) * w; + total += w; + } + return (uint32_t)(sum / total); +} + +/* ---- shapes ---- */ + +/* d becomes the part of d inside both the clip and the canvas */ +static int fit(const ck_canvas *cv, const ck_rect *clip, ck_rect *d) +{ + ck_rect all = {0, 0, cv->w, cv->h}; + return ck_clip(d, clip) && ck_clip(d, &all); +} + +void ck_glow(ck_canvas *cv, const ck_rect *clip, int32_t cx, int32_t cy, int32_t r, uint32_t color, uint32_t a) +{ + if (r <= 0 || !a) + return; + ck_rect d = {(cx - r) >> 4, (cy - r) >> 4, 0, 0}; + d.w = ((cx + r) >> 4) - d.x + 1; + d.h = ((cy + r) >> 4) - d.y + 1; + if (!fit(cv, clip, &d)) + return; + int64_t r2 = (int64_t)r * r; + uint64_t inv = (1ull << 40) / (uint64_t)r2; + for (int32_t y = d.y; y < d.y + d.h; y++) { + int64_t dy = (int64_t)y * 16 + 8 - cy, dy2 = dy * dy; + if (dy2 >= r2) + continue; + int32_t half = (int32_t)ck_isqrt((uint64_t)(r2 - dy2)); + int32_t x0 = ck_max(d.x, (cx - half) >> 4), x1 = ck_min(d.x + d.w - 1, (cx + half) >> 4); + uint32_t *row = cv->px + (size_t)y * (size_t)cv->w; + for (int32_t x = x0; x <= x1; x++) { + int64_t dx = (int64_t)x * 16 + 8 - cx, d2 = dx * dx + dy2; + if (d2 >= r2) + continue; + uint32_t f = 256u - (uint32_t)((uint64_t)d2 * inv >> 32); + uint32_t w = (f * f >> 8) * f >> 8; /* 0..256 */ + row[x] = ck_add(row[x], color, w * a >> 8); + } + } +} + +static void plot(ck_canvas *cv, const ck_rect *clip, int32_t x, int32_t y, uint32_t color, uint32_t a) +{ + if (!a || x < clip->x || y < clip->y || x >= clip->x + clip->w || y >= clip->y + clip->h || x < 0 || y < 0 || + x >= cv->w || y >= cv->h) + return; + uint32_t *p = cv->px + (size_t)y * (size_t)cv->w + x; + *p = ck_add(*p, color, a); +} + +void ck_thread(ck_canvas *cv, const ck_rect *clip, int32_t x0, int32_t y0, int32_t x1, int32_t y1, uint32_t color, + uint32_t a0, uint32_t a1) +{ + ck_rect box = {(ck_min(x0, x1) >> 4) - 1, (ck_min(y0, y1) >> 4) - 1, 0, 0}; + box.w = (ck_max(x0, x1) >> 4) - box.x + 3; + box.h = (ck_max(y0, y1) >> 4) - box.y + 3; + if (!ck_meets(box, clip) || (!a0 && !a1)) + return; + int steep = ck_abs(y1 - y0) > ck_abs(x1 - x0); + if (steep) { + int32_t t = x0; + x0 = y0, y0 = t; + t = x1; + x1 = y1, y1 = t; + } + if (x0 > x1) { + int32_t t = x0; + x0 = x1, x1 = t; + t = y0; + y0 = y1, y1 = t; + uint32_t u = a0; + a0 = a1, a1 = u; + } + int32_t len = x1 - x0; + if (len < 1) + len = 1; + int64_t grad = (int64_t)(y1 - y0) * 65536 / len; + /* a slanted thread covers more ground per column: weigh it by its length per column */ + uint32_t slant = (uint32_t)(ck_isqrt((uint64_t)(65536ll * 65536ll + grad * grad)) >> 8); /* 256 = flat */ + int32_t first = (x0 + 7) >> 4, last = (x1 - 8) >> 4; + for (int32_t X = first; X <= last; X++) { + int32_t along = X * 16 + 8 - x0; + int32_t yc = y0 + (int32_t)(along * grad >> 16) - 8; + int32_t Y = yc >> 4, f = yc & 15; + uint32_t a = (uint32_t)((int32_t)a0 + ((int32_t)a1 - (int32_t)a0) * along / len) * slant >> 8; + if (steep) { + plot(cv, clip, Y, X, color, a * (uint32_t)(16 - f) >> 4); + plot(cv, clip, Y + 1, X, color, a * (uint32_t)f >> 4); + } else { + plot(cv, clip, X, Y, color, a * (uint32_t)(16 - f) >> 4); + plot(cv, clip, X, Y + 1, color, a * (uint32_t)f >> 4); + } + } +} + +int32_t ck_sd_rrect(int32_t x, int32_t y, const ck_rect *r, int32_t rad) +{ + int64_t px = (int64_t)x * 16 + 8, py = (int64_t)y * 16 + 8; + int64_t cx = (int64_t)r->x * 16 + (int64_t)r->w * 8, cy = (int64_t)r->y * 16 + (int64_t)r->h * 8; + int64_t qx = (px > cx ? px - cx : cx - px) - ((int64_t)r->w * 8 - rad * 16); + int64_t qy = (py > cy ? py - cy : cy - py) - ((int64_t)r->h * 8 - rad * 16); + int64_t out = qx > 0 && qy > 0 ? (int64_t)ck_isqrt((uint64_t)(qx * qx + qy * qy)) : qx > qy ? qx : qy; + return (int32_t)(out - rad * 16); +} + +uint64_t ck_letter(ck_canvas *cv, const ck_rect *clip, ck_af_face *f, uint64_t pen, int32_t y, char c, + uint32_t color, uint32_t a, int add) +{ + const ck_af_glyph *g = a ? ck_af_glyph_get(f, c) : 0; + if (g && g->alpha) { + int32_t gx = (int32_t)((pen + 128) / 256) + g->ox, gy = y + g->oy; + ck_rect d = {gx, gy, g->w, g->h}; + if (fit(cv, clip, &d)) + for (int32_t yy = d.y; yy < d.y + d.h; yy++) { + uint32_t *row = cv->px + (size_t)yy * (size_t)cv->w; + const uint8_t *m = g->alpha + (size_t)(yy - gy) * g->w; + for (int32_t xx = d.x; xx < d.x + d.w; xx++) { + uint32_t cov = m[xx - gx]; + if (cov) { + uint32_t w = (cov + (cov >> 7)) * a >> 8; + row[xx] = add ? ck_add(row[xx], color, w) : ck_mix(row[xx], color, w); + } + } + } + } + return pen + ck_af_advance(f, c); +} diff --git a/native/kernel/ui/paint.h b/native/kernel/ui/paint.h new file mode 100644 index 00000000..a72aa5b5 --- /dev/null +++ b/native/kernel/ui/paint.h @@ -0,0 +1,143 @@ +/* paint.h -- the drawing kit shared by the night sky (ui/night.c), Allen's + * presence (ui/mind.c) and his home (ui/allen_ui.c): rectangles, colour + * arithmetic, soft round lights, anti-aliased threads, rounded shapes and + * text, all into a RAM canvas of 0x00RRGGBB pixels; plus the integer + * mathematics they share (sine, atan2, exp, log2, hashed noise). Integer + * only (the kernel builds -mgeneral-regs-only), freestanding, no memory of + * its own beyond fixed tables. Host tested through ui/tests/allen_ui_test.c. + * + * Angles are in 65536ths of a turn. Positions handed to the soft shapes are + * in 16ths of a pixel, so slow movement is smooth rather than stepping a + * whole pixel at a time. */ +#ifndef AIENOS_PAINT_H +#define AIENOS_PAINT_H +#include +#include + +#include "allen_font.h" + +typedef struct { + int32_t x, y, w, h; +} ck_rect; + +typedef struct { + uint32_t *px; /* w * h pixels, rows w apart */ + int32_t w, h; +} ck_canvas; + +#define CK_RGB(r, g, b) ((uint32_t)(r) << 16 | (uint32_t)(g) << 8 | (uint32_t)(b)) + +static inline int32_t ck_min(int32_t a, int32_t b) { return a < b ? a : b; } +static inline int32_t ck_max(int32_t a, int32_t b) { return a > b ? a : b; } +static inline int32_t ck_abs(int32_t a) { return a < 0 ? -a : a; } +static inline int32_t ck_clamp(int32_t v, int32_t lo, int32_t hi) { return v < lo ? lo : v > hi ? hi : v; } + +/* r becomes its overlap with c; 0 when they do not meet. */ +static inline int ck_clip(ck_rect *r, const ck_rect *c) +{ + int32_t x0 = ck_max(r->x, c->x), y0 = ck_max(r->y, c->y); + int32_t x1 = ck_min(r->x + r->w, c->x + c->w), y1 = ck_min(r->y + r->h, c->y + c->h); + if (x1 <= x0 || y1 <= y0) + return 0; + *r = (ck_rect){x0, y0, x1 - x0, y1 - y0}; + return 1; +} + +static inline int ck_meets(ck_rect a, const ck_rect *b) { return ck_clip(&a, b); } +static inline ck_rect ck_grow(ck_rect r, int32_t m) { return (ck_rect){r.x - m, r.y - m, r.w + 2 * m, r.h + 2 * m}; } + +/* The smallest rectangle holding both (an empty one adds nothing). */ +static inline ck_rect ck_union(ck_rect a, ck_rect b) +{ + if (a.w <= 0 || a.h <= 0) + return b; + if (b.w <= 0 || b.h <= 0) + return a; + int32_t x0 = ck_min(a.x, b.x), y0 = ck_min(a.y, b.y); + return (ck_rect){x0, y0, ck_max(a.x + a.w, b.x + b.w) - x0, ck_max(a.y + a.h, b.y + b.h) - y0}; +} + +/* ---- colour: channels 0..255, weights 0..256 ---- */ + +static inline uint32_t ck_ch(uint32_t c, int s) { return c >> s & 255u; } + +/* c scaled by f/256 (f <= 256), all three channels at once */ +static inline uint32_t ck_scale(uint32_t c, uint32_t f) +{ + return ((c & 0xff00ffu) * f >> 8 & 0xff00ffu) | ((c & 0x00ff00u) * f >> 8 & 0x00ff00u); +} + +/* d + c * a / 256 per channel, held at 255 */ +static inline uint32_t ck_add(uint32_t d, uint32_t c, uint32_t a) +{ + uint32_t r = ck_ch(d, 16) + (ck_ch(c, 16) * a >> 8), g = ck_ch(d, 8) + (ck_ch(c, 8) * a >> 8), + b = ck_ch(d, 0) + (ck_ch(c, 0) * a >> 8); + return (r > 255 ? 255u : r) << 16 | (g > 255 ? 255u : g) << 8 | (b > 255 ? 255u : b); +} + +/* d toward c by a/256 */ +static inline uint32_t ck_mix(uint32_t d, uint32_t c, uint32_t a) +{ + if (a >= 256) + return c; + return ck_scale(d, 256 - a) + ck_scale(c, a); +} + +/* ---- easing: t and the result in 0..256 ---- */ + +static inline uint32_t ck_smooth(int32_t t) /* 3t^2 - 2t^3 */ +{ + t = ck_clamp(t, 0, 256); + return (uint32_t)(t * t * (768 - 2 * t) >> 16); +} + +static inline uint32_t ck_ease_out(int32_t t) /* 1 - (1 - t)^3 */ +{ + t = 256 - ck_clamp(t, 0, 256); + return 256u - (uint32_t)(t * t * t >> 16); +} + +/* 0..256 for how far `now` is from `from` to `to` (ms) */ +static inline int32_t ck_prog(uint32_t now, uint32_t from, uint32_t to) +{ + if (now <= from) + return 0; + if (now >= to) + return 256; + return (int32_t)((uint64_t)(now - from) * 256u / (to - from)); +} + +/* ---- mathematics (paint.c) ---- */ + +int32_t ck_sin(uint32_t turn65536); /* scaled by 16384 */ +int32_t ck_cos(uint32_t turn65536); +uint32_t ck_atan2(int32_t y, int32_t x); /* the angle of (x, y), 0..65535 */ +uint32_t ck_exp_neg(uint32_t x256); /* exp(-x/256), scaled by 65536 */ +uint32_t ck_log2_q16(uint64_t v); /* log2(v) * 65536, v >= 1 */ +uint64_t ck_isqrt(uint64_t v); +uint32_t ck_hash(int32_t x, int32_t y, uint32_t seed); +uint32_t ck_noise(int32_t x256, int32_t y256, uint32_t seed); /* smooth value noise, 0..65535 */ +uint32_t ck_fbm(int32_t x256, int32_t y256, uint32_t seed, int octaves); /* 0..65535 */ + +/* ---- shapes (paint.c); each draws only inside the clip rectangle ---- */ + +/* A soft round light at (cx, cy) with radius r (16ths of a pixel): colour + * added with weight a * (1 - d^2/r^2)^3. */ +void ck_glow(ck_canvas *cv, const ck_rect *clip, int32_t cx, int32_t cy, int32_t r, uint32_t color, uint32_t a); +/* A thread one pixel wide from (x0, y0) to (x1, y1) (16ths of a pixel), + * anti-aliased, added as light whose weight runs from a0 to a1 along it. */ +void ck_thread(ck_canvas *cv, const ck_rect *clip, int32_t x0, int32_t y0, int32_t x1, int32_t y1, uint32_t color, + uint32_t a0, uint32_t a1); +/* Signed distance from a pixel's centre to a rounded rectangle, 16ths of a + * pixel, negative inside; and the coverage of a pixel at such a distance. */ +int32_t ck_sd_rrect(int32_t x, int32_t y, const ck_rect *r, int32_t radius); +static inline uint32_t ck_cover(int32_t d16) +{ + int32_t v = 8 - d16; + return v <= 0 ? 0u : v >= 16 ? 256u : (uint32_t)(v * 16); +} +/* One letter at pen (1/256 px) on baseline y, mixed in with weight a + * (additive light when add is set); returns the pen after it. */ +uint64_t ck_letter(ck_canvas *cv, const ck_rect *clip, ck_af_face *f, uint64_t pen, int32_t y, char c, + uint32_t color, uint32_t a, int add); +#endif diff --git a/native/kernel/ui/tests/allen_ui_test.c b/native/kernel/ui/tests/allen_ui_test.c new file mode 100644 index 00000000..4a909228 --- /dev/null +++ b/native/kernel/ui/tests/allen_ui_test.c @@ -0,0 +1,546 @@ +/* allen_ui_test.c -- host test for Allen's home (ui/allen_ui.c with the night + * sky, ui/night.c, and his presence, ui/mind.c), his typeface + * (ui/allen_font.c) and his first answers (svc/allen_reply.c). Runs the + * startup at 3840 x 2160 BGRX on a hand-moved clock, wakes Allen, types + * "Hello Allen", lets him answer, leaves him alone, saves a note; checks the + * pixels at each step, checks that drawing only the changed parts gives the + * same picture as drawing everything, runs 1280 x 800 RGBX with and without + * three helper threads (the frames must match exactly), and writes PNG + * pictures to the directory given as argv[1] (if any) for a person to look at. + * Final line: ALLEN_UI_TEST: PASS|FAIL (N checks). */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../../svc/allen_reply.h" +#include "../allen_font.h" +#include "../allen_ui.h" +#include "../night.h" + +static int checks, fails; +#define CHECK(cond, what) \ + do { \ + checks++; \ + if (!(cond)) { \ + fails++; \ + printf("FAIL %s\n", what); \ + } \ + } while (0) + +/* ---- a minimal PNG writer (stored deflate blocks), host only ---- */ +static uint32_t crc_table[256]; +static void crc_init(void) +{ + for (uint32_t n = 0; n < 256; n++) { + uint32_t c = n; + for (int k = 0; k < 8; k++) + c = c & 1 ? 0xedb88320u ^ (c >> 1) : c >> 1; + crc_table[n] = c; + } +} +static uint32_t crc(uint32_t c, const uint8_t *b, size_t n) +{ + for (size_t i = 0; i < n; i++) + c = crc_table[(c ^ b[i]) & 255] ^ (c >> 8); + return c; +} +static void be32(uint8_t *p, uint32_t v) +{ + p[0] = (uint8_t)(v >> 24), p[1] = (uint8_t)(v >> 16), p[2] = (uint8_t)(v >> 8), p[3] = (uint8_t)v; +} +static void chunk(FILE *f, const char *type, const uint8_t *data, size_t n) +{ + uint8_t h[8]; + be32(h, (uint32_t)n); + memcpy(h + 4, type, 4); + fwrite(h, 1, 8, f); + if (n) + fwrite(data, 1, n, f); + uint32_t c = crc(0xffffffffu, (const uint8_t *)type, 4); + c = crc(c, data, n) ^ 0xffffffffu; + be32(h, c); + fwrite(h, 1, 4, f); +} +/* pixels: 0x00RRGGBB (format 1) rows of `pitch`; region x,y,w,h; every `step`th pixel */ +static void png(const char *path, const uint32_t *px, uint32_t pitch, int fmt, uint32_t x0, uint32_t y0, uint32_t w, + uint32_t h, uint32_t step) +{ + uint32_t ow = w / step, oh = h / step; + size_t raw_n = (size_t)oh * (1 + (size_t)ow * 3); + uint8_t *raw = malloc(raw_n); + size_t k = 0; + for (uint32_t y = 0; y < oh; y++) { + raw[k++] = 0; + for (uint32_t x = 0; x < ow; x++) { + uint32_t sr = 0, sg = 0, sb = 0; + for (uint32_t j = 0; j < step; j++) + for (uint32_t i = 0; i < step; i++) { + uint32_t c = px[((size_t)y0 + (size_t)y * step + j) * pitch + x0 + (size_t)x * step + i]; + sr += c >> 16 & 255, sg += c >> 8 & 255, sb += c & 255; + } + uint8_t r = (uint8_t)(sr / (step * step)), g = (uint8_t)(sg / (step * step)), b = (uint8_t)(sb / (step * step)); + if (fmt == 0) { + uint8_t t = r; + r = b; + b = t; + } + raw[k++] = r, raw[k++] = g, raw[k++] = b; + } + } + size_t blocks = raw_n / 65535 + 1; + size_t z_n = 2 + raw_n + blocks * 5 + 4; + uint8_t *z = malloc(z_n); + size_t o = 0; + z[o++] = 0x78, z[o++] = 0x01; + uint32_t a = 1, b = 0; + for (size_t i = 0; i < raw_n;) { + size_t n = raw_n - i > 65535 ? 65535 : raw_n - i; + z[o++] = i + n == raw_n; + z[o++] = (uint8_t)n, z[o++] = (uint8_t)(n >> 8), z[o++] = (uint8_t)~n, z[o++] = (uint8_t)(~n >> 8); + memcpy(z + o, raw + i, n); + for (size_t j = 0; j < n; j++) { + a = (a + raw[i + j]) % 65521; + b = (b + a) % 65521; + } + o += n; + i += n; + } + be32(z + o, b << 16 | a); + o += 4; + /* 0644, not fopen's 0666 & ~umask: a picture for a person, never world-writable. */ + int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); + FILE *f = fd < 0 ? NULL : fdopen(fd, "wb"); + if (fd >= 0 && !f) + close(fd); + if (!f) { + printf("note: cannot write %s\n", path); + free(raw), free(z); + return; + } + fwrite("\x89PNG\r\n\x1a\n", 1, 8, f); + uint8_t ihdr[13]; + be32(ihdr, ow), be32(ihdr + 4, oh); + ihdr[8] = 8, ihdr[9] = 2, ihdr[10] = 0, ihdr[11] = 0, ihdr[12] = 0; + chunk(f, "IHDR", ihdr, 13); + chunk(f, "IDAT", z, o); + chunk(f, "IEND", 0, 0); + fclose(f); + free(raw), free(z); + printf("note: wrote %s (%ux%u)\n", path, ow, oh); +} + +/* ---- looking at a picture: counts over a rectangle of 0x00RRGGBB pixels ---- */ +struct pic { + const uint32_t *px; + uint32_t pitch; + int fmt; /* 0: red in the low byte (RGBX) */ +}; +static void rgb(const struct pic *p, uint32_t x, uint32_t y, int *r, int *g, int *b) +{ + uint32_t c = p->px[(size_t)y * p->pitch + x]; + *r = c >> 16 & 255, *g = c >> 8 & 255, *b = c & 255; + if (p->fmt == 0) { + int t = *r; + *r = *b; + *b = t; + } +} +enum { BRIGHT, BLACK, VIOLET, LIT }; +static unsigned count(const struct pic *p, uint32_t x0, uint32_t y0, uint32_t w, uint32_t h, int kind) +{ + unsigned n = 0; + for (uint32_t y = y0; y < y0 + h; y++) + for (uint32_t x = x0; x < x0 + w; x++) { + int r, g, b; + rgb(p, x, y, &r, &g, &b); + if (kind == BRIGHT) + n += r > 150 && g > 150 && b > 150; + else if (kind == BLACK) + n += r == 0 && g == 0 && b == 0; + else if (kind == VIOLET) + n += b > 120 && b > r + 30; + else + n += r > 60 || g > 60 || b > 90; + } + return n; +} +/* pixels of a and b (w x h, rows `pitch`) that differ by more than tol in any channel */ +static unsigned differ(const uint32_t *a, const uint32_t *b, uint32_t pitch, uint32_t w, uint32_t h, int tol) +{ + unsigned n = 0; + for (uint32_t y = 0; y < h; y++) + for (uint32_t x = 0; x < w; x++) { + uint32_t c = a[(size_t)y * pitch + x], d = b[(size_t)y * pitch + x]; + for (int s = 0; s < 24; s += 8) { + int e = (int)(c >> s & 255) - (int)(d >> s & 255); + if (e > tol || e < -tol) { + n++; + break; + } + } + } + return n; +} + +static uint64_t real_us(void) +{ + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint64_t)ts.tv_sec * 1000000u + (uint64_t)ts.tv_nsec / 1000u; +} + +/* the screen's clock in these checks: microseconds, moved by hand */ +static uint64_t now_us; +static void run_to(uint32_t ms) +{ + for (; now_us <= (uint64_t)ms * 1000u; now_us += 16000) + ck_allen_ui_tick(now_us); +} + +/* the frame drawn by changed parts against the whole screen drawn again at the same moment */ +static unsigned stale(uint32_t *fb, uint32_t *copy, uint32_t pitch, uint32_t w, uint32_t h) +{ + memcpy(copy, fb, (size_t)pitch * h * 4); + ck_allen_ui_refresh(); + ck_allen_ui_tick(now_us - 16000); + return differ(fb, copy, pitch, w, h, 6); +} + +/* The bare night sky as Allen's screen draws it (same scale and centre) with + * nothing in front of it, and the pixels in a rectangle of the screen that + * differ from it at the moment of the last frame: only what the screen added. */ +static ck_night bare_night; +static int bare_init(uint32_t w, uint32_t h, void *scratch) +{ + uint32_t k = w * 256u / 1920u; + size_t nb = ck_night_mem_bytes(w, h, k); + return ck_night_init(&bare_night, w, h, k, (int32_t)w / 2, (int32_t)(h * 40 / 100), malloc(nb), nb, scratch); +} +static unsigned added(const struct pic *p, uint32_t *sky, uint32_t x0, uint32_t y0, uint32_t w, uint32_t h) +{ + ck_canvas cv = {sky, (int32_t)p->pitch, bare_night.h}; + ck_rect r = {(int32_t)x0, (int32_t)y0, (int32_t)w, (int32_t)h}; + ck_night_at(&bare_night, (uint32_t)((now_us - 16000) / 1000)); + ck_night_base(&bare_night, &cv, &r); + ck_night_lights(&bare_night, &cv, &r, 0, 0); + return differ(p->px + (size_t)y0 * p->pitch + x0, sky + (size_t)y0 * p->pitch + x0, p->pitch, w, h, 24); +} + +static volatile int helpers_run; +static void *helper(void *arg) +{ + (void)arg; + while (helpers_run) + ck_allen_ui_help(); + return 0; +} + +int main(int argc, char **argv) +{ + const char *dir = argc > 1 ? argv[1] : 0; + char path[512]; + crc_init(); + + /* ---- answers ---- */ + CHECK(!strcmp(ck_allen_reply("Hello Allen"), "Hello Humanity."), "reply: Hello Allen"); + CHECK(!strcmp(ck_allen_reply(" hello ALLEN!! "), "Hello Humanity."), "reply: case, spaces, punctuation folded"); + CHECK(!strcmp(ck_allen_reply("hello allen."), "Hello Humanity."), "reply: trailing period"); + CHECK(strcmp(ck_allen_reply("hello allenx"), "Hello Humanity."), "reply: near miss is not the first greeting"); + CHECK(!strncmp(ck_allen_reply(""), "I don't know that yet.", 22), "reply: empty line"); + CHECK(!strncmp(ck_allen_reply(0), "I don't know that yet.", 22), "reply: no line"); + CHECK(!strncmp(ck_allen_reply("xz"), "I don't know that yet.", 22), "reply: unknown line"); + CHECK(!strcmp(ck_allen_reply("who are you"), "I am Allen. I live in AIENOS."), "reply: who are you"); + CHECK(ck_allen_reply("Goodbye, Allen!") == ck_allen_goodbye && ck_allen_reply("bye") == ck_allen_goodbye && + ck_allen_reply("good bye") == ck_allen_goodbye && ck_allen_reply("goodbye now") != ck_allen_goodbye, + "reply: goodbye ends the session (and only goodbye)"); + { + /* A conversation: what Allen is told stays for the session. */ + ck_allen_facts facts = {4, 1, 1, 3840, 2160}; + ck_allen_mind m; + ck_allen_mind_init(&m, &facts); + static const struct { + const char *say, *want; /* want: the answer starts with this */ + uint64_t awake; + } talk[] = { + {"Hello Allen", "Hello Humanity.", 5}, + {"what's my name?", "You haven't told me yet.", 6}, + {"My name is drake", "Nice to meet you, Drake.", 7}, + {"hi", "Hello, Drake. Good to see you.", 8}, + {"what is my name", "You're Drake.", 9}, + {"how are you?", "I'm running well, Drake. 4 cores awake", 10}, + {"good thanks", "Glad to hear it.", 11}, + {"i am tired", "Sorry to hear that.", 12}, + {"what is 12 times 4", "12 times 4 is 48.", 13}, + {"nine divided by two", "9 divided by 2 is 4 remainder 1.", 14}, + {"3 minus 10", "3 minus 10 is minus 7.", 15}, + {"what is 5 divided by zero", "Nobody can divide by zero", 16}, + {"tell me about this computer", "This computer has 4 cores, a 3840 by 2160 screen, 1 hard drive and 1 SSD.", + 17}, + {"how long have you been awake?", "I've been awake for 2 minutes and 5 seconds.", 125}, + {"what time is it", "I can't read the clock yet. I've been awake for 1 hour and 1 minute.", 3660}, + {"who made you", "Drake built me", 3661}, + {"what is aienos", "AIENOS is the operating system I live in", 3662}, + {"tell me a joke", "", 3663}, + {"thank you", "You're welcome, Drake.", 3664}, + {"can you remember things", "Teach me like this: remember my favorite color is blue.", 3665}, + {"help", "I learn what you teach me (remember my car is red) and keep notes", 3666}, + {"i'm fine", "Glad to hear it.", 3667}, + {"blorp", "I don't know that yet.", 3668}, + }; + int ok = 1; + for (size_t i = 0; i < sizeof talk / sizeof talk[0]; i++) { + const char *a = ck_allen_answer(&m, talk[i].say, talk[i].awake); + if (strncmp(a, talk[i].want, strlen(talk[i].want)) || strlen(a) >= 160) { + printf(" conversation line %zu: \"%s\" -> \"%s\"\n", i, talk[i].say, a); + ok = 0; + } + } + CHECK(ok, "reply: a whole conversation (name, how are you, sums, machine facts, awake time, help)"); + } + + /* ---- typeface ---- */ + CHECK(ck_af_isqrt(0) == 0 && ck_af_isqrt(15) == 3 && ck_af_isqrt(16) == 4 && + ck_af_isqrt(1000000007ull * 1000000007ull) == 1000000007ull, + "font: integer square root"); + CHECK(ck_af_sin(0) == 0 && ck_af_sin(90) == 16384 && ck_af_sin(-90) == -16384 && ck_af_cos(180) == -16384 && + ck_af_sin(450) == 16384, + "font: sine table"); + static uint8_t pool[4 << 20]; + ck_af_face face; + ck_af_face_init(&face, 30, 1250, pool, sizeof pool); + int all = 1, sym = 1; + for (int c = 33; c <= 126; c++) { + const ck_af_glyph *g = ck_af_glyph_get(&face, (char)c); + unsigned ink = 0; + if (!g || !g->alpha) { + all = 0; + continue; + } + for (size_t i = 0; i < (size_t)g->w * g->h; i++) + ink += g->alpha[i] > 128; + if (ink < 4) + all = 0; + } + const ck_af_glyph *o = ck_af_glyph_get(&face, 'o'); + for (int y = 0; o && y < o->h; y++) + for (int x = 0; x < o->w; x++) { + int d = (int)o->alpha[y * o->w + x] - (int)o->alpha[y * o->w + (o->w - 1 - x)]; + if (d > 40 || d < -40) + sym = 0; + } + CHECK(all, "font: every printable character rasterizes with ink"); + CHECK(sym, "font: 'o' is left-right symmetric"); + CHECK(ck_af_glyph_get(&face, ' ') != 0 && ck_af_advance(&face, ' ') > 0, "font: space advances"); + CHECK(ck_af_measure(&face, "Hello Humanity.", 15) > ck_af_measure(&face, "Hello", 5), "font: measure grows"); + uint8_t tiny[64]; + ck_af_face small; + ck_af_face_init(&small, 30, 1250, tiny, sizeof tiny); + CHECK(ck_af_glyph_get(&small, 'W') == 0, "font: a full pool refuses instead of overrunning"); + + /* ---- Allen's home at 3840 x 2160, BGRX ---- */ + uint32_t W = 3840, H = 2160; + uint32_t *fb = calloc((size_t)W * H, 4), *copy = malloc((size_t)W * H * 4), *sky = malloc((size_t)W * H * 4); + size_t need = ck_allen_ui_mem_bytes(W, H); + void *mem = malloc(need); + struct pic P = {fb, W, 1}; + CHECK(ck_allen_ui_start(fb, W, H, W, 1, mem, need - 1, 1000000, 0, real_us) == -1, "ui: short memory refused"); + CHECK(ck_allen_ui_start(fb, W, H, W, 2, mem, need, 1000000, 0, real_us) == -1, "ui: unknown pixel format refused"); + CHECK(bare_init(W, H, sky) == 0, "night: the bare sky for the checks"); + uint64_t t_init = real_us(); + CHECK(ck_allen_ui_start(fb, W, H, W, 1, mem, need, 1000000, 0, real_us) == 0, "ui: starts at 3840x2160"); + printf("note: the night made in %llu ms (this host)\n", (unsigned long long)((real_us() - t_init) / 1000)); + CHECK(ck_allen_ui_started() && !ck_allen_ui_on(), "ui: the night has begun; Allen is not awake yet"); + now_us = 0; + run_to(0); + CHECK(count(&P, 0, 0, W, H, LIT) == 0, "night: it opens in the dark"); + run_to(1800); + unsigned early = count(&P, 0, 0, W, H, LIT); + run_to(4200); + unsigned later = count(&P, 0, 0, W, H, LIT); + CHECK(early > 0 && later > early * 2, "night: the stars come out, the brightest first"); + CHECK(stale(fb, copy, W, W, H) == 0, "night: the fading sky is drawn whole"); + if (dir) { + snprintf(path, sizeof path, "%s/night-1-stars.png", dir); + png(path, fb, W, 1, 0, 0, W, H, 2); + } + uint32_t cx = W / 2, cy = H * 40 / 100, R = 236; + run_to(8000); + CHECK(count(&P, cx - 800, cy - 500, 1600, 1000, BLACK) > 2000, "night: two black holes, their shadows"); + CHECK(count(&P, 0, 0, W, H, BLACK) < 200000, "night: and only the holes are black"); + CHECK(stale(fb, copy, W, W, H) < 40, "night: the bent starlight round the holes is redrawn as they move"); + if (dir) { + snprintf(path, sizeof path, "%s/night-2-holes.png", dir); + png(path, fb, W, 1, 0, 0, W, H, 2); + snprintf(path, sizeof path, "%s/night-2-holes-detail.png", dir); + png(path, fb, W, 1, cx - 900, cy - 560, 1800, 1120, 1); + } + run_to(11600); + unsigned before = count(&P, cx - 300, cy - 300, 600, 600, BRIGHT); + run_to(12100); + CHECK(count(&P, cx - 300, cy - 300, 600, 600, BRIGHT) > before + 1500, "night: the merger flashes"); + run_to(12900); + CHECK(stale(fb, copy, W, W, H) < 40, "night: the ripple is redrawn wherever it runs"); + if (dir) { + snprintf(path, sizeof path, "%s/night-3-ripple.png", dir); + png(path, fb, W, 1, 0, 0, W, H, 2); + } + run_to(16500); + CHECK(count(&P, 0, 0, W, H, BLACK) == 0, "night: the last black hole has dissolved"); + CHECK(count(&P, cx - R, cy - R, 2 * R, 2 * R, BRIGHT) > 1000 && count(&P, cx - R, cy - R, 2 * R, 2 * R, VIOLET) > 5000, + "allen: formed, a bright violet mind in the middle"); + uint32_t bx = W / 2 - 720, by = H - 300, bw = 1440, bh = 108; + CHECK(added(&P, sky, 0, by - 40, W, H - by + 40) < 400, "allen: no bar before he is awake"); + CHECK(stale(fb, copy, W, W, H) < 40, "allen: drawn whole as he turns"); + if (dir) { + snprintf(path, sizeof path, "%s/allen-1-formed.png", dir); + png(path, fb, W, 1, 0, 0, W, H, 2); + snprintf(path, sizeof path, "%s/allen-1-formed-detail.png", dir); + png(path, fb, W, 1, cx - 600, cy - 500, 1200, 1000, 1); + } + /* awake: the bar comes up */ + ck_allen_ui_wake("Type goodbye to restart this computer", now_us); + run_to(17800); + CHECK(ck_allen_ui_on(), "ui: on"); + unsigned bar0 = added(&P, sky, bx, by, bw, bh); + CHECK(bar0 > 2500, "bar: up once he is awake, with its hint"); + CHECK(added(&P, sky, 0, by + bh + 10, W, H - by - bh - 10) > 1000, "bar: the footer under the empty bar"); + const char *typed = "Hello Allen"; + for (unsigned i = 1; i <= 11; i++) { + ck_allen_ui_input(typed, i, now_us); + run_to((uint32_t)(now_us / 1000) + 120); + } + CHECK(count(&P, bx, by, bw, bh, BRIGHT) > 500, "bar: what is typed appears in it"); + CHECK(added(&P, sky, 0, by + bh + 10, W, H - by - bh - 10) < 400, "bar: the footer goes while typing"); + if (dir) { + snprintf(path, sizeof path, "%s/allen-2-typing.png", dir); + png(path, fb, W, 1, 0, 0, W, H, 2); + } + /* Enter: the line rises into him, he thinks, then answers under him */ + uint32_t wy = cy + 500 - 90, wh = 5 * 80 + 60; + ck_allen_ui_said(typed, ck_allen_reply(typed), now_us); + uint32_t said = (uint32_t)(now_us / 1000); + run_to(said + 500); + CHECK(stale(fb, copy, W, W, H) < 40, "talk: the rising line and the thoughts are redrawn"); + if (dir) { + snprintf(path, sizeof path, "%s/allen-3-thinking.png", dir); + png(path, fb, W, 1, 0, 0, W, H, 2); + } + run_to(said + 1300); + CHECK(stale(fb, copy, W, W, H) < 40, "talk: the galaxies' shimmer is redrawn while he speaks"); + run_to(said + 2600); + CHECK(added(&P, sky, W / 4, wy, W / 2, wh) > 3000, "talk: Allen's answer appears under him"); + CHECK(count(&P, bx, by, bw, bh, BRIGHT) < 500, "talk: the bar is cleared for the next line"); + if (dir) { + snprintf(path, sizeof path, "%s/allen-4-answer.png", dir); + png(path, fb, W, 1, 0, 0, W, H, 2); + snprintf(path, sizeof path, "%s/allen-4-answer-detail.png", dir); + png(path, fb, W, 1, W / 4, cy - 400, W / 2, 1300, 1); + } + /* left alone: his words fade once read, then the bar; only Allen is left, waiting */ + run_to(said + 24000); + CHECK(added(&P, sky, W / 4, wy, W / 2, wh) < 400, "rest: his words fade once read"); + CHECK(added(&P, sky, 0, by - 40, W, H - by + 40) < 400, "rest: the bar fades when nothing is in use"); + CHECK(count(&P, cx - R, cy - R, 2 * R, 2 * R, BRIGHT) > 1000 && count(&P, cx - R, cy - R, 2 * R, 2 * R, VIOLET) > 5000, + "rest: Allen stays, waiting"); + CHECK(stale(fb, copy, W, W, H) < 40, "rest: nothing is left behind on the screen"); + if (dir) { + snprintf(path, sizeof path, "%s/allen-5-waiting.png", dir); + png(path, fb, W, 1, 0, 0, W, H, 2); + } + ck_allen_ui_input("h", 1, now_us); + run_to((uint32_t)(now_us / 1000) + 400); + CHECK(added(&P, sky, bx, by, bw, bh) > 2500, "rest: a key brings the bar back"); + ck_allen_ui_input("", 0, now_us); + { + /* the notes constellation: shown when a note is saved, then it goes */ + static const char *const notes[] = {"the gate code is 4471", "the garage code is 9012", + "the wifi password is Blue-Fox-88", "the garage door opener is in the truck", + "the dentist is on friday at 10", "the truck needs new tires before the winter"}; + static ck_allen_notes ns; + ns.n = 6; + for (unsigned i = 0; i < 6; i++) + ck_allen_note_set(&ns.note[i], notes[i], 1); + uint8_t ea[32], eb[32]; + unsigned ne = 0; + for (unsigned a = 0; a < 6; a++) /* point 0 is the newest note */ + for (unsigned b = a + 1; b < 6; b++) + if (ck_allen_note_links(&ns.note[5 - a], &ns.note[5 - b])) + ea[ne] = (uint8_t)a, eb[ne++] = (uint8_t)b; + CHECK(ne >= 3, "map: the six notes link (garage, code, truck)"); + uint32_t mx = W * 84 / 100 - 380, my = H * 42 / 100 - 390, mw = 760, mh = 820; + ck_allen_ui_map(6, ea, eb, ne, -1, 0, 6, ne); + run_to((uint32_t)(now_us / 1000) + 1500); + CHECK(added(&P, sky, mx, my, mw, mh) < 400, "map: not shown when nothing was saved"); + ck_allen_ui_map(6, ea, eb, ne, 0, ns.note[5].text, 6, ne); + uint32_t m0 = (uint32_t)(now_us / 1000); + run_to(m0 + 500); + CHECK(stale(fb, copy, W, W, H) < 40, "map: the spark from Allen to the note is redrawn"); + run_to(m0 + 1500); + CHECK(added(&P, sky, mx, my, mw, mh) > 3000, "map: the note just saved glows"); + if (dir) { + snprintf(path, sizeof path, "%s/allen-6-notes.png", dir); + png(path, fb, W, 1, 0, 0, W, H, 2); + snprintf(path, sizeof path, "%s/allen-6-notes-detail.png", dir); + png(path, fb, W, 1, mx, my, mw, mh, 1); + } + ck_allen_ui_map(6, ea, eb, ne, 3, "a very long note that cannot possibly fit on the one line under the map", 6, + ne); + run_to(m0 + 3000); + CHECK(added(&P, sky, mx, my, mw, mh) > 3000, "map: a long label is cut to fit, not overrun"); + run_to(m0 + 15000); + CHECK(added(&P, sky, mx, my, mw, mh) < 400, "map: it goes again after a while"); + } + uint32_t frames, slowest, average; + ck_allen_ui_stats(&frames, &slowest, &average); + printf("note: %u frames at 3840x2160 on one core of this host: average %u us, slowest %u us\n", frames, average, + slowest); + CHECK(frames > 1000, "ui: frames counted"); + + /* ---- 1280 x 800 RGBX with a padded pitch (QEMU's usual mode); then the same with three helper cores ---- */ + uint32_t w2 = 1280, h2 = 800, pitch2 = 1344; + uint32_t *fb2[2]; + size_t need2 = ck_allen_ui_mem_bytes(w2, h2); + void *mem2 = malloc(need2); + for (int run = 0; run < 2; run++) { + fb2[run] = calloc((size_t)pitch2 * h2, 4); + CHECK(ck_allen_ui_start(fb2[run], w2, h2, pitch2, 0, mem2, need2, 1000000, 0, 0) == 0, "ui: starts at 1280x800"); + pthread_t th[3]; + helpers_run = run; + for (int i = 0; run && i < 3; i++) + pthread_create(&th[i], 0, helper, 0); + now_us = 0; + run_to(15000); + ck_allen_ui_wake("footer", now_us); + ck_allen_ui_said("Hello Allen", "Hello Humanity.", now_us); + run_to(18000); + helpers_run = 0; + for (int i = 0; run && i < 3; i++) + pthread_join(th[i], 0); + } + struct pic P2 = {fb2[0], pitch2, 0}; + unsigned padding_clean = 1; + for (uint32_t y = 0; y < h2; y++) + for (uint32_t x = w2; x < pitch2; x++) + padding_clean &= fb2[0][(size_t)y * pitch2 + x] == 0; + uint32_t c2x = w2 / 2, c2y = h2 * 40 / 100; + CHECK(count(&P2, c2x - 60, c2y - 60, 120, 120, VIOLET) > 2000, "ui: RGBX screens get red and blue swapped"); + CHECK(count(&P2, w2 / 4, c2y + 120, w2 / 2, 200, BRIGHT) > 100, "ui: Allen answers at 1280x800"); + CHECK(padding_clean, "ui: nothing written past the visible width"); + CHECK(memcmp(fb2[0], fb2[1], (size_t)pitch2 * h2 * 4) == 0, "ui: three helper cores draw exactly the same frames"); + if (dir) { + snprintf(path, sizeof path, "%s/allen-1280x800.png", dir); + uint32_t *tmp = malloc((size_t)w2 * h2 * 4); + for (uint32_t y = 0; y < h2; y++) + memcpy(tmp + (size_t)y * w2, fb2[0] + (size_t)y * pitch2, w2 * 4); + png(path, tmp, w2, 0, 0, 0, w2, h2, 1); + free(tmp); + } + free(fb), free(copy), free(sky), free(mem), free(fb2[0]), free(fb2[1]), free(mem2); + printf("ALLEN_UI_TEST: %s (%d checks%s)\n", fails ? "FAIL" : "PASS", checks, fails ? ", some failed" : ""); + return fails ? 1 : 0; +} diff --git a/native/kernel/ui/tests/chirp_test.c b/native/kernel/ui/tests/chirp_test.c new file mode 100644 index 00000000..9aaebccb --- /dev/null +++ b/native/kernel/ui/tests/chirp_test.c @@ -0,0 +1,224 @@ +/* chirp_test.c -- host test of the startup sound (ui/chirp.c). Writes the + * whole sound as chirp.wav into the folder given, for a person to listen to. + * Prints CHIRP_TEST: PASS (n checks) or the first failure. */ +#define _POSIX_C_SOURCE 200809L /* fdopen, O_CLOEXEC under -std=c11 */ +#include +#include +#include +#include +#include +#include + +#include "../chirp.h" + +static int checks, failed; + +static void check(int ok, const char *what) +{ + checks++; + if (!ok && !failed) { + failed = 1; + printf("CHIRP_TEST: FAIL %s\n", what); + } +} + +static uint32_t ms(uint32_t t) { return CK_CHIRP_RATE / 1000u * t; } + +/* the pitch heard over [a, b): rising zero crossings over the time */ +static double heard_hz(const int16_t *s, uint32_t a, uint32_t b) +{ + uint32_t first = 0, last = 0, n = 0; + for (uint32_t f = a + 1; f < b; f++) + if (s[2 * (f - 1)] < 0 && s[2 * f] >= 0) { + if (!n) + first = f; + last = f; + n++; + } + return n < 2 ? 0 : (double)(n - 1) * CK_CHIRP_RATE / (last - first); +} + +static void put32(FILE *f, uint32_t v) +{ + for (int i = 0; i < 4; i++) + fputc(v >> 8 * i & 255, f); +} + +static void put16(FILE *f, uint32_t v) +{ + fputc(v & 255, f); + fputc(v >> 8 & 255, f); +} + +static int write_wav(const char *path, const int16_t *s, uint32_t frames) +{ + /* 0644, not fopen's 0666 & ~umask: the sound file must not be world-writable. */ + int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); + FILE *f = fd < 0 ? NULL : fdopen(fd, "wb"); + if (fd >= 0 && !f) + close(fd); + if (!f) + return -1; + uint32_t bytes = frames * 4; + fwrite("RIFF", 1, 4, f); + put32(f, 36 + bytes); + fwrite("WAVEfmt ", 1, 8, f); + put32(f, 16); + put16(f, 1); /* PCM */ + put16(f, 2); + put32(f, CK_CHIRP_RATE); + put32(f, CK_CHIRP_RATE * 4); + put16(f, 4); + put16(f, 16); + fwrite("data", 1, 4, f); + put32(f, bytes); + for (uint32_t i = 0; i < 2 * frames; i++) + put16(f, (uint16_t)s[i]); + return fclose(f); +} + +int main(int argc, char **argv) +{ + const uint32_t N = CK_CHIRP_FRAMES, extra = ms(200); + int16_t *s = calloc(2 * (size_t)(N + extra), sizeof *s), *p = calloc(2 * (size_t)(N + extra), sizeof *p); + if (!s || !p) + return 2; + ck_chirp_fill(s, 0, N + extra); + + /* silence while the stars come out, and after the end */ + int quiet = 1; + for (uint32_t f = 0; f < ms(CK_CHIRP_START_MS - CK_CHIRP_IN_MS); f++) + quiet &= s[2 * f] == 0 && s[2 * f + 1] == 0; + check(quiet, "silent until just before the sweep"); + uint32_t first = 0, last = 0; + for (uint32_t f = 0; f < N; f++) + if (s[2 * f]) { + first = first ? first : f; + last = f; + } + printf("note: sound from %u ms to %u ms (%u ms)\n", first * 1000 / CK_CHIRP_RATE, last * 1000 / CK_CHIRP_RATE, + (last - first) * 1000 / CK_CHIRP_RATE); + check(first && last - first < ms(1000), "a quick blirp: under a second from first sound to last"); + quiet = 1; + for (uint32_t f = N; f < N + extra; f++) + quiet &= s[2 * f] == 0; + check(quiet, "silent after the end"); + check(ck_chirp_level(N - 1) < 2, "faded out by the end"); + + /* both channels the same, nothing past the peak */ + int same = 1, top = 0; + for (uint32_t f = 0; f < N; f++) { + same &= s[2 * f] == s[2 * f + 1]; + int v = abs(s[2 * f]); + top = v > top ? v : top; + } + check(same, "left and right the same"); + check(top <= CK_CHIRP_PEAK && top > CK_CHIRP_PEAK * 98 / 100, "loudest sample at the peak level"); + + /* no jump big enough to click: a sine at TO_HZ moves at most 2 pi f / rate of its height a frame */ + int jump = 0; + for (uint32_t f = 1; f < N + extra; f++) { + int d = abs(s[2 * f] - s[2 * (f - 1)]); + jump = d > jump ? d : jump; + } + printf("note: largest step between frames %d (a %u Hz sine at the peak: %d)\n", jump, CK_CHIRP_TO_HZ, + (int)(6.2832 * CK_CHIRP_TO_HZ / CK_CHIRP_RATE * CK_CHIRP_PEAK)); + check(jump <= (int)(6.2832 * CK_CHIRP_TO_HZ / CK_CHIRP_RATE * CK_CHIRP_PEAK) + 64, "no clicks"); + + /* loudness: comes in, then only rises to the merger, then falls */ + uint32_t a = ck_chirp_level(ms(CK_CHIRP_START_MS - CK_CHIRP_IN_MS)), b = ck_chirp_level(ms(CK_CHIRP_START_MS) - 1); + check(a < 4 && b > 1000, "the sound comes in over CK_CHIRP_IN_MS"); + check(ck_chirp_level(ms(CK_CHIRP_START_MS)) - b < 8, "no step in loudness when the sweep starts"); + int up = 1, down = 1; + for (uint32_t f = ms(CK_CHIRP_START_MS - CK_CHIRP_IN_MS) + 1; f < ms(CK_NIGHT_MERGE_MS); f++) + up &= ck_chirp_level(f) >= ck_chirp_level(f - 1); + for (uint32_t f = ms(CK_NIGHT_MERGE_MS) + 1; f < N; f++) + down &= ck_chirp_level(f) <= ck_chirp_level(f - 1); + check(up, "louder all the way to the merger"); + check(down, "quieter all the way after it"); + check(ck_chirp_level(ms(CK_NIGHT_MERGE_MS) - 1) == CK_CHIRP_PEAK, "the peak at the merger"); + check(ck_chirp_level(ms(CK_NIGHT_MERGE_MS) + ms(60)) < CK_CHIRP_PEAK * 40 / 100, "the ring fades in tens of ms"); + + /* pitch: steady, then only rises, reaching TO_HZ in the last moments */ + check(ck_chirp_hz(ms(CK_CHIRP_START_MS - CK_CHIRP_IN_MS)) == CK_CHIRP_FROM_HZ && + ck_chirp_hz(ms(CK_CHIRP_START_MS)) == CK_CHIRP_FROM_HZ, + "steady pitch while it comes in"); + up = 1; + uint32_t reach = 0; + for (uint32_t f = ms(CK_CHIRP_START_MS) + 1; f < ms(CK_NIGHT_MERGE_MS); f++) { + up &= ck_chirp_hz(f) >= ck_chirp_hz(f - 1); + if (!reach && ck_chirp_hz(f) == CK_CHIRP_TO_HZ) + reach = f; + } + check(up, "pitch only rises in the sweep"); + printf("note: pitch mid-sweep %u Hz, 100 ms before the merger %u Hz; the top reached %u ms before it\n", + ck_chirp_hz(ms(CK_CHIRP_START_MS + CK_CHIRP_RISE_MS / 2)), ck_chirp_hz(ms(CK_NIGHT_MERGE_MS - 100)), (ms(CK_NIGHT_MERGE_MS) - reach) * 1000 / CK_CHIRP_RATE); + check(reach && ms(CK_NIGHT_MERGE_MS) - reach < ms(60), "the top pitch only in the last 60 ms"); + + /* what is heard matches: zero crossings */ + const uint32_t mid = CK_CHIRP_START_MS + CK_CHIRP_RISE_MS / 2; + double h0 = heard_hz(s, ms(CK_CHIRP_START_MS - CK_CHIRP_IN_MS / 2), ms(CK_CHIRP_START_MS)), + h1 = heard_hz(s, ms(mid - 50), ms(mid + 50)), + h2 = heard_hz(s, ms(CK_NIGHT_MERGE_MS), ms(CK_NIGHT_MERGE_MS) + ms(100)); + printf("note: heard %.1f Hz as it comes in, %.1f Hz mid-sweep (asked %u), %.1f Hz in the ring\n", h0, h1, + ck_chirp_hz(ms(mid)), h2); + check(h0 > CK_CHIRP_FROM_HZ - 3.0 && h0 < CK_CHIRP_FROM_HZ + 3.0, "heard pitch as it comes in"); + check(h1 > ck_chirp_hz(ms(mid - 50)) - 2.0 && h1 < ck_chirp_hz(ms(mid + 50)) + 2.0, "heard pitch in the sweep"); + check(h2 > CK_CHIRP_TO_HZ - 5.0 && h2 < CK_CHIRP_TO_HZ + 5.0, "heard pitch in the ring"); + + /* any frame in any order: backwards in odd pieces gives the same sound */ + for (uint32_t end = N + extra; end;) { + uint32_t n = end < 997 ? end : 997; + end -= n; + ck_chirp_fill(p + 2 * (size_t)end, end, n); + } + check(!memcmp(s, p, 4 * (size_t)(N + extra)), "pieces in any order give the same sound"); + + /* the 44.1 kHz copy: where the two rates meet (every 147th frame) it is + * the 48 kHz sample exactly, in the top 16 bits; in between it lies + * between its neighbours; pieces agree; silent after the end */ + const uint32_t N4 = CK_CHIRP_FRAMES_441, extra4 = CK_CHIRP_RATE_441 / 5u; + int32_t *q = calloc(2 * (size_t)(N4 + extra4), sizeof *q), *r = calloc(2 * (size_t)(N4 + extra4), sizeof *r); + if (!q || !r) + return 2; + ck_chirp_fill_441(q, 0, N4 + extra4); + int meet = 1, between = 1, lr = 1, low = 1; + for (uint32_t j = 0; j < N4; j++) { + uint32_t f = j * 160u / 147u; + int32_t a = s[2 * f], b = s[2 * f + 2], v = q[2 * j] >> 16; + if (j % 147u == 0 && q[2 * j] != (int32_t)((uint32_t)a << 16)) + meet = 0; + if (v < (a < b ? a : b) || v > (a < b ? b : a)) + between = 0; + lr &= q[2 * j] == q[2 * j + 1]; + low &= (q[2 * j] & 0xffff) == 0; + } + check(meet, "44.1 kHz copy equals the 48 kHz sound where the rates meet"); + check(between, "44.1 kHz copy lies between its 48 kHz neighbours"); + check(lr && low, "44.1 kHz copy: left equals right, sample in the top 16 bits"); + for (uint32_t end = N4 + extra4; end;) { + uint32_t n = end < 1009 ? end : 1009; + end -= n; + ck_chirp_fill_441(r + 2 * (size_t)end, end, n); + } + check(!memcmp(q, r, 8 * (size_t)(N4 + extra4)), "44.1 kHz pieces in any order give the same sound"); + quiet = 1; + for (uint32_t j = N4 + 2; j < N4 + extra4; j++) + quiet &= q[2 * j] == 0; + check(quiet, "44.1 kHz copy silent after the end"); + free(q); + free(r); + + if (argc > 1) { + char path[4096]; + snprintf(path, sizeof path, "%s/chirp.wav", argv[1]); + check(write_wav(path, s, N) == 0, "wav written"); + printf("note: wrote %s (%u frames, %u ms)\n", path, N, N * 1000 / CK_CHIRP_RATE); + } + free(s); + free(p); + if (failed) + return 1; + printf("CHIRP_TEST: PASS (%d checks)\n", checks); + return 0; +} diff --git a/native/kernel/x86/ahci_x86.c b/native/kernel/x86/ahci_x86.c index 953ed13b..8da80653 100644 --- a/native/kernel/x86/ahci_x86.c +++ b/native/kernel/x86/ahci_x86.c @@ -15,8 +15,9 @@ */ /* ahci_x86.c -- AIENOS-IMAC-KERNEL-1: the SATA disks behind an AHCI - * controller, READ-ONLY, for the 2017 iMac (Intel 8086:a102, the 1 TB hard - * disk half of the Fusion Drive) and QEMU q35 (ICH9). + * controller for the 2017 iMac (Intel 8086:a102, the 1 TB hard disk half of + * the Fusion Drive) and QEMU q35 (ICH9). Read-only unless a write range is + * opened. * * Each controller is driven polled, * with interrupts off: AHCI mode on, no controller or port reset (the links @@ -25,11 +26,15 @@ * kernel owns, the engine started again. The PCI walk that finds the * controllers is pci_x86.c. * - * Only two ATA commands exist in this file: IDENTIFY DEVICE (0xEC) and READ - * DMA EXT (0x25). issue() refuses every other opcode, and the disk_dev the - * GPT checker (dev/disk_part.c) reads through has a write hook that always - * refuses: nothing here can change a disk. The IDENTIFY serial number words - * are never read. QEMU runs of this path qualify nothing physical. */ + * Four ATA commands exist in this file: IDENTIFY DEVICE (0xEC), READ DMA + * EXT (0x25), WRITE DMA EXT (0x35) and FLUSH CACHE EXT (0xEA); issue() + * refuses every other opcode. Writes and flushes are refused unless the + * transfer lies wholly inside a write range opened with ck_x86_ahci_allow, + * and only x86/memory_x86.c opens ranges (the Makefile checks): the GPT + * blocks of the approved hard disk while Allen's partition is added, then + * the two memory copies inside that partition. A disk with no open range + * cannot be changed. The IDENTIFY serial number words are never read. QEMU + * runs of this path qualify nothing physical. */ #include "../core/ck_internal.h" #include "../mm/frames.h" #include "disk.h" @@ -77,6 +82,9 @@ #define ATA_IDENTIFY 0xec #define ATA_READ_DMA_EXT 0x25 +#define ATA_WRITE_DMA_EXT 0x35 +#define ATA_FLUSH_CACHE_EXT 0xea +#define AHCI_MAX_ALLOW 3u /* pci_x86.c: sector 0 and the GPT check of one disk, printed. */ void ck_x86_disk_report(const char *tag, unsigned ctrl, unsigned index, const disk_dev *dev); @@ -86,6 +94,9 @@ struct ahci_disk { uint8_t *cl, *fis, *ct, *bounce; /* kernel frames the controller reads and writes */ uint64_t tsc_hz; unsigned ctrl, index; + char model[41]; + uint64_t allow_first[AHCI_MAX_ALLOW], allow_last[AHCI_MAX_ALLOW]; /* open write ranges, inclusive */ + unsigned nallow; disk_dev dev; }; @@ -124,18 +135,22 @@ static int alloc_low(struct ck_frames *f, uint64_t pages, int low4g, uint8_t **o static uint64_t pa_of(const void *p) { return (uint64_t)(uintptr_t)p; } -/* One command in slot 0, polled. Only IDENTIFY DEVICE and READ DMA EXT. */ +/* One command in slot 0, polled. Only IDENTIFY DEVICE, READ DMA EXT, WRITE + * DMA EXT (the data already in the bounce buffer) and FLUSH CACHE EXT (no + * data, bytes 0). */ static int issue(struct ahci_disk *d, uint8_t cmd, uint64_t lba, uint32_t count, uint32_t bytes) { - if (cmd != ATA_IDENTIFY && cmd != ATA_READ_DMA_EXT) + int rw = cmd == ATA_READ_DMA_EXT || cmd == ATA_WRITE_DMA_EXT; + if (cmd != ATA_IDENTIFY && !rw && cmd != ATA_FLUSH_CACHE_EXT) return DISK_EARG; - if (!bytes || bytes > BOUNCE_BYTES) + if ((cmd == ATA_FLUSH_CACHE_EXT) != !bytes || bytes > BOUNCE_BYTES) return DISK_EARG; volatile uint8_t *p = d->port; if (wait_reg(p, P_TFD, TFD_BSY | TFD_DRQ, 0, 1000)) return DISK_ESTATE; uint32_t *hdr = (uint32_t *)d->cl; - hdr[0] = 5u | 1u << 16; /* CFL 5 dwords, read (W = 0), one PRD */ + /* CFL 5 dwords; W (bit 6) for a write; one PRD, none for a flush */ + hdr[0] = 5u | (cmd == ATA_WRITE_DMA_EXT ? 1u << 6 : 0u) | (bytes ? 1u << 16 : 0u); hdr[1] = 0; hdr[2] = (uint32_t)pa_of(d->ct); hdr[3] = (uint32_t)(pa_of(d->ct) >> 32); @@ -144,7 +159,7 @@ static int issue(struct ahci_disk *d, uint8_t cmd, uint64_t lba, uint32_t count, f[0] = 0x27; /* host to device register FIS */ f[1] = 0x80; /* command */ f[2] = cmd; - if (cmd == ATA_READ_DMA_EXT) { + if (rw) { f[4] = (uint8_t)lba; f[5] = (uint8_t)(lba >> 8); f[6] = (uint8_t)(lba >> 16); @@ -159,11 +174,12 @@ static int issue(struct ahci_disk *d, uint8_t cmd, uint64_t lba, uint32_t count, prd[0] = (uint32_t)pa_of(d->bounce); prd[1] = (uint32_t)(pa_of(d->bounce) >> 32); prd[2] = 0; - prd[3] = bytes - 1u; + prd[3] = bytes ? bytes - 1u : 0u; __asm__ volatile("mfence" ::: "memory"); mw(p, P_IS, 0xffffffffu); mw(p, P_CI, 1); - uint64_t t0 = ck_rdtsc(), lim = d->tsc_hz * 15; /* 15 s: a spun-down hard disk spins up first */ + uint64_t t0 = ck_rdtsc(), lim = d->tsc_hz * 30; /* a spun-down hard disk spins up first; a flush + * may also wait for the cache to reach the platters */ for (;;) { if (mr(p, P_IS) & IS_TFES) return DISK_EIO; @@ -189,16 +205,37 @@ static int ahci_read(void *ctx, uint64_t lba, uint32_t count, uint8_t *buf) return rc; } +/* Inside one open write range, as a whole. */ +static int allowed(const struct ahci_disk *d, uint64_t lba, uint32_t count) +{ + uint64_t last = lba + count - 1u; + if (!count || last < lba) + return 0; + for (unsigned i = 0; i < d->nallow; i++) + if (lba >= d->allow_first[i] && last <= d->allow_last[i]) + return 1; + return 0; +} + static int ahci_write(void *ctx, uint64_t lba, uint32_t count, const uint8_t *buf) { - (void)ctx, (void)lba, (void)count, (void)buf; - return DISK_ESTATE; /* read-only driver */ + struct ahci_disk *d = ctx; + if (!allowed(d, lba, count)) { + ck_printf("ahci_write: ctrl=%u disk=%u lba=%llu count=%u refused: outside the open write ranges\n", d->ctrl, + d->index, (unsigned long long)lba, count); + return DISK_ERANGE; + } + uint32_t bytes = count * d->dev.block_size; + memcpy(d->bounce, buf, bytes); + return issue(d, ATA_WRITE_DMA_EXT, lba, count, bytes); } static int ahci_flush(void *ctx) { - (void)ctx; - return DISK_ESTATE; + struct ahci_disk *d = ctx; + if (!d->nallow) + return DISK_ESTATE; /* nothing could have been written */ + return issue(d, ATA_FLUSH_CACHE_EXT, 0, 0, 0); } static void id_string(const uint16_t *id, unsigned w0, unsigned words, char *out) @@ -283,6 +320,8 @@ static void port_bringup(unsigned ctrl, volatile uint8_t *hba, unsigned pn, stru const uint16_t *id = (const uint16_t *)d->bounce; char model[41]; id_string(id, 27, 20, model); /* words 10..19 (serial number) are never read */ + memcpy(d->model, model, sizeof d->model); + d->nallow = 0; uint64_t sectors = 0; int lba48 = (id[83] & (1u << 10)) != 0; if (lba48) @@ -333,3 +372,35 @@ void ck_x86_ahci_start(unsigned ctrl, uint64_t abar, struct ck_frames *fr, uint6 } unsigned ck_x86_ahci_disks(void) { return ndisks; } + +const disk_dev *ck_x86_ahci_dev(unsigned index, const char **model) +{ + if (index >= ndisks) + return 0; + if (model) + *model = disks[index].model; + return &disks[index].dev; +} + +int ck_x86_ahci_allow(unsigned index, uint64_t first, uint64_t last) +{ + if (index >= ndisks) + return -1; + struct ahci_disk *d = &disks[index]; + if (d->nallow == AHCI_MAX_ALLOW || first == 0 || first > last || last >= d->dev.block_count) + return -1; /* LBA 0 (the protective MBR) is never opened */ + d->allow_first[d->nallow] = first; + d->allow_last[d->nallow] = last; + d->nallow++; + ck_printf("ahci_disk: ctrl=%u disk=%u writes allowed lba=%llu..%llu\n", d->ctrl, index, + (unsigned long long)first, (unsigned long long)last); + return 0; +} + +void ck_x86_ahci_allow_none(unsigned index) +{ + if (index < ndisks && disks[index].nallow) { + disks[index].nallow = 0; + ck_printf("ahci_disk: ctrl=%u disk=%u write ranges closed\n", disks[index].ctrl, index); + } +} diff --git a/native/kernel/x86/console_x86.c b/native/kernel/x86/console_x86.c index 8d5b2d31..bef4f95d 100644 --- a/native/kernel/x86/console_x86.c +++ b/native/kernel/x86/console_x86.c @@ -14,7 +14,7 @@ * limitations under the License. */ -/* console_x86.c -- ck_puts/ck_printf for AIENOS-IMAC-KERNEL-0. +/* console_x86.c -- ck_puts/ck_printf for AIENOS-KERNEL-0. * * Three sinks. COM1 (I/O port 0x3f8) only when a 16550 answers there (the * scratch register keeps a written value): QEMU has one, the 2017 iMac has @@ -25,7 +25,9 @@ * ExitBootServices (UEFI ConOut is not used: on a Mac it is invisible unless * the firmware is switched to text mode); report_x86.c also sends that copy * over the network. '\n' goes to COM1 as CR LF. A fault - * while drawing turns the screen off for good. */ + * while drawing turns the screen off for good. While the startup picture + * plays (ck_x86_console_fb_hold) the screen is known but the text stays off + * it; ck_x86_console_fb_show brings the text back (a panic always does). */ #include "../core/ck_internal.h" #include "../core/fbcon.h" #include "x86.h" @@ -36,6 +38,9 @@ static int com1_on; static struct ck_fbcon fb; static int fb_on, fb_busy; +static int fb_held; /* the screen is known but the text stays off it (the startup picture) */ +static void (*held_tick)(void); +static int tick_busy; static char log_buf[CK_X86_LOG_BYTES]; static size_t log_len; @@ -76,6 +81,11 @@ static void write_n(const char *s, size_t n) memcpy(log_buf + log_len, s, k); log_len += k; fb_write(s, n); + if (fb_held && held_tick && !tick_busy) { + tick_busy = 1; /* a fault while drawing prints, and must not draw again */ + held_tick(); + tick_busy = 0; + } if (!com1_on) return; for (size_t i = 0; i < n; i++) { @@ -88,16 +98,56 @@ static void write_n(const char *s, size_t n) int ck_x86_console_fb_on(volatile void *base, uint32_t width, uint32_t height, uint32_t pitch, uint32_t format, uint32_t *scale, uint32_t *cols, uint32_t *rows) { - if (ck_fbcon_setup(&fb, base, width, height, pitch, format) != 0) - return -1; - fb_on = 1; - fb_write(log_buf, log_len); + if (held_tick) { + if (ck_fbcon_attach(&fb, base, width, height, pitch, format) != 0) + return -1; + fb_held = 1; + } else { + if (ck_fbcon_setup(&fb, base, width, height, pitch, format) != 0) + return -1; + fb_on = 1; + fb_write(log_buf, log_len); + } *scale = fb.scale; *cols = fb.cols; *rows = fb.rows; return 0; } +int ck_x86_console_fb_get(volatile uint32_t **px, uint32_t *width, uint32_t *height, uint32_t *pitch, + uint32_t *format) +{ + if (!(fb_on || fb_held) || fb_busy) + return -1; + *px = fb.px; + *width = fb.width; + *height = fb.height; + *pitch = fb.pitch; + *format = fb.format; + return 0; +} + +void ck_x86_console_fb_off(void) +{ + fb_on = fb_held = 0; /* text keeps going to the RAM copy and COM1 */ + held_tick = 0; +} + +void ck_x86_console_fb_hold(void (*tick)(void)) { held_tick = tick; } + +void ck_x86_console_fb_show(void) +{ + if (!fb_held || fb_busy) + return; + fb_held = 0; + held_tick = 0; + fb_on = 1; + fb_busy = 1; + ck_fbcon_clear(&fb); + fb_busy = 0; + fb_write(log_buf, log_len); +} + const char *ck_x86_console_log(size_t *len) { *len = log_len; diff --git a/native/kernel/x86/efi_x86.c b/native/kernel/x86/efi_x86.c index 73b3ab03..3a994d93 100644 --- a/native/kernel/x86/efi_x86.c +++ b/native/kernel/x86/efi_x86.c @@ -14,7 +14,7 @@ * limitations under the License. */ -/* efi_x86.c -- UEFI stub of AIENOS-IMAC-KERNEL-0 (x86_64): the same job as +/* efi_x86.c -- UEFI stub of AIENOS-KERNEL-0 (x86_64): the same job as * native/boot/efi_main.c does for the AArch64 kernel, on the same CHANDOF3 * record (handoff.h), so core/handoff_check.c checks it unchanged. * @@ -66,7 +66,7 @@ EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *st) if (guid_eq(&st->ConfigurationTable[i].VendorGuid, &acpi20)) h->rsdp = (uint64_t)(uintptr_t)st->ConfigurationTable[i].VendorTable; - ck_puts("AIENOS-IMAC-KERNEL-0\n"); + ck_puts("AIENOS-KERNEL-0\n"); ck_printf("report_kind: pre_exit\naienos_commit: %s\n", ck_commit()); ck_puts("kernel_impl: c (native/kernel/x86, x86_64)\n"); char v[80]; diff --git a/native/kernel/x86/hda_x86.c b/native/kernel/x86/hda_x86.c new file mode 100644 index 00000000..4e46194f --- /dev/null +++ b/native/kernel/x86/hda_x86.c @@ -0,0 +1,838 @@ +/* hda_x86.c -- the sound controller (Intel High Definition Audio): plays the + * night's chirp (ui/chirp.c) through the speakers, in step with the sky. + * + * Per controller: stop any DMA the firmware left running (a startup chime may + * leave the command rings or a stream running into memory the kernel now + * owns), then reset it: STATESTS cleared, GCTL.CRST held at 0 for 1 ms, set + * to 1, then 1 ms for the codecs to ask for an address before STATESTS is + * read (Linux's reset_link: at least 100 us in reset, 1 ms after). Codecs are + * then spoken to through the command rings (CORB out, RIRB back, 256 entries + * each in one page, polled; Linux's snd_hdac_bus_init_cmd_io); the immediate + * command registers are the fallback, and they went unanswered on the first + * real machine. + * + * Each codec's audio function group goes onto the report, one line per + * widget, and is searched for output pins (speaker first, then line out and + * headphone; never digital, never "no connection") with a path back through + * mixers and selectors to a converter (DAC). On the first controller with + * such a path, every widget on every path is powered (D0), routed, unmuted at + * 0 dB, the pins driven and their external amplifiers switched on (EAPD; on + * Apple boards also every codec GPIO, which Linux's Cirrus fixups use as the + * speaker and headphone amplifier enables); Cirrus CS4206/7/8 get their + * vendor set-up words (Linux cs420x.c); a Cirrus CS8409 bridge on an Apple + * board gets its own set-up instead (cs8409_apple, below). Then the first + * output stream plays the chirp from the night's current moment, 16-bit + * stereo at 48 kHz (44.1 kHz 24-bit behind a CS8409), and HDA_TAIL_MS of + * silence after it. A stream loops by design (the controller + * has no play-once), so ck_x86_hda_step stops it once the chirp is over. + * Register offsets and bits: Linux's hda_register.h and hda_verbs.h; the + * Intel PCI settings are in pci_x86.c (docs-read records). */ +#include "../core/ck_internal.h" +#include "../mm/frames.h" +#include "../ui/chirp.h" +#include "x86.h" + +#define GCAP 0x00 +#define VMIN 0x02 +#define VMAJ 0x03 +#define GCTL 0x08 +#define STATESTS 0x0e +#define CORBLBASE 0x40 +#define CORBUBASE 0x44 +#define CORBWP 0x48 +#define CORBRP 0x4a +#define CORBCTL 0x4c +#define CORBSIZE 0x4e +#define RIRBLBASE 0x50 +#define RIRBUBASE 0x54 +#define RIRBWP 0x58 +#define RINTCNT 0x5a +#define RIRBCTL 0x5c +#define RIRBSTS 0x5d +#define RIRBSIZE 0x5e +#define IC 0x60 +#define IR 0x64 +#define IRS 0x68 +#define IRS_BUSY 1u +#define IRS_VALID 2u +#define RING_RST 0x8000u /* CORBRP and RIRBWP: reset the pointer */ +#define SD0 0x80 /* stream descriptors, 0x20 apart: input, output, then bidirectional */ +#define SD_STS 0x03 +#define SD_LPIB 0x04 +#define SD_CBL 0x08 +#define SD_LVI 0x0c +#define SD_FMT 0x12 +#define SD_BDLPL 0x18 +#define SD_BDLPU 0x1c +#define SRST 1u /* SD_CTL: stream in reset */ +#define RUN 2u /* CORBCTL, RIRBCTL and SD_CTL: the DMA engine runs */ + +/* codec verbs (12-bit verbs carry 8 bits; the 4-bit ones 0x2-0x5 carry 16) */ +#define V_FORMAT 0x200 +#define V_AMP 0x300 +#define V_PROC_COEF 0x400 +#define V_COEF_INDEX 0x500 +#define V_CONNECT_SEL 0x701 +#define V_PROC_STATE 0x703 +#define V_POWER 0x705 +#define V_STREAM 0x706 +#define V_PIN_CTL 0x707 +#define V_EAPD 0x70c +#define V_GPIO_DATA 0x715 +#define V_GPIO_MASK 0x716 +#define V_GPIO_DIR 0x717 +#define V_PARAM 0xf00 +#define V_CONN_LIST 0xf02 +#define V_GET_POWER 0xf05 +#define V_GET_EAPD 0xf0c +#define V_CONFIG 0xf1c +#define V_SUBSYSTEM 0xf20 +#define P_VENDOR 0x00 +#define P_SUBSYSTEM 0x01 +#define P_REV 0x02 +#define P_NODES 0x04 +#define P_FUNC 0x05 +#define P_WCAPS 0x09 +#define P_PINCAP 0x0c +#define P_AMP_IN 0x0d +#define P_CONN_LEN 0x0e +#define P_GPIO 0x11 +#define P_AMP_OUT 0x12 +#define W_AUD_OUT 0 +#define W_MIX 2 +#define W_SEL 3 +#define W_PIN 4 +#define WC_IN_AMP (1u << 1) +#define WC_OUT_AMP (1u << 2) +#define WC_AMP_OVRD (1u << 3) +#define WC_CONN_LIST (1u << 8) +#define WC_DIGITAL (1u << 9) +#define WC_POWER (1u << 10) +#define PC_HP_DRV (1u << 3) +#define PC_OUT (1u << 4) +#define PC_EAPD (1u << 16) +#define FMT_48K_16_STEREO 0x0011u +#define TAG 1u /* the stream's tag; the converters listen for it */ +#define CHUNK 65536u /* bytes per buffer descriptor */ +#define HDA_TAIL_MS 8000u /* silence after the chirp, so a late stop never replays it */ +#define MAX_NID 128u +#define MAX_PATH 6u +#define MAX_PINS 8u + +static volatile uint8_t *g_bar; +static uint64_t g_hz; +static volatile uint32_t *corb; /* 256 commands */ +static volatile uint32_t *rirb; /* 256 answers of two words: the answer, then which codec */ +static unsigned corb_wp, rirb_rp, rings; +static unsigned g_fmt; /* the stream format: FMT_48K_16_STEREO unless a codec takes only another */ + +/* the stream once playing: ck_x86_hda_step stops it */ +static volatile uint8_t *play_bar; +static unsigned play_sd; +static uint64_t play_t0; + +static uint8_t r8(unsigned o) { return g_bar[o]; } +static uint16_t r16(unsigned o) { return *(volatile uint16_t *)(g_bar + o); } +static uint32_t r32(unsigned o) { return *(volatile uint32_t *)(g_bar + o); } +static void w8(unsigned o, uint8_t v) { g_bar[o] = v; } +static void w16(unsigned o, uint16_t v) { *(volatile uint16_t *)(g_bar + o) = v; } +static void w32(unsigned o, uint32_t v) { *(volatile uint32_t *)(g_bar + o) = v; } + +static void spin_us(unsigned us) +{ + uint64_t t0 = ck_rdtsc(), n = g_hz / 1000000 * us; + while (ck_rdtsc() - t0 < n) + ck_pause(); +} + +/* waits up to ms for (reg & mask) == want; 0 when it got there */ +static int wait8(unsigned o, uint8_t mask, uint8_t want, unsigned ms) +{ + uint64_t t0 = ck_rdtsc(); + while ((r8(o) & mask) != want) + if (ck_rdtsc() - t0 > g_hz / 1000 * ms) + return -1; + else + ck_pause(); + return 0; +} +static int wait16(unsigned o, uint16_t mask, uint16_t want, unsigned ms) +{ + uint64_t t0 = ck_rdtsc(); + while ((r16(o) & mask) != want) + if (ck_rdtsc() - t0 > g_hz / 1000 * ms) + return -1; + else + ck_pause(); + return 0; +} + +/* Writes the cache lines over [p, p + n) back to memory and drops them, so + * the controller reads what was written and the CPU then reads what the + * controller wrote, whether or not its DMA is snooped. */ +static void flush(const volatile void *p, size_t n) +{ + uintptr_t a = (uintptr_t)p & ~(uintptr_t)63, e = (uintptr_t)p + n; + __asm__ volatile("mfence" ::: "memory"); + for (; a < e; a += 64) + __asm__ volatile("clflush (%0)" ::"r"(a) : "memory"); + __asm__ volatile("mfence" ::: "memory"); +} + +static int imm_cmd(uint32_t c, uint32_t *out) +{ + if (wait16(IRS, IRS_BUSY, 0, 10)) + return -1; + w16(IRS, (uint16_t)(r16(IRS) | IRS_VALID)); /* clears an old answer */ + w32(IC, c); + w16(IRS, (uint16_t)(r16(IRS) | IRS_BUSY)); + if (wait16(IRS, IRS_VALID, IRS_VALID, 10)) + return -1; + *out = r32(IR); + return 0; +} + +static int ring_cmd(uint32_t c, uint32_t *out) +{ + corb_wp = (corb_wp + 1) & 255u; + corb[corb_wp] = c; + flush(&corb[corb_wp], 4); + w16(CORBWP, (uint16_t)corb_wp); + uint64_t t0 = ck_rdtsc(); + for (;;) { + if ((r16(RIRBWP) & 255u) != rirb_rp) { + rirb_rp = (rirb_rp + 1) & 255u; + flush(&rirb[2 * rirb_rp], 8); + uint32_t v = rirb[2 * rirb_rp], ext = rirb[2 * rirb_rp + 1]; + w8(RIRBSTS, 5); /* response and overrun flags cleared: the controller may go on */ + if (ext & 0x10u) /* unsolicited (none are asked for) */ + continue; + *out = v; + return 0; + } + if (ck_rdtsc() - t0 > g_hz / 1000 * 50) { + rirb_rp = r16(RIRBWP) & 255u; /* a late answer is not taken for the next one */ + return -1; + } + ck_pause(); + } +} + +/* one codec command, tried three times; 0 with *out set (when given), or -1 */ +static int verb(unsigned a, unsigned nid, unsigned v, unsigned payload, uint32_t *out) +{ + uint32_t c = (uint32_t)a << 28 | (uint32_t)nid << 20 | (uint32_t)v << 8 | payload, dummy; + for (int k = 0; k < 3; k++) + if (!(rings ? ring_cmd(c, out ? out : &dummy) : imm_cmd(c, out ? out : &dummy))) + return 0; + return -1; +} +static uint32_t param(unsigned a, unsigned nid, unsigned p) +{ + uint32_t v = 0; + return verb(a, nid, V_PARAM, p, &v) ? 0 : v; +} + +/* The rings in one page from fr: CORB at its start, RIRB at +2048, 256 + * entries each (Linux's order and checks). 0 when both run. */ +static int rings_start(struct ck_frames *fr, unsigned ctrl) +{ + uint64_t pa; + if (!fr || ck_frames_alloc(fr, 1, CK_PAGE, &pa)) + return -1; + memset((void *)(uintptr_t)pa, 0, CK_PAGE); + flush((void *)(uintptr_t)pa, CK_PAGE); + corb = (volatile uint32_t *)(uintptr_t)pa; + rirb = (volatile uint32_t *)(uintptr_t)(pa + 2048); + w32(CORBLBASE, (uint32_t)pa); + w32(CORBUBASE, (uint32_t)(pa >> 32)); + w8(CORBSIZE, 0x02); + w16(CORBWP, 0); + w16(CORBRP, RING_RST); + int bad = wait16(CORBRP, RING_RST, RING_RST, 10); + w16(CORBRP, 0); + bad |= wait16(CORBRP, RING_RST, 0, 10); + w8(CORBCTL, RUN); + w32(RIRBLBASE, (uint32_t)(pa + 2048)); + w32(RIRBUBASE, (uint32_t)((pa + 2048) >> 32)); + w8(RIRBSIZE, 0x02); + w16(RIRBWP, RING_RST); + w16(RINTCNT, 1); + w8(RIRBCTL, RUN | 1u); /* with the response flag (bit 0), cleared after each answer: Linux does the same, and + a controller may hold the next command until it is cleared; no interrupt is + delivered (INTCTL stays 0) */ + bad |= wait8(CORBCTL, RUN, RUN, 10) | wait8(RIRBCTL, RUN, RUN, 10); + corb_wp = r16(CORBWP) & 255u; + rirb_rp = r16(RIRBWP) & 255u; + if (bad) { + w8(CORBCTL, 0); + w8(RIRBCTL, 0); + ck_printf("sound: ctrl=%u command rings did not start; immediate commands\n", ctrl); + return -1; + } + return 0; +} + +/* ---- the codec's map ---- */ +struct wid { + uint32_t caps, pincap, cfg, amp_out, amp_in; + uint8_t type, nconn, conn[16]; +}; +static struct wid W[MAX_NID]; +static uint8_t path[MAX_PATH], pick[MAX_PATH]; +static unsigned plen; + +static void read_conns(unsigned a, unsigned nid, struct wid *x) +{ + uint32_t len = param(a, nid, P_CONN_LEN), n = len & 0x7fu, wide = len >> 7 & 1u, per = wide ? 2 : 4; + unsigned last = 0; + x->nconn = 0; + for (uint32_t i = 0; i < n && x->nconn < 16; i += per) { + uint32_t v; + if (verb(a, nid, V_CONN_LIST, i, &v)) + return; + for (uint32_t k = 0; k < per && i + k < n && x->nconn < 16; k++) { + unsigned e = wide ? v >> (16 * k) & 0xffffu : v >> (8 * k) & 0xffu; + unsigned range = wide ? e >> 15 : e >> 7, id = wide ? e & 0x7fffu : e & 0x7fu; + if (range && last) /* "every node from the last one to this one" */ + for (unsigned m = last + 1; m <= id && x->nconn < 16; m++) + x->conn[x->nconn++] = (uint8_t)m; + else + x->conn[x->nconn++] = (uint8_t)id; + last = id; + } + } +} + +static const char *type_name(unsigned t) +{ + static const char *const n[16] = {"dac", "adc", "mix", "sel", "pin", "power", "knob", "beep", + "t8", "t9", "t10", "t11", "t12", "t13", "t14", "vendor"}; + return n[t & 15u]; +} + +/* One line per widget on the report: what it is, and for pins where it goes. */ +static void map_widget(unsigned a, unsigned nid, const struct wid *x) +{ + char line[200]; + int n = ck_snprintf(line, sizeof line, "sound: codec=%u w=0x%02x %s caps=0x%08x", a, nid, type_name(x->type), + x->caps); + if (x->type == W_PIN) + n += ck_snprintf(line + n, sizeof line - n, " pincap=0x%08x cfg=0x%08x", x->pincap, x->cfg); + if (x->caps & WC_AMP_OVRD) + n += ck_snprintf(line + n, sizeof line - n, " amp_out=0x%08x amp_in=0x%08x", x->amp_out, x->amp_in); + for (unsigned k = 0; k < x->nconn && n < (int)sizeof line - 8; k++) + n += ck_snprintf(line + n, sizeof line - n, k ? ",0x%02x" : " conn=0x%02x", x->conn[k]); + ck_printf("%s\n", line); +} + +/* depth-first from a pin back to a converter, through mixers and selectors */ +static int find_dac(unsigned nid, unsigned depth) +{ + const struct wid *x = &W[nid]; + path[depth] = (uint8_t)nid; + if (depth && x->type == W_AUD_OUT && !(x->caps & WC_DIGITAL)) { + plen = depth + 1; + return 1; + } + if (depth + 1 >= MAX_PATH || (depth && x->type != W_MIX && x->type != W_SEL)) + return 0; + for (unsigned k = 0; k < x->nconn; k++) { + unsigned c = x->conn[k]; + if (c >= MAX_NID || !W[c].caps) + continue; + pick[depth] = (uint8_t)k; + if (find_dac(c, depth + 1)) + return 1; + } + return 0; +} + +/* gain at 0 dB (the amp's offset), limited to its steps */ +static unsigned zero_db(uint32_t amp) +{ + unsigned off = amp & 0x7fu, steps = amp >> 8 & 0x7fu; + return off > steps ? steps : off; +} + +/* Every widget on the found path made ready to carry the stream. */ +static void open_path(unsigned a, unsigned dev, uint32_t afg_out, uint32_t afg_in) +{ + for (unsigned i = 0; i < plen; i++) { + unsigned nid = path[i]; + const struct wid *x = &W[nid]; + uint32_t ao = x->caps & WC_AMP_OVRD ? x->amp_out : afg_out, ai = x->caps & WC_AMP_OVRD ? x->amp_in : afg_in; + if (x->caps & WC_POWER) + verb(a, nid, V_POWER, 0, 0); + if (i + 1 < plen && x->type != W_MIX && x->nconn > 1) + verb(a, nid, V_CONNECT_SEL, pick[i], 0); + if (i + 1 < plen && x->type == W_MIX && (x->caps & WC_IN_AMP)) + verb(a, nid, V_AMP, 0x7000u | (unsigned)pick[i] << 8 | zero_db(ai), 0); /* input, both sides */ + if (x->caps & WC_OUT_AMP) + verb(a, nid, V_AMP, 0xb000u | zero_db(ao), 0); /* output, both sides */ + if (x->type == W_PIN) { + verb(a, nid, V_PIN_CTL, 0x40u | (dev == 2 && (x->pincap & PC_HP_DRV) ? 0x80u : 0), 0); + uint32_t e = 0; + if ((x->pincap & PC_EAPD) && !verb(a, nid, V_GET_EAPD, 0, &e)) + verb(a, nid, V_EAPD, (e & 0xffu) | 0x02u, 0); + } + if (x->type == W_AUD_OUT) { + verb(a, nid, V_FORMAT, FMT_48K_16_STEREO, 0); + verb(a, nid, V_STREAM, TAG << 4, 0); + } + } +} + +/* Cirrus set-up words (Linux cs420x.c cs_errata_init_verbs, cs_coef_init_verbs, + * cs4208_coef_init_verbs): node, verb, payload. */ +static const uint16_t cs420x_words[][3] = { + {0x11, V_PROC_STATE, 1}, {0x11, V_COEF_INDEX, 0x08}, {0x11, V_PROC_COEF, 0x9999}, {0x11, V_COEF_INDEX, 0x17}, + {0x11, V_PROC_COEF, 0xa412}, {0x11, V_COEF_INDEX, 0x01}, {0x11, V_PROC_COEF, 0x0009}, {0x07, V_POWER, 0}, + {0x08, V_POWER, 0}, {0x11, V_COEF_INDEX, 0x17}, {0x11, V_PROC_COEF, 0x2412}, {0x11, V_COEF_INDEX, 0x08}, + {0x11, V_PROC_COEF, 0}, {0x11, V_COEF_INDEX, 0x01}, {0x11, V_PROC_COEF, 0x0008}, {0x11, V_PROC_STATE, 0}, + {0x11, V_PROC_STATE, 1}, {0x11, V_COEF_INDEX, 0x03}, {0x11, V_PROC_COEF, 0x146a}, {0x11, V_COEF_INDEX, 0x02}, + {0x11, V_PROC_COEF, 0x000a}, {0x11, V_COEF_INDEX, 0x04}, {0x11, V_PROC_COEF, 0x0007}, +}; +static const uint16_t cs4208_words[][3] = { + {0x24, V_PROC_STATE, 1}, {0x24, V_COEF_INDEX, 0x33}, {0x24, V_PROC_COEF, 0x0001}, + {0x24, V_COEF_INDEX, 0x34}, {0x24, V_PROC_COEF, 0x1c01}, +}; + +/* ---- Cirrus CS8409 on Apple boards ---- + * The CS8409 is a bridge: its converters feed a TDM bus (several channels + * time-shared on one wire) to four TAS576x-family speaker amplifiers, which it + * sets up over its own I2C bus (a two-wire link to small chips). Its + * converters leave nothing on the pins without that, so the generic path + * above stays silent. The sequence is the one davidjo/snd_hda_macbookpro + * replays from macOS for subsystem 106b:1000 (cirrus_apple.h -> new84 -> + * real84; boot84 helpers), reduced to the speakers: bridge defaults, I2C + * set-up, the four amplifiers reset into shutdown, then per amplifier pair + * its TDM slots and clocks, the amplifiers configured and switched on, and + * the converters synchronised. That driver plays only 44.1 kHz 24-bit + * (cirrus_apple.h:1300), so the chirp goes out in that format here. The + * amplifiers' digital volume is CS_AMP_VOLUME, 24 dB under the 0 dB (0xcf, + * 0.5 dB a step) macOS uses: 12 dB under was very loud on the test computer; + * 0x9f is the reduction the reference driver also lists. */ +#define CS_VENDOR 0x47u /* the vendor widget holding the coefficients */ +#define CS_I2C_ADDR 0x59u /* coefficient: the chip spoken to */ +#define CS_I2C_STS 0x5cu /* bits 3 and 4 both set: the transfer is done */ +#define CS_I2C_WRITE 0x5du /* register << 8 | value */ +#define CS_I2C_READ 0x5eu +#define CS_AMP_VOLUME 0x9fu +#define FMT_441_24_STEREO 0x4031u +#define V_GET_COEF 0xc00 +#define V_VENDOR_7F0 0x7f0 + +static unsigned cs_a, cs_i2c_bad; + +static uint32_t coef_get(unsigned idx) +{ + uint32_t v = 0; + verb(cs_a, CS_VENDOR, V_COEF_INDEX, idx, 0); + verb(cs_a, CS_VENDOR, V_GET_COEF, 0, &v); + verb(cs_a, CS_VENDOR, V_COEF_INDEX, 0, 0); + return v & 0xffffu; +} +static void coef_set(unsigned idx, unsigned v) +{ + verb(cs_a, CS_VENDOR, V_COEF_INDEX, idx, 0); + verb(cs_a, CS_VENDOR, V_PROC_COEF, v & 0xffffu, 0); + verb(cs_a, CS_VENDOR, V_COEF_INDEX, 0, 0); +} +/* the bits in mask replaced by bits (new84.h cs_8409_vendor_coef_set_mask) */ +static void coef_mask(unsigned idx, unsigned mask, unsigned bits) { coef_set(idx, (coef_get(idx) & ~mask) | bits); } + +/* One register write to the chip at I2C address chip (new84.h + * cs_8409_vendor_i2cWrite, unpaged): clock on (coefficient 0 bit 3), address, + * register and value, then up to 9 status reads 2 ms apart, clock off. After + * 13 unconfirmed transfers the rest are skipped. */ +static void i2c_write(unsigned chip, unsigned reg, unsigned val) +{ + if (cs_i2c_bad > 12) /* nothing is answering: the rest would only slow the boot */ + return; + verb(cs_a, CS_VENDOR, V_PROC_STATE, 1, 0); + coef_set(0, coef_get(0) | 0x8u); + coef_set(CS_I2C_ADDR, chip); + coef_set(CS_I2C_WRITE, (reg & 0xffu) << 8 | (val & 0xffu)); + int done = 0; + for (unsigned k = 0; k < 9 && !done; k++) { + done = (coef_get(CS_I2C_STS) & 0x18u) == 0x18u; + if (!done) + spin_us(2000); + } + cs_i2c_bad += !done; + coef_set(0, coef_get(0) & 0xfff7u); +} + +/* The TDM unit's routing refresh after slots change (real84.h configureTDMUR) */ +static void cs_tdm_refresh(void) +{ + coef_set(0x6b, 0x001f); + coef_set(0x71, coef_get(0x71) | 0x400fu); + verb(cs_a, CS_VENDOR, V_VENDOR_7F0, 0xb6, 0); +} + +/* One amplifier configured and switched on (real84.h cs_8409_setup_amp_tas576, + * playback): I2S input, its TDM slot, analogue gain, fault set-up, volume. */ +static void cs_amp_on(unsigned chip, unsigned slot) +{ + static const uint8_t regs[][2] = {{0x02, 0x44}, {0x03, 0x80}, {0x06, 0x55}, {0x08, 0x18}, + {0x04, 0}, {0x13, 0x00}, {0x02, 0x44}, {0x01, 0xfd}}; + for (unsigned k = 0; k < sizeof regs / sizeof regs[0]; k++) + i2c_write(chip, regs[k][0], regs[k][0] == 0x03 ? 0x80u | slot : regs[k][0] == 0x04 ? CS_AMP_VOLUME : regs[k][1]); +} + +static unsigned cs8409_apple(unsigned a, unsigned afg, char *say, size_t say_n) +{ + static const uint8_t amps[4] = {0xd8, 0xda, 0xdc, 0xde}; + static const uint8_t amp_reset[][2] = {{0x01, 0xfc}, {0x02, 0x04}, {0x03, 0x80}, {0x04, 0xcf}, {0x06, 0x51}, + {0x08, 0x00}, {0x10, 0xff}, {0x11, 0xfc}, {0x13, 0x00}, {0x14, 0x02}}; + uint64_t t0 = ck_rdtsc(); + cs_a = a; + cs_i2c_bad = 0; + verb(a, CS_VENDOR, V_PROC_STATE, 1, 0); + /* bridge defaults: every TDM slot off (boot84.h init_for_node_vendor) */ + coef_set(0x00, 0x9008); + coef_set(0x01, 0); + coef_set(0x17, 0); + coef_set(0x18, 0); + coef_set(0x02, 0); + for (unsigned i = 0x19; i <= 0x57; i++) + coef_set(i, 0x8000); + coef_set(0x0a, 0); + coef_set(0x82, 0); + coef_set(0x6b, 0x001f); + coef_set(0x6c, 0x001f); + coef_set(0x82, 0); + /* I2C set-up (boot84.h) */ + verb(a, CS_VENDOR, V_PROC_STATE, 1, 0); + coef_set(0x00, 0x9008); + coef_set(0x02, 0x0080); + coef_set(0x5b, 0x0010); + coef_set(0x00, 0x9000); + verb(a, 0x24, V_PIN_CTL, 0, 0); + verb(a, 0x25, V_PIN_CTL, 0, 0); + /* the amplifiers reset into shutdown, GPIOs 1 and 4 driven high around + each (boot84.h setup_amps_reset_i2c_tas576, setup_gpio_set_10) */ + for (unsigned c = 0; c < 4; c++) { + verb(a, afg, V_GPIO_DIR, 0x12, 0); + verb(a, afg, V_GPIO_DATA, 0x12, 0); + verb(a, afg, V_GPIO_MASK, 0x1f, 0); + for (unsigned k = 0; k < sizeof amp_reset / sizeof amp_reset[0]; k++) + i2c_write(amps[c], amp_reset[k][0], amp_reset[k][1]); + } + /* amplifiers 1 and 2: converter 0x02 on TDM slots 0 and 1, the bus clocks, + pin 0x24 (real84.h cs_8409_setup_TDM_amps12, cs_8409_setup_TDM_sample_rate, + cs_8409_setup_TDM_proper_amps12) */ + verb(a, 0x02, V_FORMAT, FMT_441_24_STEREO, 0); + verb(a, 0x02, V_STREAM, TAG << 4, 0); + coef_set(0x01, coef_get(0x01)); + coef_mask(0x01, 0x0380, 0x0200); + coef_mask(0x05, 0x0007, 0x0001); + coef_mask(0x04, 0x01ff, 0x08ff); + coef_set(0x19, 0x0800); + coef_set(0x1a, 0x0820); + unsigned saved = coef_get(0x00); + coef_set(0x00, 0xb000); + coef_set(0x04, 0x08ff); + coef_set(0x00, saved); + coef_set(0x03, 0x8000); + coef_set(0x05, 0x0001); + coef_mask(0x82, 0, 0x5400); + coef_set(0x02, 0x0280); + coef_set(0x01, coef_get(0x01) | 0x20u); + cs_tdm_refresh(); + verb(a, 0x24, V_PIN_CTL, 0x40, 0); + cs_amp_on(0xd8, 0); + cs_amp_on(0xda, 2); + /* amplifiers 3 and 4: converter 0x03 on slots 2 and 3, pin 0x25 */ + verb(a, 0x03, V_FORMAT, FMT_441_24_STEREO, 0); + verb(a, 0x03, V_STREAM, TAG << 4, 0); + coef_set(0x1b, 0x0840); + coef_set(0x1c, 0x0860); + cs_tdm_refresh(); + verb(a, 0x25, V_PIN_CTL, 0x40, 0); + cs_amp_on(0xdc, 1); + cs_amp_on(0xde, 3); + /* the converters synchronised (real84.h cs_8409_sync_converters_on) */ + verb(a, CS_VENDOR, V_PROC_STATE, 1, 0); + verb(a, 0x02, V_STREAM, 0, 0); + coef_set(0x17, 0x0001); + verb(a, 0x03, V_STREAM, 0, 0); + coef_set(0x17, 0x0003); + verb(a, 0x02, V_STREAM, TAG << 4, 0); + verb(a, 0x03, V_STREAM, TAG << 4, 0); + g_fmt = FMT_441_24_STEREO; + ck_printf("sound: codec=%u CS8409 bridge set up: 4 amplifiers at 0x%02x volume, %u I2C transfer(s) unconfirmed%s, " + "coef 0x01=0x%04x 0x17=0x%04x 0x82=0x%04x; %u ms\n", a, CS_AMP_VOLUME, cs_i2c_bad, + cs_i2c_bad > 12 ? " (gave up)" : "", coef_get(0x01), coef_get(0x17), coef_get(0x82), + (unsigned)((ck_rdtsc() - t0) * 1000 / g_hz)); + ck_snprintf(say, say_n, "codec %u CS8409 0x24(spk)<-0x02 0x25(spk)<-0x03, amplifiers on", a); + return 2; +} + +/* Maps codec a, opens every output path it has; the number of pins opened + * (their converters set to the stream's tag), with a summary in *say. */ +static unsigned codec_open(unsigned ctrl, unsigned a, char *say, size_t say_n) +{ + uint32_t id = param(a, 0, P_VENDOR), rev = param(a, 0, P_REV), nodes = param(a, 0, P_NODES), afg = 0; + if (!id) { + ck_printf("sound: codec=%u no answer (%s)\n", a, rings ? "command rings" : "immediate command"); + return 0; + } + for (unsigned k = 0, first = nodes >> 16 & 0xffu; k < (nodes & 0xffu) && k < 8; k++) + if ((param(a, first + k, P_FUNC) & 0xffu) == 1) + afg = first + k; + uint32_t sub = param(a, 0, P_SUBSYSTEM); + if (afg && !sub) + verb(a, afg, V_SUBSYSTEM, 0, &sub); + if (!afg) { + ck_printf("sound: codec=%u id=%04x:%04x rev=0x%08x no audio function group\n", a, id >> 16, id & 0xffffu, rev); + return 0; + } + verb(a, afg, V_POWER, 0, 0); + uint64_t t0 = ck_rdtsc(); + uint32_t ps = 0; + while (!verb(a, afg, V_GET_POWER, 0, &ps) && (ps >> 4 & 15u) && ck_rdtsc() - t0 < g_hz / 20) + spin_us(100); + uint32_t wn = param(a, afg, P_NODES), first = wn >> 16 & 0xffu, n = wn & 0xffu; + uint32_t afg_out = param(a, afg, P_AMP_OUT), afg_in = param(a, afg, P_AMP_IN), gpio = param(a, afg, P_GPIO) & 0xffu; + ck_printf("sound: codec=%u id=%04x:%04x sub=%04x:%04x rev=0x%08x afg=%u power=D%u widgets=0x%02x..0x%02x gpio=%u " + "amp_out=0x%08x amp_in=0x%08x\n", a, id >> 16, id & 0xffffu, sub >> 16, sub & 0xffffu, rev, afg, + ps >> 4 & 15u, first, first + n - 1, gpio, afg_out, afg_in); + memset(W, 0, sizeof W); + for (unsigned nid = first; nid < first + n && nid < MAX_NID; nid++) { + struct wid *x = &W[nid]; + x->caps = param(a, nid, P_WCAPS); + x->type = (uint8_t)(x->caps >> 20 & 15u); + if (x->type == W_PIN) { + x->pincap = param(a, nid, P_PINCAP); + verb(a, nid, V_CONFIG, 0, &x->cfg); + } + if (x->caps & WC_AMP_OVRD) { + x->amp_out = param(a, nid, P_AMP_OUT); + x->amp_in = param(a, nid, P_AMP_IN); + } + if (x->caps & WC_CONN_LIST) + read_conns(a, nid, x); + if (x->type <= 4) + map_widget(a, nid, x); + } + if ((id >> 16) == 0x1013 && ((id & 0xffffu) == 0x4206 || (id & 0xffffu) == 0x4207)) + for (unsigned k = 0; k < sizeof cs420x_words / sizeof cs420x_words[0]; k++) + verb(a, cs420x_words[k][0], cs420x_words[k][1], cs420x_words[k][2], 0); + if (id == 0x10134208) + for (unsigned k = 0; k < sizeof cs4208_words / sizeof cs4208_words[0]; k++) + verb(a, cs4208_words[k][0], cs4208_words[k][1], cs4208_words[k][2], 0); + if (id == 0x10138409 && (sub >> 16) == 0x106b && W[0x24].type == W_PIN && W[0x25].type == W_PIN && + W[0x02].type == W_AUD_OUT && W[0x03].type == W_AUD_OUT) + return cs8409_apple(a, afg, say, say_n); + /* output pins, speakers first: device 1 speaker, 0 line out, 2 headphone */ + static const unsigned order[3] = {1, 0, 2}; + unsigned opened = 0; + int m = ck_snprintf(say, say_n, "codec %u pins", a); + for (unsigned o = 0; o < 3; o++) + for (unsigned nid = first; nid < first + n && nid < MAX_NID && opened < MAX_PINS; nid++) { + const struct wid *x = &W[nid]; + unsigned dev = x->cfg >> 20 & 15u, port = x->cfg >> 30; + if (x->type != W_PIN || dev != order[o] || port == 1 || !(x->pincap & PC_OUT) || (x->caps & WC_DIGITAL)) + continue; + if (!find_dac(nid, 0)) { + ck_printf("sound: codec=%u pin 0x%02x (%s) has no path to a converter\n", a, nid, + dev == 1 ? "speaker" : dev ? "headphone" : "line out"); + continue; + } + open_path(a, dev, afg_out, afg_in); + opened++; + m += ck_snprintf(say + m, say_n - (size_t)m, " 0x%02x(%s)<-", nid, dev == 1 ? "spk" : dev ? "hp" : "line"); + for (unsigned i = 1; i < plen && m < (int)say_n - 6; i++) + m += ck_snprintf(say + m, say_n - (size_t)m, i > 1 ? ",0x%02x" : "0x%02x", path[i]); + } + if (opened && (sub >> 16) == 0x106b && gpio) { /* Apple: the GPIOs switch the amplifiers on */ + unsigned all = gpio >= 8 ? 0xffu : (1u << gpio) - 1u; + verb(a, afg, V_GPIO_MASK, all, 0); + verb(a, afg, V_GPIO_DIR, all, 0); + verb(a, afg, V_GPIO_DATA, all, 0); + m += ck_snprintf(say + m, say_n - (size_t)m, "; gpio 0x%02x high", all); + } + (void)ctrl; + return opened; +} + +/* ---- the stream ---- */ + +/* The chirp from the night's current moment, then silence, through output + * stream sd. buf holds bytes of PCM (page aligned, contiguous), bdl one page. + * The buffer is filled from the moment the filling starts; the descriptors + * then begin where the night has got to by the time the stream runs, so the + * sound keeps time with the sky however long the filling took. */ +static int stream_play(unsigned ctrl, unsigned sd, uint8_t *buf, size_t bytes, uint64_t *bdl, uint64_t night_t0) +{ + unsigned s = SD0 + 0x20 * sd; + w8(s, 0); + wait8(s, RUN, 0, 10); + w8(s, SRST); + if (wait8(s, SRST, SRST, 10)) { + ck_printf("sound: ctrl=%u stream did not enter reset\n", ctrl); + return -1; + } + w8(s, 0); + if (wait8(s, SRST, 0, 10)) { + ck_printf("sound: ctrl=%u stream did not leave reset\n", ctrl); + return -1; + } + const int wide = g_fmt == FMT_441_24_STEREO; + const uint32_t rate = wide ? CK_CHIRP_RATE_441 : CK_CHIRP_RATE, all = wide ? CK_CHIRP_FRAMES_441 : CK_CHIRP_FRAMES; + const size_t fb = wide ? 8 : 4; /* bytes a frame */ + uint64_t t_fill = ck_rdtsc(); + uint32_t from = (uint32_t)((t_fill - night_t0) * rate / g_hz); + if (from >= all) { + ck_printf("sound: ctrl=%u ready at night %u ms, after the chirp (%u ms); nothing played\n", ctrl, + (uint32_t)((uint64_t)from * 1000 / rate), CK_CHIRP_END_MS); + return -1; + } + uint32_t frames = all - from, tail = rate / 1000u * HDA_TAIL_MS; + if ((frames + tail) * fb > bytes) + tail = (uint32_t)(bytes / fb) - frames; + if (wide) + ck_chirp_fill_441((int32_t *)buf, from, frames); + else + ck_chirp_fill((int16_t *)buf, from, frames); + memset(buf + frames * fb, 0, tail * fb); + flush(buf, (frames + tail) * fb); + uint64_t t_run = ck_rdtsc(); + uint32_t now = (uint32_t)((t_run - night_t0) * rate / g_hz), skip = (now - from) & ~31u; + if (skip >= frames) { + ck_printf("sound: ctrl=%u the chirp was over (night %u ms) once its %u ms were made\n", ctrl, + (uint32_t)((uint64_t)now * 1000 / rate), (uint32_t)((t_run - t_fill) * 1000 / g_hz)); + return -1; + } + uint8_t *p = buf + skip * fb; /* 128-byte aligned, as descriptors need */ + size_t used = (frames + tail - skip) * fb & ~(size_t)127; + unsigned entries = (unsigned)((used + CHUNK - 1) / CHUNK); + for (unsigned k = 0; k < entries; k++) { + size_t off = (size_t)k * CHUNK, len = used - off < CHUNK ? used - off : CHUNK; + bdl[2 * k] = (uint64_t)(uintptr_t)(p + off); + bdl[2 * k + 1] = (uint64_t)len; /* length; no interrupt on completion */ + } + flush(bdl, (size_t)entries * 16); + w32(s + SD_CBL, (uint32_t)used); + w16(s + SD_LVI, (uint16_t)(entries - 1)); + w16(s + SD_FMT, (uint16_t)g_fmt); + w32(s + SD_BDLPL, (uint32_t)(uintptr_t)bdl); + w32(s + SD_BDLPU, (uint32_t)((uint64_t)(uintptr_t)bdl >> 32)); + w8(s + 2, (uint8_t)((r8(s + 2) & 0x0fu) | TAG << 4)); + w8(s + SD_STS, 0x1c); /* old status cleared */ + w8(s, RUN); + uint32_t start_ms = (uint32_t)((uint64_t)(from + skip) * 1000 / rate); + spin_us(2000); + ck_printf("sound: ctrl=%u stream %u playing the chirp from night %u ms (%u ms of it, then %u ms quiet; made in " + "%u ms; format 0x%04x); position after 2 ms %u bytes, status 0x%02x\n", ctrl, sd, start_ms, + (uint32_t)((uint64_t)(frames - skip) * 1000 / rate), HDA_TAIL_MS, + (uint32_t)((t_run - t_fill) * 1000 / g_hz), g_fmt, r32(s + SD_LPIB), r8(s + SD_STS)); + play_bar = g_bar; + play_sd = s; + play_t0 = night_t0; + return 0; +} + +int ck_x86_hda_start(unsigned ctrl, volatile uint8_t *bar, struct ck_frames *fr, uint64_t tsc_hz, uint64_t night_t0, + int play) +{ + g_bar = bar; + g_hz = tsc_hz; + g_fmt = FMT_48K_16_STEREO; + rings = 0; + uint16_t gcap = r16(GCAP); + unsigned iss = gcap >> 8 & 15u, oss = gcap >> 12 & 15u, bss = gcap >> 3 & 31u, nsd = iss + oss + bss; + unsigned running = 0, corb_on = r8(CORBCTL) & RUN, rirb_on = r8(RIRBCTL) & RUN; + for (unsigned i = 0; i < nsd; i++) + running += (r8(SD0 + 0x20 * i) & RUN) != 0; + ck_printf("sound: ctrl=%u version=%u.%u streams out=%u in=%u both=%u; left by the firmware: in_reset=%u " + "command_rings=%s streams_running=%u\n", ctrl, r8(VMAJ), r8(VMIN), oss, iss, bss, !(r32(GCTL) & 1), + corb_on || rirb_on ? "running" : "stopped", running); + int stuck = 0; + for (unsigned i = 0; i < nsd; i++) + if (r8(SD0 + 0x20 * i) & RUN) { + w8(SD0 + 0x20 * i, (uint8_t)(r8(SD0 + 0x20 * i) & ~RUN)); + stuck |= wait8(SD0 + 0x20 * i, RUN, 0, 10); + } + if (corb_on) { + w8(CORBCTL, (uint8_t)(r8(CORBCTL) & ~RUN)); + stuck |= wait8(CORBCTL, RUN, 0, 10); + } + if (rirb_on) { + w8(RIRBCTL, (uint8_t)(r8(RIRBCTL) & ~RUN)); + stuck |= wait8(RIRBCTL, RUN, 0, 10); + } + if (corb_on || rirb_on || running) + ck_printf("sound: ctrl=%u the firmware's DMA %s\n", ctrl, stuck ? "did NOT stop within 10 ms" : "stopped"); + w16(STATESTS, 0x7fff); /* old codec reports cleared */ + w32(GCTL, r32(GCTL) & ~1u); /* into reset */ + if (wait8(GCTL, 1, 0, 10)) { + ck_printf("sound: ctrl=%u did not enter reset\n", ctrl); + return -1; + } + spin_us(1000); + w32(GCTL, r32(GCTL) | 1u); /* out of reset */ + if (wait8(GCTL, 1, 1, 10)) { + ck_printf("sound: ctrl=%u did not leave reset\n", ctrl); + return -1; + } + spin_us(1000); + uint64_t t0 = ck_rdtsc(); + while (!r16(STATESTS) && ck_rdtsc() - t0 < tsc_hz / 20) + ck_pause(); + uint16_t codecs = r16(STATESTS) & 0x7fffu; + ck_printf("sound: ctrl=%u codecs answering: mask=0x%x (1 ms after reset, then %llu us)\n", ctrl, codecs, + (unsigned long long)((ck_rdtsc() - t0) * 1000000 / tsc_hz)); + rings = !rings_start(fr, ctrl); + unsigned opened = 0; + char say[160]; + say[0] = 0; + for (unsigned a = 0; a < 15; a++) + if (codecs >> a & 1) { + char one[160]; + unsigned k = codec_open(ctrl, a, one, sizeof one); + if (k && !opened) + memcpy(say, one, sizeof say); + opened += k; + } + if (!opened) { + ck_printf("sound: ctrl=%u no speaker, line out or headphone path\n", ctrl); + return -1; + } + ck_printf("sound: ctrl=%u opened %u output pin(s): %s\n", ctrl, opened, say); + if (!play) + return 0; + if (!night_t0) { + ck_printf("sound: ctrl=%u ready; no night running, so no chirp\n", ctrl); + return 0; + } + if (!oss) { + ck_printf("sound: ctrl=%u has no output stream\n", ctrl); + return -1; + } + size_t bytes = g_fmt == FMT_441_24_STEREO + ? (size_t)(CK_CHIRP_FRAMES_441 + CK_CHIRP_RATE_441 / 1000u * HDA_TAIL_MS) * 8 + : (size_t)(CK_CHIRP_FRAMES + CK_CHIRP_RATE / 1000u * HDA_TAIL_MS) * 4; + bytes = (bytes + CK_PAGE - 1) & ~(size_t)(CK_PAGE - 1); + uint64_t pa, bpa; + if (!fr || ck_frames_alloc(fr, bytes / CK_PAGE, CK_PAGE, &pa) || ck_frames_alloc(fr, 1, CK_PAGE, &bpa)) { + ck_printf("sound: ctrl=%u no memory for the chirp (%llu KiB)\n", ctrl, (unsigned long long)(bytes >> 10)); + return -1; + } + return stream_play(ctrl, iss, (uint8_t *)(uintptr_t)pa, bytes, (uint64_t *)(uintptr_t)bpa, night_t0) ? -1 : 1; +} + +void ck_x86_hda_step(void) +{ + if (!play_bar || (ck_rdtsc() - play_t0) * 1000 / g_hz < CK_CHIRP_END_MS + 200u) + return; + volatile uint8_t *b = play_bar; + play_bar = 0; + uint32_t pos = *(volatile uint32_t *)(b + play_sd + SD_LPIB); + b[play_sd] = 0; + ck_printf("sound: chirp over; stream stopped at night %llu ms (position %u bytes)\n", + (unsigned long long)((ck_rdtsc() - play_t0) * 1000 / g_hz), pos); +} diff --git a/native/kernel/x86/kmain_x86.c b/native/kernel/x86/kmain_x86.c index f3865112..0a8b96e8 100644 --- a/native/kernel/x86/kmain_x86.c +++ b/native/kernel/x86/kmain_x86.c @@ -14,7 +14,7 @@ * limitations under the License. */ -/* kmain_x86.c -- AIENOS-IMAC-KERNEL-0: the C kernel core on x86_64, first +/* kmain_x86.c -- AIENOS-KERNEL-0: the C kernel core on x86_64, first * cut, for the 2017 iMac (iMac18,3, Core i5-7500) and QEMU q35. * * After ExitBootServices (efi_x86.c) on the firmware's page tables: @@ -33,17 +33,21 @@ * local APIC (xAPIC) with its timer at 100 Hz for 20 ticks, the MADT CPU * count, the secondary cores started and parked (smp_x86.S), the AHCI and * NVMe disks read-only and a look at the Ethernet chip (pci_x86.c, - * ahci_x86.c), and the final report. It holds the screen CK_X86_HOLD_S seconds and + * ahci_x86.c), and the final report. With a keyboard, Allen's window, whose + * memory lives in its own partition of the approved hard disk (memory_x86.c, + * the only disk writes). It holds the screen CK_X86_HOLD_S seconds and * powers off through ACPI S5 (FADT PM1 control + the DSDT's \_S5 package); the lab image * (CK_X86_REPORT=1) restarts through the FADT reset register instead, back * into its network loader (native/boot/net_loader.c). - * Scheduling on the secondary cores, disk writes, the network driver and VT-d + * Scheduling on the secondary cores, the network driver and VT-d * are later cuts. No runtime service * is called. QEMU runs of this path qualify nothing physical. */ #include "../core/ck_internal.h" #include "../core/handoff_check.h" #include "../mm/frames.h" #include "../mm/heap.h" +#include "../svc/allen_reply.h" +#include "../ui/allen_ui.h" #include "x86.h" #ifndef AIENOS_COMMIT @@ -278,6 +282,238 @@ static void acpi_reset(void) } #endif +/* Allen on the screen (ui/allen_ui.c) with its first local answers + * (svc/allen_reply.c). Every Enter gets an answer on the console + * ("allen: ..."); when a keyboard is ready and the RAM for drawing is there, + * the screen switches from the boot report to Allen's window, which stays + * up (no idle countdown) until "goodbye" is typed or the power button is + * held. Without either, the text screen and its timed hold stay as they were. */ +static int allen_on; +static uint64_t allen_bye; /* TSC when Allen said goodbye; 0 = still talking */ +static uint64_t allen_woke; /* TSC when Allen's window took the screen */ +static void night_stats(const char *when); +static ck_allen_facts allen_facts; /* filled at the summary line */ +static ck_allen_mind allen_mind; +static ck_allen_notes allen_notes; /* loaded from disk at the window, or empty */ + +static void allen_edit(const char *buf, unsigned len) { ck_allen_ui_input(buf, len, ck_rdtsc()); } + +/* The notes map beside the window: the newest live notes (point 0 the newest) + * and the links among them; every live note and link is counted. */ +static void allen_map(void) +{ + static uint32_t idx[CK_ALLEN_UI_MAP_NODES]; + static uint8_t ea[CK_ALLEN_UI_MAP_LINKS], eb[CK_ALLEN_UI_MAP_LINKS]; + unsigned n = 0, ne = 0, total = 0, links = 0; + int lit = -1; + for (uint32_t i = allen_notes.n; i-- > 0;) { + if (allen_notes.note[i].gone) + continue; + total++; + for (uint32_t j = i + 1; j < allen_notes.n; j++) + links += !allen_notes.note[j].gone && ck_allen_note_links(&allen_notes.note[i], &allen_notes.note[j]) > 0; + if (n == CK_ALLEN_UI_MAP_NODES) + continue; + if (allen_mind.lit == (int)i + 1) + lit = (int)n; + for (unsigned k = 0; k < n && ne < CK_ALLEN_UI_MAP_LINKS; k++) + if (ck_allen_note_links(&allen_notes.note[i], &allen_notes.note[idx[k]]) > 0) { + ea[ne] = (uint8_t)k; + eb[ne++] = (uint8_t)n; + } + idx[n++] = i; + } + ck_allen_ui_map(n, ea, eb, ne, lit, lit >= 0 ? allen_notes.note[idx[lit]].text : 0, total, links); +} + +static void allen_line(const char *text) +{ + const char *reply = ck_allen_answer(&allen_mind, text, ck_rdtsc() / tsc_hz); + /* What was taught goes to disk before Allen says it will remember it: a + * note first, then the memory copy that counts it; goodbye saves the line + * count. A failed write is said out loud. */ + int save = allen_mind.changed || reply == ck_allen_goodbye; + if (allen_mind.lasting && allen_mind.note_dirty && + ck_x86_notes_write(&allen_notes, (uint32_t)allen_mind.note_dirty - 1u)) { + allen_mind.lasting = 0; + reply = ck_allen_save_failed; + } + if (allen_mind.lasting && save && ck_x86_memory_save(&allen_mind.mem)) { + allen_mind.lasting = 0; + if (allen_mind.changed) + reply = ck_allen_save_failed; + } + allen_mind.changed = 0; + if (allen_mind.map_changed || allen_mind.note_dirty) + allen_map(); + allen_mind.map_changed = 0; + allen_mind.note_dirty = 0; + ck_printf("allen: %s\n", reply); + /* the only line about it the lab report may carry: lengths, no words */ + ck_printf("screen: Allen answered (%u characters in, %u out)\n", (unsigned)strlen(text), (unsigned)strlen(reply)); + ck_allen_ui_said(text, reply, ck_rdtsc()); + if (reply == ck_allen_goodbye && !allen_bye) + allen_bye = ck_rdtsc() | 1; + if (reply == ck_allen_goodbye) + night_stats("by goodbye"); +} + +/* The startup screen (ui/allen_ui.c): the night sky from the moment the clock + * is measured, Allen formed in it by the time the keyboard is ready. Until + * the secondary cores are up the boot core draws a frame between console + * writes (night_tick); then the first secondary core draws the frames + * (draw_loop) and the next two draw strips of them (help_loop). draw_lock + * keeps to one frame at a time whoever draws it. */ +static uint32_t night_ms, night_mib; /* what is said about it once the console is up */ +static uint64_t night_t0; /* when the night began (TSC); the chirp keeps time with it */ +static uint64_t night_last, night_cost; /* the boot core's last frame and what it took */ +static volatile uint32_t draw_run, draw_on, draw_helpers; /* drawing allowed; a core draws frames; cores helping */ +static volatile uint8_t draw_lock; + +static uint64_t night_clock(void) { return ck_rdtsc(); } + +/* After each console write, while no secondary core draws: a frame when one + * is due, with at least twice a frame's drawing time between frames, so + * startup is not slowed by more than a third. */ +static void night_tick(void) +{ + ck_x86_hda_step(); + uint64_t now = ck_rdtsc(); + if (__atomic_load_n(&draw_on, __ATOMIC_ACQUIRE) || now - night_last < night_cost * 2 || + __atomic_test_and_set(&draw_lock, __ATOMIC_ACQUIRE)) + return; + if (ck_allen_ui_tick(now)) { + night_last = ck_rdtsc(); + night_cost = night_last - now; + } + __atomic_clear(&draw_lock, __ATOMIC_RELEASE); +} + +/* The secondary cores' work while the night is up; each returns to its halt + * once draw_stop clears draw_run. */ +static void draw_loop(void) +{ + __atomic_store_n(&draw_on, 1, __ATOMIC_RELEASE); + while (__atomic_load_n(&draw_run, __ATOMIC_ACQUIRE)) { + while (__atomic_test_and_set(&draw_lock, __ATOMIC_ACQUIRE)) + ck_pause(); + int drew = ck_allen_ui_tick(ck_rdtsc()); + __atomic_clear(&draw_lock, __ATOMIC_RELEASE); + if (!drew) + ck_pause(); + } + __atomic_store_n(&draw_on, 0, __ATOMIC_RELEASE); +} +static void help_loop(void) +{ + __atomic_fetch_add(&draw_helpers, 1, __ATOMIC_ACQ_REL); + while (__atomic_load_n(&draw_run, __ATOMIC_ACQUIRE)) + if (!ck_allen_ui_help()) + ck_pause(); + __atomic_fetch_sub(&draw_helpers, 1, __ATOMIC_ACQ_REL); +} + +/* Before text goes back on the screen: the drawing cores finish the frame in + * hand and stop. Waits at most 200 ms (a panic never hangs here); then the + * frame lock is held for good, so nothing draws over the text. */ +static void draw_stop(void) +{ + __atomic_store_n(&draw_run, 0, __ATOMIC_RELEASE); + if (!tsc_hz) + return; + uint64_t t0 = ck_rdtsc(); + while ((draw_on || draw_helpers) && ck_rdtsc() - t0 < tsc_hz / 5) + ck_pause(); + while (__atomic_test_and_set(&draw_lock, __ATOMIC_ACQUIRE) && ck_rdtsc() - t0 < tsc_hz / 5) + ck_pause(); +} + +static void night_stats(const char *when) +{ + uint32_t n, slowest, average; + ck_allen_ui_stats(&n, &slowest, &average); + ck_printf("screen: night: %u frames %s, average %u.%u ms, slowest %u.%u ms (drawn by %s)\n", n, when, + average / 1000, average / 100 % 10, slowest / 1000, slowest / 100 % 10, + draw_on ? "a secondary core" : "the boot core"); +} + +static void allen_window(void) +{ + static char footer[64]; + volatile uint32_t *px; + uint32_t w, h, pitch, format; + uint64_t pa; + ck_allen_mind_init(&allen_mind, &allen_facts); + allen_mind.notes = &allen_notes; + if (ck_x86_memory_open(&allen_mind.mem, &allen_notes, tsc_hz)) { + allen_mind.lasting = 1; + allen_mind.mem.starts++; + if (ck_x86_memory_save(&allen_mind.mem)) + allen_mind.lasting = 0; + } else { + allen_notes.n = 0; /* nothing half-loaded is kept */ + allen_mind.mem.nnotes = 0; + } + ck_x86_kbd_sink(0, allen_line); + if (ck_x86_console_fb_get(&px, &w, &h, &pitch, &format)) { + ck_puts("screen: text only (no framebuffer for Allen's window)\n"); + return; + } + allen_facts.screen_w = w; + allen_facts.screen_h = h; + allen_mind.facts = allen_facts; + if (!ck_allen_ui_started()) { /* the night could not start at boot: Allen's home starts here */ + size_t need = ck_allen_ui_mem_bytes(w, h); + uint64_t pages = (need + CK_PAGE - 1) / CK_PAGE; + if (ck_frames_alloc(&frames, pages, CK_PAGE, &pa)) { + ck_printf("screen: text only (no %llu MiB for Allen's window)\n", (unsigned long long)(need >> 20)); + return; + } + if (ck_allen_ui_start(px, w, h, pitch, format, (void *)(uintptr_t)pa, pages * CK_PAGE, tsc_hz, ck_rdtsc(), + night_clock)) { + ck_puts("screen: text only (Allen's window refused the screen)\n"); + ck_frames_free(&frames, pa, pages); + return; + } + night_mib = (uint32_t)(need >> 20); + } + ck_snprintf(footer, sizeof footer, "Type goodbye to %s this computer", CK_X86_REPORT ? "restart" : "turn off"); + ck_printf("screen: Allen's window (%ux%u, %u MiB drawing memory)\n", w, h, night_mib); + ck_x86_console_fb_off(); + ck_allen_ui_refresh(); /* whatever else was on the screen goes */ + ck_allen_ui_wake(footer, ck_rdtsc()); + ck_x86_kbd_sink(allen_edit, allen_line); + allen_on = 1; + allen_woke = ck_rdtsc(); + night_stats("before Allen woke"); + allen_map(); /* the notes loaded from disk, before the first word */ + const char *hello = ck_allen_welcome(&allen_mind); + if (hello) { + ck_printf("allen: %s\n", hello); + ck_allen_ui_said(0, hello, ck_rdtsc()); + } +} + +void ck_x86_hold_step(uint64_t *end) +{ + ck_x86_hda_step(); + ck_x86_kbd_hold_poll(end); + if (!allen_on) + return; + if (!__atomic_load_n(&draw_on, __ATOMIC_ACQUIRE) && !__atomic_test_and_set(&draw_lock, __ATOMIC_ACQUIRE)) { + ck_allen_ui_tick(ck_rdtsc()); /* no secondary core draws: this one does */ + __atomic_clear(&draw_lock, __ATOMIC_RELEASE); + } + static int told; + if (!told && ck_rdtsc() - allen_woke > 20 * tsc_hz) { + told = 1; + night_stats("by 20 s after Allen woke"); + } + /* No countdown while Allen's window is up; after goodbye, 4 s for the + * answer to appear, then the hold ends. */ + *end = allen_bye ? allen_bye + 4 * tsc_hz : ~0ull; +} + static __attribute__((noreturn)) void finish(void) { ck_cli(); @@ -290,16 +526,40 @@ static __attribute__((noreturn)) void finish(void) for (;;) __asm__ volatile("hlt"); } + if (CK_X86_HOLD_S && ck_x86_kbd_ready()) { + allen_window(); + if (allen_on) + ck_puts("keyboard: type a line and press Enter; Allen's window stays on until you type goodbye\n"); + else + ck_printf("keyboard: type a line and press Enter; the screen stays on until %u s after the last key\n", + ck_x86_kbd_idle_s()); + } + if (!allen_on) { /* no Allen's window: the startup text, not the night */ + draw_stop(); + ck_x86_console_fb_show(); + } if (CK_X86_HOLD_S) { #if CK_X86_REPORT /* Lab build only (make imac-kernel CK_X86_REPORT=1): sends the * allowlisted, unauthenticated report if the network is up. */ - ck_printf("power: holding the screen %u s, then restart\n", (unsigned)CK_X86_HOLD_S); + if (allen_on) + ck_puts("power: Allen's window stays on until goodbye (or the power button), then restart\n"); + else + ck_printf("power: holding the screen %u s, then restart\n", (unsigned)CK_X86_HOLD_S); ck_x86_report_hold(tsc_hz, CK_X86_HOLD_S); + ck_x86_kbd_done(); #else /* Default and resident builds: no report code is linked; nothing is sent. */ - ck_printf("power: holding the screen %u s, then ACPI S5\n", (unsigned)CK_X86_HOLD_S); - delay_ms((uint64_t)CK_X86_HOLD_S * 1000u); + if (allen_on) + ck_puts("power: Allen's window stays on until goodbye (or the power button), then ACPI S5\n"); + else + ck_printf("power: holding the screen %u s, then ACPI S5\n", (unsigned)CK_X86_HOLD_S); + uint64_t end = ck_rdtsc() + (uint64_t)CK_X86_HOLD_S * tsc_hz; /* typing moves it out */ + while (ck_rdtsc() < end) { + ck_x86_hold_step(&end); + ck_pause(); + } + ck_x86_kbd_done(); #endif } #if CK_X86_REPORT @@ -314,6 +574,8 @@ static __attribute__((noreturn)) void finish(void) void ck_panic(const char *fmt, ...) { ck_cli(); + draw_stop(); + ck_x86_console_fb_show(); /* a panic is always readable */ va_list ap; va_start(ap, fmt); ck_puts("panic: "); @@ -782,6 +1044,10 @@ static void ap_entry(void *arg) if ((ck_rdmsr(MSR_EFER) & EFER_NXE) && (ck_rd_cr0() & CR0_WP)) __atomic_fetch_add(&ap_nx_wp, 1, __ATOMIC_SEQ_CST); __atomic_fetch_add(&ap_up, 1, __ATOMIC_SEQ_CST); + if (idx == 0) /* the first one draws the night's frames, the next two help */ + draw_loop(); + else if (idx < 3) + help_loop(); for (;;) __asm__ volatile("cli; hlt"); } @@ -1026,10 +1292,36 @@ static void cpu_line(void) ck_printf("cpu: %s %s\n", vendor, b); } +/* The night begins before anything is said on the screen; the text stays + * off it (still in the RAM copy and on COM1) until Allen's window takes + * over, or comes back if anything goes wrong. */ +static void night_start(const struct ck_handoff *h) +{ + if (h->fb_status != CK_HANDOFF_FB_PRESENT || !mm.fb_ok || !tsc_hz) + return; + size_t need = ck_allen_ui_mem_bytes(h->fb_width, h->fb_height); + uint64_t pages = (need + CK_PAGE - 1) / CK_PAGE, pa; + if (ck_frames_alloc(&frames, pages, CK_PAGE, &pa)) + return; + uint64_t t0 = ck_rdtsc(); + if (ck_allen_ui_start((volatile uint32_t *)(uintptr_t)h->fb_base, h->fb_width, h->fb_height, h->fb_pitch, + h->fb_format, (void *)(uintptr_t)pa, pages * CK_PAGE, tsc_hz, t0, night_clock)) { + ck_frames_free(&frames, pa, pages); + return; + } + night_t0 = t0; + night_ms = (uint32_t)((ck_rdtsc() - t0) * 1000 / tsc_hz); + night_mib = (uint32_t)(need >> 20); + draw_run = 1; + ck_x86_console_fb_hold(night_tick); +} + static __attribute__((noreturn)) void kernel_main(void *arg) { (void)arg; const struct ck_handoff *h = hand; + tsc_measure(); /* first: the night runs on this clock */ + night_start(h); if (h->fb_status == CK_HANDOFF_FB_PRESENT && mm.fb_ok) { uint32_t scale, cols, rows; if (ck_x86_console_fb_on((volatile void *)(uintptr_t)h->fb_base, h->fb_width, h->fb_height, @@ -1039,6 +1331,9 @@ static __attribute__((noreturn)) void kernel_main(void *arg) (unsigned long long)h->fb_base, scale, cols, rows); else ck_puts("screen: refused (unusable geometry)\n"); + if (draw_run) + ck_printf("screen: night: the sky made in %u ms (%u MiB drawing memory); stars, black holes, then Allen\n", + night_ms, night_mib); } else if (h->fb_status == CK_HANDOFF_FB_PRESENT) { ck_puts("screen: refused (framebuffer overlaps RAM or lies above the mapped range)\n"); } else { @@ -1062,6 +1357,15 @@ static __attribute__((noreturn)) void kernel_main(void *arg) ck_printf("memory: frame_ranges=%u free_bytes=%llu heap=0x%llx+%u heap_test=ok\n", frames.n, (unsigned long long)ck_frames_free_bytes(&frames), (unsigned long long)hp, (unsigned)(HEAP_PAGES * CK_PAGE)); + uint64_t ram = 0; + for (uint64_t off = 0; off + hand->desc_size <= hand->map_size; off += hand->desc_size) { + const struct ck_efi_desc *d = (const void *)(uintptr_t)(hand->memory_map + off); + if (efi_ram(d->type)) + ram += d->pages * CK_PAGE; + } + /* the firmware keeps a little for itself, so whole GiB rounded up is what is fitted */ + ck_printf("ram: %llu MiB in the memory map, about %llu GiB fitted\n", (unsigned long long)(ram >> 20), + (unsigned long long)((ram + (1ull << 30) - 1) >> 30)); ck_printf("stack: 0x%llx-0x%llx guard=0x%llx ist1=0x%llx\n", (unsigned long long)(uintptr_t)(kstack + 4096), (unsigned long long)(uintptr_t)(kstack + sizeof kstack), (unsigned long long)(uintptr_t)kstack, @@ -1087,7 +1391,6 @@ static __attribute__((noreturn)) void kernel_main(void *arg) (unsigned long long)probe.err); wx_probes(); - tsc_measure(); if (!tsc_hz) ck_panic("timebase: no HPET and no CPUID leaf 0x16 frequency"); ck_printf("timebase: %s period_fs=%llu tsc_hz=%llu\n", timebase, (unsigned long long)hpet_period_fs, @@ -1116,12 +1419,17 @@ static __attribute__((noreturn)) void kernel_main(void *arg) for (unsigned k = 0; k < sr.started; k++) n += (unsigned)ck_snprintf(ids + n, sizeof ids - n, k ? ",%u" : "%u", sr.up_ids[k]); ids[n] = 0; - ck_printf("smp: cpus=%u started=%u failed=%u bsp_id=%u ap_ids=%s trampoline=0x%llx state=halted\n", + ck_printf("smp: cpus=%u started=%u failed=%u bsp_id=%u ap_ids=%s trampoline=0x%llx state=%s helpers=%u\n", sr.listed, sr.started, sr.failed, ar.id, sr.started ? ids : "none", - (unsigned long long)tramp_pa); + (unsigned long long)tramp_pa, draw_on ? "drawing" : "halted", draw_helpers); } const struct ck_x86_storage_result *st = ck_x86_storage(h->rsdp, &frames, tsc_hz, mm.top); + ck_x86_sound(&frames, tsc_hz, night_t0); /* before the keyboard: the chirp is already under way */ + ck_x86_usb(&frames, tsc_hz); + allen_facts.cores = sr.started + 1; + allen_facts.sata_disks = st->ahci_disks; + allen_facts.nvme_disks = st->nvme_disks; wx_audit(sr.started); ck_puts("kernel: alive\n"); ck_printf("summary: cores=%u/%u timer=ok sata_disks=%u nvme_disks=%u gpt_valid=%u writes=none net=%s\n", @@ -1131,7 +1439,7 @@ static __attribute__((noreturn)) void kernel_main(void *arg) : st->net_link == 1 ? "link-up" : st->net_link == 2 ? "link-down" : "seen"); - ck_puts("AIENOS-IMAC-KERNEL-0 DONE\n"); + ck_puts("AIENOS-KERNEL-0 DONE\n"); ck_puts("note: QEMU qualifies nothing physical\n"); finish(); } diff --git a/native/kernel/x86/memory_x86.c b/native/kernel/x86/memory_x86.c new file mode 100644 index 00000000..156e2061 --- /dev/null +++ b/native/kernel/x86/memory_x86.c @@ -0,0 +1,202 @@ +/* memory_x86.c -- Allen's memory and notes on a hard disk of whatever + * machine AIENOS boots on. + * + * Which disk, at boot, once: + * 1. the SATA disk that already holds Allen's section (a GPT partition of + * the AIENOS type): on any machine, the section is what makes a disk + * Allen's. Two disks with a section: neither is written; + * 2. with no section anywhere, one of ALLEN_PART_MIB is added only on a disk + * its owner approved (approved_disks, by IDENTIFY model; Drake approved + * his hard disk 2026-10-17), in unused space (dev/gpt_add.c): only then + * are the GPT blocks (LBA 1 up to the first usable LBA, and after the + * last usable LBA) opened for writing, and closed again right after. + * Existing partitions are never touched; no unused space, an invalid GPT + * or no GPT: nothing written. A new machine gets its section from the + * installer instead, on the disk its owner picks there; + * 3. every partition of the chosen disk is listed ("ahci_part:"), a record + * of the layout as found; + * 4. the write range is set to the units of the section Allen uses (the two + * memory copies and the note units, svc/allen_memory.h) and nothing + * else; the newest valid copy is loaded, then the notes it counts. + * NVMe disks are never written (no write path exists). With no usable disk + * Allen remembers only until the power goes off. The conversation itself + * never goes on the console or the network report from here: only counts + * ("3 facts", "2 notes"). */ +#include "../core/ck_internal.h" +#include "../svc/allen_memory.h" +#include "disk_part.h" +#include "gpt_add.h" +#include "x86.h" + +#define ALLEN_PART_MIB 1024u + +/* Disks whose owner approved adding Allen's section to them. */ +static const char *const approved_disks[] = {"APPLE HDD ST1000DM003", 0}; + +static ck_part part; +static ck_allen_store store; +static unsigned disk_index; +static int lasting; +static uint64_t hz; + +static int same_text(const char *a, const char *b) +{ + while (*a && *a == *b) + a++, b++; + return *a == *b; +} + +static int approved(const char *model) +{ + for (const char *const *p = approved_disks; *p; p++) + if (same_text(model, *p)) + return 1; + return 0; +} + +static void show_entry(void *ctx, const ck_gpt_entry *e) +{ + const disk_dev *d = ctx; + const uint8_t *t = e->type; + ck_printf("ahci_part: disk=%u entry=%u type=%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x " + "first_lba=%llu last_lba=%llu mib=%llu name=\"%s\"%s\n", + disk_index, e->index, t[3], t[2], t[1], t[0], t[5], t[4], t[7], t[6], t[8], t[9], t[10], t[11], t[12], + t[13], t[14], t[15], (unsigned long long)e->first, (unsigned long long)e->last, + (unsigned long long)((e->last - e->first + 1u) * d->block_size >> 20), e->name, + memcmp(t, ck_aienos_part_type, 16) ? "" : " (AIENOS)"); +} + +static int no_memory(const char *why) +{ + ck_printf("allen_memory: %s; Allen remembers only until this computer turns off\n", why); + return 0; +} + +/* Adds Allen's section on the approved disk d (no section anywhere yet). */ +static int add_section(const disk_dev *d, const ck_gpt_info *gi) +{ + uint64_t per_mib = (1024u * 1024u) / d->block_size; + if (ck_x86_ahci_allow(disk_index, 1, gi->first_usable - 1u) || + ck_x86_ahci_allow(disk_index, gi->last_usable + 1u, gi->last_lba)) { + ck_x86_ahci_allow_none(disk_index); + return no_memory("could not open the GPT blocks for writing"); + } + ck_gpt_added a; + int rc = ck_gpt_add_aienos(d, (uint64_t)ALLEN_PART_MIB * per_mib, per_mib, &a); + ck_x86_ahci_allow_none(disk_index); + if (rc) { + ck_printf("allen_memory: AIENOS partition not added: %s%s\n", ck_gpt_add_strerror(rc), + rc == CK_GPT_EWRITE || rc == CK_GPT_EVERIFY ? " (the GPT may need a look)" : "; nothing was written"); + return no_memory("no AIENOS partition"); + } + ck_printf("allen_memory: AIENOS partition added, entry %u, first_lba=%llu last_lba=%llu (%u MiB); the existing " + "partitions were not touched\n", a.index, (unsigned long long)a.first, (unsigned long long)a.last, + ALLEN_PART_MIB); + return 1; +} + +int ck_x86_memory_open(ck_allen_memory *mem, ck_allen_notes *notes, uint64_t tsc_hz) +{ + hz = tsc_hz; + const disk_dev *home = 0, *ok = 0; + unsigned homes = 0, oks = 0, home_i = 0, ok_i = 0; + ck_gpt_info gi, ok_gi; + for (unsigned i = 0;; i++) { + const char *model = 0; + const disk_dev *x = ck_x86_ahci_dev(i, &model); + if (!x) + break; + int rc = ck_gpt_find_aienos(x, &part, &gi); + if (rc == CK_GPT_OK) { + home = x; + home_i = i; + homes++; + } else if (rc == CK_GPT_ENOPART && approved(model)) { + ok = x; + ok_i = i; + ok_gi = gi; + oks++; + } + } + if (homes > 1) + return no_memory("two disks hold Allen's section, writing to neither"); + const disk_dev *d = homes ? home : ok; + disk_index = homes ? home_i : ok_i; + if (!homes && oks != 1) + return no_memory(oks ? "two approved disks and no section yet, writing to neither" + : "no disk holds Allen's section and none is approved for one"); + ck_printf("allen_memory: %s disk %u (%llu blocks of %u bytes)\n", + homes ? "Allen's section is on" : "no section yet; the approved disk is", disk_index, + (unsigned long long)d->block_count, d->block_size); + int n = ck_gpt_list(d, show_entry, (void *)d); + if (n < 0) + return no_memory(ck_gpt_add_strerror(n)); /* no GPT or an invalid one: never written */ + ck_printf("allen_memory: the disk has %d partition%s\n", n, n == 1 ? "" : "s"); + if (!homes && !add_section(d, &ok_gi)) + return 0; + int rc = ck_gpt_find_aienos(d, &part, &gi); + if (rc) + return no_memory(ck_gpt_add_strerror(rc)); + if (homes) + ck_printf("allen_memory: AIENOS partition found, entry %u, first_lba=%llu last_lba=%llu\n", gi.part_index, + (unsigned long long)part.first_lba, (unsigned long long)(part.first_lba + part.blocks - 1u)); + + uint64_t units = (uint64_t)CK_ALLEN_DISK_UNITS * CK_ALLEN_MEM_UNIT / d->block_size; + if (part.blocks < units || ck_x86_ahci_allow(disk_index, part.first_lba, part.first_lba + units - 1u)) + return no_memory("could not open Allen's section for writing"); + rc = ck_allen_store_load(&store, &part.dev, mem); + if (rc < 0) { + ck_x86_ahci_allow_none(disk_index); + return no_memory("reading the memory copies failed"); + } + if (rc == CK_ALLEN_MEM_EMPTY) + ck_puts("allen_memory: empty (a first start); Allen starts fresh\n"); + else + ck_printf("allen_memory: loaded generation %llu (%u of 2 copies valid): %u fact%s, name %s, %u earlier start%s\n", + (unsigned long long)store.gen, store.valid, mem->nfacts, mem->nfacts == 1 ? "" : "s", ``` The diff is longer than this page shows; the raw diff has all of it.