solanapolis 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/README.md +518 -0
  2. package/bin/solanapolis.js +197 -0
  3. package/convex/_generated/api.d.ts +175 -0
  4. package/convex/_generated/api.js +23 -0
  5. package/convex/_generated/dataModel.d.ts +60 -0
  6. package/convex/_generated/server.d.ts +143 -0
  7. package/convex/_generated/server.js +93 -0
  8. package/convex/agent/conversation.ts +352 -0
  9. package/convex/agent/embeddingsCache.ts +110 -0
  10. package/convex/agent/memory.ts +450 -0
  11. package/convex/agent/schema.ts +53 -0
  12. package/convex/aiChat.ts +54 -0
  13. package/convex/aiTown/agent.ts +382 -0
  14. package/convex/aiTown/agentDescription.ts +27 -0
  15. package/convex/aiTown/agentInputs.ts +155 -0
  16. package/convex/aiTown/agentOperations.ts +178 -0
  17. package/convex/aiTown/conversation.ts +395 -0
  18. package/convex/aiTown/conversationMembership.ts +38 -0
  19. package/convex/aiTown/game.ts +371 -0
  20. package/convex/aiTown/ids.ts +32 -0
  21. package/convex/aiTown/inputHandler.ts +9 -0
  22. package/convex/aiTown/inputs.ts +25 -0
  23. package/convex/aiTown/insertInput.ts +20 -0
  24. package/convex/aiTown/location.ts +32 -0
  25. package/convex/aiTown/main.ts +154 -0
  26. package/convex/aiTown/movement.ts +189 -0
  27. package/convex/aiTown/player.ts +310 -0
  28. package/convex/aiTown/playerDescription.ts +35 -0
  29. package/convex/aiTown/schema.ts +79 -0
  30. package/convex/aiTown/world.ts +65 -0
  31. package/convex/aiTown/worldMap.ts +74 -0
  32. package/convex/chat.ts +79 -0
  33. package/convex/constants.ts +78 -0
  34. package/convex/convex.config.ts +6 -0
  35. package/convex/crons.ts +89 -0
  36. package/convex/engine/abstractGame.ts +199 -0
  37. package/convex/engine/historicalObject.ts +355 -0
  38. package/convex/engine/schema.ts +56 -0
  39. package/convex/http.ts +36 -0
  40. package/convex/init.ts +110 -0
  41. package/convex/messages.ts +53 -0
  42. package/convex/npcCarAgents.ts +415 -0
  43. package/convex/schema.ts +61 -0
  44. package/convex/streaming.ts +23 -0
  45. package/convex/testing.ts +202 -0
  46. package/convex/tsconfig.json +18 -0
  47. package/convex/util/FastIntegerCompression.ts +221 -0
  48. package/convex/util/assertNever.ts +4 -0
  49. package/convex/util/asyncMap.ts +20 -0
  50. package/convex/util/compression.ts +71 -0
  51. package/convex/util/geometry.ts +132 -0
  52. package/convex/util/isSimpleObject.ts +11 -0
  53. package/convex/util/llm.ts +724 -0
  54. package/convex/util/minheap.ts +38 -0
  55. package/convex/util/object.ts +22 -0
  56. package/convex/util/sleep.ts +3 -0
  57. package/convex/util/types.ts +33 -0
  58. package/convex/util/xxhash.ts +228 -0
  59. package/convex/world.ts +257 -0
  60. package/data/animations/campfire.json +45 -0
  61. package/data/animations/gentlesparkle.json +37 -0
  62. package/data/animations/gentlesplash.json +61 -0
  63. package/data/animations/gentlewaterfall.json +61 -0
  64. package/data/animations/windmill.json +78 -0
  65. package/data/characters.ts +121 -0
  66. package/data/convertMap.js +74 -0
  67. package/data/gentle.js +330 -0
  68. package/data/spritesheets/f1.ts +75 -0
  69. package/data/spritesheets/f2.ts +75 -0
  70. package/data/spritesheets/f3.ts +75 -0
  71. package/data/spritesheets/f4.ts +75 -0
  72. package/data/spritesheets/f5.ts +75 -0
  73. package/data/spritesheets/f6.ts +75 -0
  74. package/data/spritesheets/f7.ts +75 -0
  75. package/data/spritesheets/f8.ts +75 -0
  76. package/data/spritesheets/p1.ts +59 -0
  77. package/data/spritesheets/p2.ts +59 -0
  78. package/data/spritesheets/p3.ts +59 -0
  79. package/data/spritesheets/player.ts +59 -0
  80. package/data/spritesheets/types.ts +26 -0
  81. package/eslint.config.mjs +37 -0
  82. package/next.config.ts +7 -0
  83. package/package.json +85 -0
  84. package/postcss.config.mjs +7 -0
  85. package/public/file.svg +1 -0
  86. package/public/globe.svg +1 -0
  87. package/public/helius-icon.svg +84 -0
  88. package/public/helius-logo.svg +85 -0
  89. package/public/next.svg +1 -0
  90. package/public/plane.glb +0 -0
  91. package/public/vercel.svg +1 -0
  92. package/public/window.svg +1 -0
  93. package/scripts/clear-city.ts +74 -0
  94. package/scripts/seed-wallets.ts +185 -0
  95. package/scripts/setup-webhook.ts +73 -0
  96. package/src/app/api/auth/callback/route.ts +6 -0
  97. package/src/app/api/auth/link-wallet/route.ts +6 -0
  98. package/src/app/api/auth/phantom/route.ts +6 -0
  99. package/src/app/api/broadcast-position/route.ts +59 -0
  100. package/src/app/api/leaderboard/route.ts +85 -0
  101. package/src/app/api/network-stats/route.ts +86 -0
  102. package/src/app/api/parcel-reward/route.ts +181 -0
  103. package/src/app/api/queue-status/route.ts +30 -0
  104. package/src/app/api/snapshots/route.ts +37 -0
  105. package/src/app/api/transactions/enhanced/route.ts +57 -0
  106. package/src/app/api/treasury/route.ts +83 -0
  107. package/src/app/api/wallet/[address]/balances/route.ts +124 -0
  108. package/src/app/api/wallet/[address]/identity/route.ts +32 -0
  109. package/src/app/api/wallet/[address]/route.ts +216 -0
  110. package/src/app/api/wallet/[address]/traded-tokens/route.ts +41 -0
  111. package/src/app/api/wallets/route.ts +68 -0
  112. package/src/app/api/webhooks/helius/route.ts +76 -0
  113. package/src/app/auth/callback/page.tsx +29 -0
  114. package/src/app/favicon.ico +0 -0
  115. package/src/app/globals.css +39 -0
  116. package/src/app/layout.tsx +43 -0
  117. package/src/app/page.tsx +16 -0
  118. package/src/components/AITownNPCs.tsx +206 -0
  119. package/src/components/ActivityFeed.tsx +189 -0
  120. package/src/components/AuthPanel.tsx +163 -0
  121. package/src/components/BeachScene.tsx +280 -0
  122. package/src/components/Building.tsx +138 -0
  123. package/src/components/CesiumFlight.tsx +1768 -0
  124. package/src/components/CesiumGlobe.tsx +616 -0
  125. package/src/components/CitizenCard.tsx +442 -0
  126. package/src/components/CitizenCardModal.tsx +153 -0
  127. package/src/components/CityGrid.tsx +313 -0
  128. package/src/components/CityLandmarks.tsx +427 -0
  129. package/src/components/CityScene.tsx +1289 -0
  130. package/src/components/CitySlotsBadge.tsx +68 -0
  131. package/src/components/CockpitHUD.tsx +460 -0
  132. package/src/components/ConvexWrapper.tsx +19 -0
  133. package/src/components/DubaiDistrict.tsx +630 -0
  134. package/src/components/FlightMiniMap.tsx +133 -0
  135. package/src/components/GameChat.tsx +383 -0
  136. package/src/components/GameHUD.tsx +393 -0
  137. package/src/components/Ground.tsx +14 -0
  138. package/src/components/HowItWorksModal.tsx +251 -0
  139. package/src/components/IngestionBanner.tsx +123 -0
  140. package/src/components/InstancedBuildings.tsx +316 -0
  141. package/src/components/InstancedCars.tsx +504 -0
  142. package/src/components/InstancedCityPlanes.tsx +259 -0
  143. package/src/components/InstancedHouses.tsx +246 -0
  144. package/src/components/InstancedLampPosts.tsx +201 -0
  145. package/src/components/InstancedResidentCars.tsx +357 -0
  146. package/src/components/InstancedRoadDashes.tsx +42 -0
  147. package/src/components/InstancedSkyscrapers.tsx +434 -0
  148. package/src/components/InstancedTrees.tsx +67 -0
  149. package/src/components/LeaderboardPanel.tsx +136 -0
  150. package/src/components/MultiplayerPlanes.tsx +128 -0
  151. package/src/components/NetworkStats.tsx +83 -0
  152. package/src/components/NewBuildingSpotlight.tsx +93 -0
  153. package/src/components/ParcelChallengeBanner.tsx +242 -0
  154. package/src/components/ParcelReward.tsx +191 -0
  155. package/src/components/Park.tsx +42 -0
  156. package/src/components/PhantomWrapper.tsx +22 -0
  157. package/src/components/PixelStreamViewer.tsx +335 -0
  158. package/src/components/PlaneMode.tsx +190 -0
  159. package/src/components/PlayerCar.tsx +211 -0
  160. package/src/components/PlayerPlane.tsx +255 -0
  161. package/src/components/ProjectileRenderer.tsx +249 -0
  162. package/src/components/QueueStatusBanner.tsx +86 -0
  163. package/src/components/RealPlayerTags.tsx +82 -0
  164. package/src/components/SceneLighting.tsx +382 -0
  165. package/src/components/SelectionBeam.tsx +59 -0
  166. package/src/components/SwapPanel.tsx +104 -0
  167. package/src/components/SwapParticles.tsx +237 -0
  168. package/src/components/TreasureGate.tsx +505 -0
  169. package/src/components/WalletPanel.tsx +421 -0
  170. package/src/components/WalletSearch.tsx +244 -0
  171. package/src/components/WelcomeOverlay.tsx +135 -0
  172. package/src/components/WindowTooltip.tsx +498 -0
  173. package/src/context/AuthContext.tsx +230 -0
  174. package/src/lib/bot-detection.ts +125 -0
  175. package/src/lib/building-math.ts +136 -0
  176. package/src/lib/building-shader.ts +253 -0
  177. package/src/lib/car-paths.ts +244 -0
  178. package/src/lib/car-system.ts +182 -0
  179. package/src/lib/city-constants.ts +29 -0
  180. package/src/lib/city-slots.ts +35 -0
  181. package/src/lib/city-zoning.ts +64 -0
  182. package/src/lib/collision-map.ts +147 -0
  183. package/src/lib/day-night.ts +252 -0
  184. package/src/lib/export-card.ts +28 -0
  185. package/src/lib/helius-webhook.ts +90 -0
  186. package/src/lib/helius.ts +74 -0
  187. package/src/lib/house-shader.ts +119 -0
  188. package/src/lib/mock-data.ts +56 -0
  189. package/src/lib/multiplayer-manager.ts +329 -0
  190. package/src/lib/plane-physics.ts +66 -0
  191. package/src/lib/player-car.ts +147 -0
  192. package/src/lib/player-plane.ts +200 -0
  193. package/src/lib/projectile-system.ts +272 -0
  194. package/src/lib/skyscraper-types.ts +52 -0
  195. package/src/lib/sound-engine.ts +464 -0
  196. package/src/lib/supabase-admin.ts +9 -0
  197. package/src/lib/supabase.ts +8 -0
  198. package/src/lib/swap-events.ts +70 -0
  199. package/src/middleware.ts +37 -0
  200. package/src/types/phantom.d.ts +16 -0
  201. package/src/types/wallet.ts +20 -0
  202. package/tsconfig.json +34 -0
@@ -0,0 +1,38 @@
1
+ // Basic 1-indexed minheap implementation
2
+ export function MinHeap<T>(compare: (a: T, b: T) => boolean) {
3
+ const tree = [null as T];
4
+ let endIndex = 1;
5
+ return {
6
+ peek: (): T | undefined => tree[1],
7
+ length: () => endIndex - 1,
8
+ push: (newValue: T) => {
9
+ let destinationIndex = endIndex++;
10
+ let nextToCheck;
11
+ while ((nextToCheck = destinationIndex >> 1) > 0) {
12
+ const existing = tree[nextToCheck];
13
+ if (compare(newValue, existing)) break;
14
+ tree[destinationIndex] = existing;
15
+ destinationIndex = nextToCheck;
16
+ }
17
+ tree[destinationIndex] = newValue;
18
+ },
19
+ pop: () => {
20
+ if (endIndex == 1) return undefined;
21
+ endIndex--;
22
+ const value = tree[1];
23
+ const lastValue = tree[endIndex];
24
+ let destinationIndex = 1;
25
+ let nextToCheck;
26
+ while ((nextToCheck = destinationIndex << 1) < endIndex) {
27
+ if (nextToCheck + 1 <= endIndex && compare(tree[nextToCheck], tree[nextToCheck + 1]))
28
+ nextToCheck++;
29
+ const existing = tree[nextToCheck];
30
+ if (compare(existing, lastValue)) break;
31
+ tree[destinationIndex] = existing;
32
+ destinationIndex = nextToCheck;
33
+ }
34
+ tree[destinationIndex] = lastValue;
35
+ return value;
36
+ },
37
+ };
38
+ }
@@ -0,0 +1,22 @@
1
+ export function parseMap<Id, Serialized, Parsed>(
2
+ records: Serialized[],
3
+ constructor: new (r: Serialized) => Parsed,
4
+ getId: (r: Parsed) => Id,
5
+ ): Map<Id, Parsed> {
6
+ const out = new Map();
7
+ for (const record of records) {
8
+ const parsed = new constructor(record);
9
+ const id = getId(parsed);
10
+ if (out.has(id)) {
11
+ throw new Error(`Duplicate ID ${id}`);
12
+ }
13
+ out.set(id, parsed);
14
+ }
15
+ return out;
16
+ }
17
+
18
+ export function serializeMap<Serialized, T extends { serialize(): Serialized }>(
19
+ map: Map<string, T>,
20
+ ): Serialized[] {
21
+ return [...map.values()].map((v) => v.serialize());
22
+ }
@@ -0,0 +1,3 @@
1
+ export async function sleep(ms: number) {
2
+ return new Promise((resolve) => setTimeout(resolve, ms));
3
+ }
@@ -0,0 +1,33 @@
1
+ import { Infer, v } from 'convex/values';
2
+
3
+ export const point = v.object({
4
+ x: v.number(),
5
+ y: v.number(),
6
+ });
7
+ export type Point = Infer<typeof point>;
8
+
9
+ export const vector = v.object({
10
+ dx: v.number(),
11
+ dy: v.number(),
12
+ });
13
+ export type Vector = Infer<typeof vector>;
14
+
15
+ // Paths are arrays of [x, y, dx, dy, t] tuples;
16
+ export const path = v.array(v.array(v.number()));
17
+ export type Path = [number, number, number, number, number][];
18
+
19
+ export type PathComponent = { position: Point; facing: Vector; t: number };
20
+
21
+ export function queryPath(p: Path, at: number): PathComponent {
22
+ return unpackPathComponent(p[at]);
23
+ }
24
+ export function packPathComponent(p: PathComponent): [number, number, number, number, number] {
25
+ return [p.position.x, p.position.y, p.facing.dx, p.facing.dy, p.t];
26
+ }
27
+ export function unpackPathComponent(p: [number, number, number, number, number]): PathComponent {
28
+ return {
29
+ position: { x: p[0], y: p[1] },
30
+ facing: { dx: p[2], dy: p[3] },
31
+ t: p[4],
32
+ };
33
+ }
@@ -0,0 +1,228 @@
1
+ /*
2
+ From https://github.com/Jason3S/xxhash
3
+
4
+ MIT License
5
+
6
+ Copyright (c) 2019 Jason Dent
7
+
8
+ Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ of this software and associated documentation files (the "Software"), to deal
10
+ in the Software without restriction, including without limitation the rights
11
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ copies of the Software, and to permit persons to whom the Software is
13
+ furnished to do so, subject to the following conditions:
14
+
15
+ The above copyright notice and this permission notice shall be included in all
16
+ copies or substantial portions of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ SOFTWARE.
25
+ */
26
+
27
+ const PRIME32_1 = 2654435761;
28
+ const PRIME32_2 = 2246822519;
29
+ const PRIME32_3 = 3266489917;
30
+ const PRIME32_4 = 668265263;
31
+ const PRIME32_5 = 374761393;
32
+
33
+ export function toUtf8(text: string): Uint8Array {
34
+ const bytes: number[] = [];
35
+ for (let i = 0, n = text.length; i < n; ++i) {
36
+ const c = text.charCodeAt(i);
37
+ if (c < 0x80) {
38
+ bytes.push(c);
39
+ } else if (c < 0x800) {
40
+ bytes.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f));
41
+ } else if (c < 0xd800 || c >= 0xe000) {
42
+ bytes.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));
43
+ } else {
44
+ const cp = 0x10000 + (((c & 0x3ff) << 10) | (text.charCodeAt(++i) & 0x3ff));
45
+ bytes.push(
46
+ 0xf0 | ((cp >> 18) & 0x7),
47
+ 0x80 | ((cp >> 12) & 0x3f),
48
+ 0x80 | ((cp >> 6) & 0x3f),
49
+ 0x80 | (cp & 0x3f),
50
+ );
51
+ }
52
+ }
53
+ return new Uint8Array(bytes);
54
+ }
55
+
56
+ /**
57
+ *
58
+ * @param buffer - byte array or string
59
+ * @param seed - optional seed (32-bit unsigned);
60
+ */
61
+ export function xxHash32(buffer: Uint8Array | string, seed = 0): number {
62
+ buffer = typeof buffer === 'string' ? toUtf8(buffer) : buffer;
63
+ const b = buffer;
64
+
65
+ /*
66
+ Step 1. Initialize internal accumulators
67
+ Each accumulator gets an initial value based on optional seed input. Since the seed is optional, it can be 0.
68
+
69
+ ```
70
+ u32 acc1 = seed + PRIME32_1 + PRIME32_2;
71
+ u32 acc2 = seed + PRIME32_2;
72
+ u32 acc3 = seed + 0;
73
+ u32 acc4 = seed - PRIME32_1;
74
+ ```
75
+ Special case : input is less than 16 bytes
76
+ When input is too small (< 16 bytes), the algorithm will not process any stripe. Consequently, it will not
77
+ make use of parallel accumulators.
78
+
79
+ In which case, a simplified initialization is performed, using a single accumulator :
80
+
81
+ u32 acc = seed + PRIME32_5;
82
+ The algorithm then proceeds directly to step 4.
83
+ */
84
+
85
+ let acc = (seed + PRIME32_5) & 0xffffffff;
86
+ let offset = 0;
87
+
88
+ if (b.length >= 16) {
89
+ const accN = [
90
+ (seed + PRIME32_1 + PRIME32_2) & 0xffffffff,
91
+ (seed + PRIME32_2) & 0xffffffff,
92
+ (seed + 0) & 0xffffffff,
93
+ (seed - PRIME32_1) & 0xffffffff,
94
+ ];
95
+
96
+ /*
97
+ Step 2. Process stripes
98
+ A stripe is a contiguous segment of 16 bytes. It is evenly divided into 4 lanes, of 4 bytes each.
99
+ The first lane is used to update accumulator 1, the second lane is used to update accumulator 2, and so on.
100
+
101
+ Each lane read its associated 32-bit value using little-endian convention.
102
+
103
+ For each {lane, accumulator}, the update process is called a round, and applies the following formula :
104
+
105
+ ```
106
+ accN = accN + (laneN * PRIME32_2);
107
+ accN = accN <<< 13;
108
+ accN = accN * PRIME32_1;
109
+ ```
110
+
111
+ This shuffles the bits so that any bit from input lane impacts several bits in output accumulator.
112
+ All operations are performed modulo 2^32.
113
+
114
+ Input is consumed one full stripe at a time. Step 2 is looped as many times as necessary to consume
115
+ the whole input, except the last remaining bytes which cannot form a stripe (< 16 bytes). When that
116
+ happens, move to step 3.
117
+ */
118
+
119
+ const b = buffer;
120
+ const limit = b.length - 16;
121
+ let lane = 0;
122
+ for (offset = 0; (offset & 0xfffffff0) <= limit; offset += 4) {
123
+ const i = offset;
124
+ const laneN0 = (b[i + 0] as any) + ((b[i + 1] as any) << 8);
125
+ const laneN1 = (b[i + 2] as any) + ((b[i + 3] as any) << 8);
126
+ const laneNP = laneN0 * PRIME32_2 + ((laneN1 * PRIME32_2) << 16);
127
+ let acc = (accN[lane] + laneNP) & 0xffffffff;
128
+ acc = (acc << 13) | (acc >>> 19);
129
+ const acc0 = acc & 0xffff;
130
+ const acc1 = acc >>> 16;
131
+ accN[lane] = (acc0 * PRIME32_1 + ((acc1 * PRIME32_1) << 16)) & 0xffffffff;
132
+ lane = (lane + 1) & 0x3;
133
+ }
134
+
135
+ /*
136
+ Step 3. Accumulator convergence
137
+ All 4 lane accumulators from previous steps are merged to produce a single remaining accumulator
138
+ of same width (32-bit). The associated formula is as follows :
139
+
140
+ ```
141
+ acc = (acc1 <<< 1) + (acc2 <<< 7) + (acc3 <<< 12) + (acc4 <<< 18);
142
+ ```
143
+ */
144
+ acc =
145
+ (((accN[0] << 1) | (accN[0] >>> 31)) +
146
+ ((accN[1] << 7) | (accN[1] >>> 25)) +
147
+ ((accN[2] << 12) | (accN[2] >>> 20)) +
148
+ ((accN[3] << 18) | (accN[3] >>> 14))) &
149
+ 0xffffffff;
150
+ }
151
+
152
+ /*
153
+ Step 4. Add input length
154
+ The input total length is presumed known at this stage. This step is just about adding the length to
155
+ accumulator, so that it participates to final mixing.
156
+
157
+ ```
158
+ acc = acc + (u32)inputLength;
159
+ ```
160
+ */
161
+ acc = (acc + buffer.length) & 0xffffffff;
162
+
163
+ /*
164
+ Step 5. Consume remaining input
165
+ There may be up to 15 bytes remaining to consume from the input. The final stage will digest them according
166
+ to following pseudo-code :
167
+ ```
168
+ while (remainingLength >= 4) {
169
+ lane = read_32bit_little_endian(input_ptr);
170
+ acc = acc + lane * PRIME32_3;
171
+ acc = (acc <<< 17) * PRIME32_4;
172
+ input_ptr += 4; remainingLength -= 4;
173
+ }
174
+ ```
175
+ This process ensures that all input bytes are present in the final mix.
176
+ */
177
+
178
+ const limit = buffer.length - 4;
179
+ for (; offset <= limit; offset += 4) {
180
+ const i = offset;
181
+ const laneN0 = (b[i + 0] as any) + ((b[i + 1] as any) << 8);
182
+ const laneN1 = (b[i + 2] as any) + ((b[i + 3] as any) << 8);
183
+ const laneP = laneN0 * PRIME32_3 + ((laneN1 * PRIME32_3) << 16);
184
+ acc = (acc + laneP) & 0xffffffff;
185
+ acc = (acc << 17) | (acc >>> 15);
186
+ acc = ((acc & 0xffff) * PRIME32_4 + (((acc >>> 16) * PRIME32_4) << 16)) & 0xffffffff;
187
+ }
188
+
189
+ /*
190
+ ```
191
+ while (remainingLength >= 1) {
192
+ lane = read_byte(input_ptr);
193
+ acc = acc + lane * PRIME32_5;
194
+ acc = (acc <<< 11) * PRIME32_1;
195
+ input_ptr += 1; remainingLength -= 1;
196
+ }
197
+ ```
198
+ */
199
+
200
+ for (; offset < b.length; ++offset) {
201
+ const lane = b[offset];
202
+ acc = acc + (lane as any) * PRIME32_5;
203
+ acc = (acc << 11) | (acc >>> 21);
204
+ acc = ((acc & 0xffff) * PRIME32_1 + (((acc >>> 16) * PRIME32_1) << 16)) & 0xffffffff;
205
+ }
206
+
207
+ /*
208
+ Step 6. Final mix (avalanche)
209
+ The final mix ensures that all input bits have a chance to impact any bit in the output digest,
210
+ resulting in an unbiased distribution. This is also called avalanche effect.
211
+ ```
212
+ acc = acc xor (acc >> 15);
213
+ acc = acc * PRIME32_2;
214
+ acc = acc xor (acc >> 13);
215
+ acc = acc * PRIME32_3;
216
+ acc = acc xor (acc >> 16);
217
+ ```
218
+ */
219
+
220
+ acc = acc ^ (acc >>> 15);
221
+ acc = (((acc & 0xffff) * PRIME32_2) & 0xffffffff) + (((acc >>> 16) * PRIME32_2) << 16);
222
+ acc = acc ^ (acc >>> 13);
223
+ acc = (((acc & 0xffff) * PRIME32_3) & 0xffffffff) + (((acc >>> 16) * PRIME32_3) << 16);
224
+ acc = acc ^ (acc >>> 16);
225
+
226
+ // turn any negatives back into a positive number;
227
+ return acc < 0 ? acc + 4294967296 : acc;
228
+ }
@@ -0,0 +1,257 @@
1
+ import { ConvexError, v } from 'convex/values';
2
+ import { internalMutation, mutation, query } from './_generated/server';
3
+ import { characters } from '../data/characters';
4
+ import { insertInput } from './aiTown/insertInput';
5
+ import {
6
+ DEFAULT_NAME,
7
+ ENGINE_ACTION_DURATION,
8
+ IDLE_WORLD_TIMEOUT,
9
+ WORLD_HEARTBEAT_INTERVAL,
10
+ } from './constants';
11
+ import { playerId } from './aiTown/ids';
12
+ import { kickEngine, startEngine, stopEngine } from './aiTown/main';
13
+ import { engineInsertInput } from './engine/abstractGame';
14
+
15
+ export const defaultWorldStatus = query({
16
+ handler: async (ctx) => {
17
+ const worldStatus = await ctx.db
18
+ .query('worldStatus')
19
+ .filter((q) => q.eq(q.field('isDefault'), true))
20
+ .first();
21
+ return worldStatus;
22
+ },
23
+ });
24
+
25
+ export const heartbeatWorld = mutation({
26
+ args: {
27
+ worldId: v.id('worlds'),
28
+ },
29
+ handler: async (ctx, args) => {
30
+ const worldStatus = await ctx.db
31
+ .query('worldStatus')
32
+ .withIndex('worldId', (q) => q.eq('worldId', args.worldId))
33
+ .first();
34
+ if (!worldStatus) {
35
+ throw new Error(`Invalid world ID: ${args.worldId}`);
36
+ }
37
+ const now = Date.now();
38
+
39
+ // Skip the update (and then potentially make the transaction readonly)
40
+ // if it's been viewed sufficiently recently..
41
+ if (!worldStatus.lastViewed || worldStatus.lastViewed < now - WORLD_HEARTBEAT_INTERVAL / 2) {
42
+ await ctx.db.patch(worldStatus._id, {
43
+ lastViewed: Math.max(worldStatus.lastViewed ?? now, now),
44
+ });
45
+ }
46
+
47
+ // Restart inactive worlds, but leave worlds explicitly stopped by the developer alone.
48
+ if (worldStatus.status === 'stoppedByDeveloper') {
49
+ console.debug(`World ${worldStatus._id} is stopped by developer, not restarting.`);
50
+ }
51
+ if (worldStatus.status === 'inactive') {
52
+ console.log(`Restarting inactive world ${worldStatus._id}...`);
53
+ await ctx.db.patch(worldStatus._id, { status: 'running' });
54
+ await startEngine(ctx, worldStatus.worldId);
55
+ }
56
+ },
57
+ });
58
+
59
+ export const stopInactiveWorlds = internalMutation({
60
+ handler: async (ctx) => {
61
+ const cutoff = Date.now() - IDLE_WORLD_TIMEOUT;
62
+ const worlds = await ctx.db.query('worldStatus').collect();
63
+ for (const worldStatus of worlds) {
64
+ if (cutoff < worldStatus.lastViewed || worldStatus.status !== 'running') {
65
+ continue;
66
+ }
67
+ console.log(`Stopping inactive world ${worldStatus._id}`);
68
+ await ctx.db.patch(worldStatus._id, { status: 'inactive' });
69
+ await stopEngine(ctx, worldStatus.worldId);
70
+ }
71
+ },
72
+ });
73
+
74
+ export const restartDeadWorlds = internalMutation({
75
+ handler: async (ctx) => {
76
+ const now = Date.now();
77
+
78
+ // Restart an engine if it hasn't run for 2x its action duration.
79
+ const engineTimeout = now - ENGINE_ACTION_DURATION * 2;
80
+ const worlds = await ctx.db.query('worldStatus').collect();
81
+ for (const worldStatus of worlds) {
82
+ if (worldStatus.status !== 'running') {
83
+ continue;
84
+ }
85
+ const engine = await ctx.db.get(worldStatus.engineId);
86
+ if (!engine) {
87
+ throw new Error(`Invalid engine ID: ${worldStatus.engineId}`);
88
+ }
89
+ if (engine.currentTime && engine.currentTime < engineTimeout) {
90
+ console.warn(`Restarting dead engine ${engine._id}...`);
91
+ await kickEngine(ctx, worldStatus.worldId);
92
+ }
93
+ }
94
+ },
95
+ });
96
+
97
+ export const userStatus = query({
98
+ args: {
99
+ worldId: v.id('worlds'),
100
+ },
101
+ handler: async (ctx, args) => {
102
+ // const identity = await ctx.auth.getUserIdentity();
103
+ // if (!identity) {
104
+ // return null;
105
+ // }
106
+ // return identity.tokenIdentifier;
107
+ return DEFAULT_NAME;
108
+ },
109
+ });
110
+
111
+ export const joinWorld = mutation({
112
+ args: {
113
+ worldId: v.id('worlds'),
114
+ },
115
+ handler: async (ctx, args) => {
116
+ // const identity = await ctx.auth.getUserIdentity();
117
+ // if (!identity) {
118
+ // throw new ConvexError(`Not logged in`);
119
+ // }
120
+ // const name =
121
+ // identity.givenName || identity.nickname || (identity.email && identity.email.split('@')[0]);
122
+ const name = DEFAULT_NAME;
123
+
124
+ // if (!name) {
125
+ // throw new ConvexError(`Missing name on ${JSON.stringify(identity)}`);
126
+ // }
127
+ const world = await ctx.db.get(args.worldId);
128
+ if (!world) {
129
+ throw new ConvexError(`Invalid world ID: ${args.worldId}`);
130
+ }
131
+ // const { tokenIdentifier } = identity;
132
+ return await insertInput(ctx, world._id, 'join', {
133
+ name,
134
+ character: characters[Math.floor(Math.random() * characters.length)].name,
135
+ description: `${DEFAULT_NAME} is a human player`,
136
+ // description: `${identity.givenName} is a human player`,
137
+ tokenIdentifier: DEFAULT_NAME,
138
+ });
139
+ },
140
+ });
141
+
142
+ export const leaveWorld = mutation({
143
+ args: {
144
+ worldId: v.id('worlds'),
145
+ },
146
+ handler: async (ctx, args) => {
147
+ // const identity = await ctx.auth.getUserIdentity();
148
+ // if (!identity) {
149
+ // throw new Error(`Not logged in`);
150
+ // }
151
+ // const { tokenIdentifier } = identity;
152
+ const world = await ctx.db.get(args.worldId);
153
+ if (!world) {
154
+ throw new Error(`Invalid world ID: ${args.worldId}`);
155
+ }
156
+ // const existingPlayer = world.players.find((p) => p.human === tokenIdentifier);
157
+ const existingPlayer = world.players.find((p) => p.human === DEFAULT_NAME);
158
+ if (!existingPlayer) {
159
+ return;
160
+ }
161
+ await insertInput(ctx, world._id, 'leave', {
162
+ playerId: existingPlayer.id,
163
+ });
164
+ },
165
+ });
166
+
167
+ export const sendWorldInput = mutation({
168
+ args: {
169
+ engineId: v.id('engines'),
170
+ name: v.string(),
171
+ args: v.any(),
172
+ },
173
+ handler: async (ctx, args) => {
174
+ // const identity = await ctx.auth.getUserIdentity();
175
+ // if (!identity) {
176
+ // throw new Error(`Not logged in`);
177
+ // }
178
+ return await engineInsertInput(ctx, args.engineId, args.name as any, args.args);
179
+ },
180
+ });
181
+
182
+ export const worldState = query({
183
+ args: {
184
+ worldId: v.id('worlds'),
185
+ },
186
+ handler: async (ctx, args) => {
187
+ const world = await ctx.db.get(args.worldId);
188
+ if (!world) {
189
+ throw new Error(`Invalid world ID: ${args.worldId}`);
190
+ }
191
+ const worldStatus = await ctx.db
192
+ .query('worldStatus')
193
+ .withIndex('worldId', (q) => q.eq('worldId', world._id))
194
+ .unique();
195
+ if (!worldStatus) {
196
+ throw new Error(`Invalid world status ID: ${world._id}`);
197
+ }
198
+ const engine = await ctx.db.get(worldStatus.engineId);
199
+ if (!engine) {
200
+ throw new Error(`Invalid engine ID: ${worldStatus.engineId}`);
201
+ }
202
+ return { world, engine };
203
+ },
204
+ });
205
+
206
+ export const gameDescriptions = query({
207
+ args: {
208
+ worldId: v.id('worlds'),
209
+ },
210
+ handler: async (ctx, args) => {
211
+ const playerDescriptions = await ctx.db
212
+ .query('playerDescriptions')
213
+ .withIndex('worldId', (q) => q.eq('worldId', args.worldId))
214
+ .collect();
215
+ const agentDescriptions = await ctx.db
216
+ .query('agentDescriptions')
217
+ .withIndex('worldId', (q) => q.eq('worldId', args.worldId))
218
+ .collect();
219
+ const worldMap = await ctx.db
220
+ .query('maps')
221
+ .withIndex('worldId', (q) => q.eq('worldId', args.worldId))
222
+ .first();
223
+ if (!worldMap) {
224
+ throw new Error(`No map for world: ${args.worldId}`);
225
+ }
226
+ return { worldMap, playerDescriptions, agentDescriptions };
227
+ },
228
+ });
229
+
230
+ export const previousConversation = query({
231
+ args: {
232
+ worldId: v.id('worlds'),
233
+ playerId,
234
+ },
235
+ handler: async (ctx, args) => {
236
+ // Walk the player's history in descending order, looking for a nonempty
237
+ // conversation.
238
+ const members = ctx.db
239
+ .query('participatedTogether')
240
+ .withIndex('playerHistory', (q) => q.eq('worldId', args.worldId).eq('player1', args.playerId))
241
+ .order('desc');
242
+
243
+ for await (const member of members) {
244
+ const conversation = await ctx.db
245
+ .query('archivedConversations')
246
+ .withIndex('worldId', (q) => q.eq('worldId', args.worldId).eq('id', member.conversationId))
247
+ .unique();
248
+ if (!conversation) {
249
+ throw new Error(`Invalid conversation ID: ${member.conversationId}`);
250
+ }
251
+ if (conversation.numMessages > 0) {
252
+ return conversation;
253
+ }
254
+ }
255
+ return null;
256
+ },
257
+ });
@@ -0,0 +1,45 @@
1
+ {"frames": {
2
+
3
+ "pixels_large1.png":
4
+ {
5
+ "frame": {"x":0,"y":0,"w":32,"h":32},
6
+ "rotated": false,
7
+ "trimmed": true,
8
+ "spriteSourceSize": {"x":0,"y":0,"w":32,"h":32},
9
+ "sourceSize": {"w":32,"h":32}
10
+ },
11
+ "pixels_large2.png":
12
+ {
13
+ "frame": {"x":32,"y":0,"w":32,"h":32},
14
+ "rotated": false,
15
+ "trimmed": true,
16
+ "spriteSourceSize": {"x":0,"y":0,"w":32,"h":32},
17
+ "sourceSize": {"w":32,"h":32}
18
+ },
19
+ "pixels_large3.png":
20
+ {
21
+ "frame": {"x":64,"y":0,"w":32,"h":32},
22
+ "rotated": false,
23
+ "trimmed": true,
24
+ "spriteSourceSize": {"x":0,"y":0,"w":32,"h":32},
25
+ "sourceSize": {"w":32,"h":32}
26
+ },
27
+ "pixels_large4.png":
28
+ {
29
+ "frame": {"x":96,"y":0,"w":32,"h":32},
30
+ "rotated": false,
31
+ "trimmed": true,
32
+ "spriteSourceSize": {"x":0,"y":0,"w":32,"h":32},
33
+ "sourceSize": {"w":32,"h":32}
34
+ }
35
+ },
36
+ "animations": {
37
+ "pixels_large": ["pixels_large1.png","pixels_large2.png","pixels_large3.png","pixels_large4.png"]
38
+ },
39
+ "meta": {
40
+ "image": "./spritesheets/campfire.png",
41
+ "format": "RGBA8888",
42
+ "size": {"w":128,"h":32},
43
+ "scale": "1"
44
+ }
45
+ }
@@ -0,0 +1,37 @@
1
+ {"frames": {
2
+
3
+ "pixels_large1.png":
4
+ {
5
+ "frame": {"x":0,"y":0,"w":32,"h":32},
6
+ "rotated": false,
7
+ "trimmed": true,
8
+ "spriteSourceSize": {"x":0,"y":0,"w":32,"h":32},
9
+ "sourceSize": {"w":32,"h":32}
10
+ },
11
+ "pixels_large2.png":
12
+ {
13
+ "frame": {"x":32,"y":0,"w":32,"h":32},
14
+ "rotated": false,
15
+ "trimmed": true,
16
+ "spriteSourceSize": {"x":0,"y":0,"w":32,"h":32},
17
+ "sourceSize": {"w":32,"h":32}
18
+ },
19
+ "pixels_large3.png":
20
+ {
21
+ "frame": {"x":64,"y":0,"w":32,"h":32},
22
+ "rotated": false,
23
+ "trimmed": true,
24
+ "spriteSourceSize": {"x":0,"y":0,"w":32,"h":32},
25
+ "sourceSize": {"w":32,"h":32}
26
+ }
27
+ },
28
+ "animations": {
29
+ "pixels_large": ["pixels_large1.png","pixels_large2.png","pixels_large3.png"]
30
+ },
31
+ "meta": {
32
+ "image": "./spritesheets/gentlesparkle32.png",
33
+ "format": "RGBA8888",
34
+ "size": {"w":192,"h":320},
35
+ "scale": "1"
36
+ }
37
+ }