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.
- package/README.md +518 -0
- package/bin/solanapolis.js +197 -0
- package/convex/_generated/api.d.ts +175 -0
- package/convex/_generated/api.js +23 -0
- package/convex/_generated/dataModel.d.ts +60 -0
- package/convex/_generated/server.d.ts +143 -0
- package/convex/_generated/server.js +93 -0
- package/convex/agent/conversation.ts +352 -0
- package/convex/agent/embeddingsCache.ts +110 -0
- package/convex/agent/memory.ts +450 -0
- package/convex/agent/schema.ts +53 -0
- package/convex/aiChat.ts +54 -0
- package/convex/aiTown/agent.ts +382 -0
- package/convex/aiTown/agentDescription.ts +27 -0
- package/convex/aiTown/agentInputs.ts +155 -0
- package/convex/aiTown/agentOperations.ts +178 -0
- package/convex/aiTown/conversation.ts +395 -0
- package/convex/aiTown/conversationMembership.ts +38 -0
- package/convex/aiTown/game.ts +371 -0
- package/convex/aiTown/ids.ts +32 -0
- package/convex/aiTown/inputHandler.ts +9 -0
- package/convex/aiTown/inputs.ts +25 -0
- package/convex/aiTown/insertInput.ts +20 -0
- package/convex/aiTown/location.ts +32 -0
- package/convex/aiTown/main.ts +154 -0
- package/convex/aiTown/movement.ts +189 -0
- package/convex/aiTown/player.ts +310 -0
- package/convex/aiTown/playerDescription.ts +35 -0
- package/convex/aiTown/schema.ts +79 -0
- package/convex/aiTown/world.ts +65 -0
- package/convex/aiTown/worldMap.ts +74 -0
- package/convex/chat.ts +79 -0
- package/convex/constants.ts +78 -0
- package/convex/convex.config.ts +6 -0
- package/convex/crons.ts +89 -0
- package/convex/engine/abstractGame.ts +199 -0
- package/convex/engine/historicalObject.ts +355 -0
- package/convex/engine/schema.ts +56 -0
- package/convex/http.ts +36 -0
- package/convex/init.ts +110 -0
- package/convex/messages.ts +53 -0
- package/convex/npcCarAgents.ts +415 -0
- package/convex/schema.ts +61 -0
- package/convex/streaming.ts +23 -0
- package/convex/testing.ts +202 -0
- package/convex/tsconfig.json +18 -0
- package/convex/util/FastIntegerCompression.ts +221 -0
- package/convex/util/assertNever.ts +4 -0
- package/convex/util/asyncMap.ts +20 -0
- package/convex/util/compression.ts +71 -0
- package/convex/util/geometry.ts +132 -0
- package/convex/util/isSimpleObject.ts +11 -0
- package/convex/util/llm.ts +724 -0
- package/convex/util/minheap.ts +38 -0
- package/convex/util/object.ts +22 -0
- package/convex/util/sleep.ts +3 -0
- package/convex/util/types.ts +33 -0
- package/convex/util/xxhash.ts +228 -0
- package/convex/world.ts +257 -0
- package/data/animations/campfire.json +45 -0
- package/data/animations/gentlesparkle.json +37 -0
- package/data/animations/gentlesplash.json +61 -0
- package/data/animations/gentlewaterfall.json +61 -0
- package/data/animations/windmill.json +78 -0
- package/data/characters.ts +121 -0
- package/data/convertMap.js +74 -0
- package/data/gentle.js +330 -0
- package/data/spritesheets/f1.ts +75 -0
- package/data/spritesheets/f2.ts +75 -0
- package/data/spritesheets/f3.ts +75 -0
- package/data/spritesheets/f4.ts +75 -0
- package/data/spritesheets/f5.ts +75 -0
- package/data/spritesheets/f6.ts +75 -0
- package/data/spritesheets/f7.ts +75 -0
- package/data/spritesheets/f8.ts +75 -0
- package/data/spritesheets/p1.ts +59 -0
- package/data/spritesheets/p2.ts +59 -0
- package/data/spritesheets/p3.ts +59 -0
- package/data/spritesheets/player.ts +59 -0
- package/data/spritesheets/types.ts +26 -0
- package/eslint.config.mjs +37 -0
- package/next.config.ts +7 -0
- package/package.json +85 -0
- package/postcss.config.mjs +7 -0
- package/public/file.svg +1 -0
- package/public/globe.svg +1 -0
- package/public/helius-icon.svg +84 -0
- package/public/helius-logo.svg +85 -0
- package/public/next.svg +1 -0
- package/public/plane.glb +0 -0
- package/public/vercel.svg +1 -0
- package/public/window.svg +1 -0
- package/scripts/clear-city.ts +74 -0
- package/scripts/seed-wallets.ts +185 -0
- package/scripts/setup-webhook.ts +73 -0
- package/src/app/api/auth/callback/route.ts +6 -0
- package/src/app/api/auth/link-wallet/route.ts +6 -0
- package/src/app/api/auth/phantom/route.ts +6 -0
- package/src/app/api/broadcast-position/route.ts +59 -0
- package/src/app/api/leaderboard/route.ts +85 -0
- package/src/app/api/network-stats/route.ts +86 -0
- package/src/app/api/parcel-reward/route.ts +181 -0
- package/src/app/api/queue-status/route.ts +30 -0
- package/src/app/api/snapshots/route.ts +37 -0
- package/src/app/api/transactions/enhanced/route.ts +57 -0
- package/src/app/api/treasury/route.ts +83 -0
- package/src/app/api/wallet/[address]/balances/route.ts +124 -0
- package/src/app/api/wallet/[address]/identity/route.ts +32 -0
- package/src/app/api/wallet/[address]/route.ts +216 -0
- package/src/app/api/wallet/[address]/traded-tokens/route.ts +41 -0
- package/src/app/api/wallets/route.ts +68 -0
- package/src/app/api/webhooks/helius/route.ts +76 -0
- package/src/app/auth/callback/page.tsx +29 -0
- package/src/app/favicon.ico +0 -0
- package/src/app/globals.css +39 -0
- package/src/app/layout.tsx +43 -0
- package/src/app/page.tsx +16 -0
- package/src/components/AITownNPCs.tsx +206 -0
- package/src/components/ActivityFeed.tsx +189 -0
- package/src/components/AuthPanel.tsx +163 -0
- package/src/components/BeachScene.tsx +280 -0
- package/src/components/Building.tsx +138 -0
- package/src/components/CesiumFlight.tsx +1768 -0
- package/src/components/CesiumGlobe.tsx +616 -0
- package/src/components/CitizenCard.tsx +442 -0
- package/src/components/CitizenCardModal.tsx +153 -0
- package/src/components/CityGrid.tsx +313 -0
- package/src/components/CityLandmarks.tsx +427 -0
- package/src/components/CityScene.tsx +1289 -0
- package/src/components/CitySlotsBadge.tsx +68 -0
- package/src/components/CockpitHUD.tsx +460 -0
- package/src/components/ConvexWrapper.tsx +19 -0
- package/src/components/DubaiDistrict.tsx +630 -0
- package/src/components/FlightMiniMap.tsx +133 -0
- package/src/components/GameChat.tsx +383 -0
- package/src/components/GameHUD.tsx +393 -0
- package/src/components/Ground.tsx +14 -0
- package/src/components/HowItWorksModal.tsx +251 -0
- package/src/components/IngestionBanner.tsx +123 -0
- package/src/components/InstancedBuildings.tsx +316 -0
- package/src/components/InstancedCars.tsx +504 -0
- package/src/components/InstancedCityPlanes.tsx +259 -0
- package/src/components/InstancedHouses.tsx +246 -0
- package/src/components/InstancedLampPosts.tsx +201 -0
- package/src/components/InstancedResidentCars.tsx +357 -0
- package/src/components/InstancedRoadDashes.tsx +42 -0
- package/src/components/InstancedSkyscrapers.tsx +434 -0
- package/src/components/InstancedTrees.tsx +67 -0
- package/src/components/LeaderboardPanel.tsx +136 -0
- package/src/components/MultiplayerPlanes.tsx +128 -0
- package/src/components/NetworkStats.tsx +83 -0
- package/src/components/NewBuildingSpotlight.tsx +93 -0
- package/src/components/ParcelChallengeBanner.tsx +242 -0
- package/src/components/ParcelReward.tsx +191 -0
- package/src/components/Park.tsx +42 -0
- package/src/components/PhantomWrapper.tsx +22 -0
- package/src/components/PixelStreamViewer.tsx +335 -0
- package/src/components/PlaneMode.tsx +190 -0
- package/src/components/PlayerCar.tsx +211 -0
- package/src/components/PlayerPlane.tsx +255 -0
- package/src/components/ProjectileRenderer.tsx +249 -0
- package/src/components/QueueStatusBanner.tsx +86 -0
- package/src/components/RealPlayerTags.tsx +82 -0
- package/src/components/SceneLighting.tsx +382 -0
- package/src/components/SelectionBeam.tsx +59 -0
- package/src/components/SwapPanel.tsx +104 -0
- package/src/components/SwapParticles.tsx +237 -0
- package/src/components/TreasureGate.tsx +505 -0
- package/src/components/WalletPanel.tsx +421 -0
- package/src/components/WalletSearch.tsx +244 -0
- package/src/components/WelcomeOverlay.tsx +135 -0
- package/src/components/WindowTooltip.tsx +498 -0
- package/src/context/AuthContext.tsx +230 -0
- package/src/lib/bot-detection.ts +125 -0
- package/src/lib/building-math.ts +136 -0
- package/src/lib/building-shader.ts +253 -0
- package/src/lib/car-paths.ts +244 -0
- package/src/lib/car-system.ts +182 -0
- package/src/lib/city-constants.ts +29 -0
- package/src/lib/city-slots.ts +35 -0
- package/src/lib/city-zoning.ts +64 -0
- package/src/lib/collision-map.ts +147 -0
- package/src/lib/day-night.ts +252 -0
- package/src/lib/export-card.ts +28 -0
- package/src/lib/helius-webhook.ts +90 -0
- package/src/lib/helius.ts +74 -0
- package/src/lib/house-shader.ts +119 -0
- package/src/lib/mock-data.ts +56 -0
- package/src/lib/multiplayer-manager.ts +329 -0
- package/src/lib/plane-physics.ts +66 -0
- package/src/lib/player-car.ts +147 -0
- package/src/lib/player-plane.ts +200 -0
- package/src/lib/projectile-system.ts +272 -0
- package/src/lib/skyscraper-types.ts +52 -0
- package/src/lib/sound-engine.ts +464 -0
- package/src/lib/supabase-admin.ts +9 -0
- package/src/lib/supabase.ts +8 -0
- package/src/lib/swap-events.ts +70 -0
- package/src/middleware.ts +37 -0
- package/src/types/phantom.d.ts +16 -0
- package/src/types/wallet.ts +20 -0
- package/tsconfig.json +34 -0
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
import { xxHash32 } from '../util/xxhash';
|
|
2
|
+
import { compressSigned, uncompressSigned } from '../util/FastIntegerCompression';
|
|
3
|
+
import {
|
|
4
|
+
runLengthEncode,
|
|
5
|
+
deltaEncode,
|
|
6
|
+
quantize,
|
|
7
|
+
deltaDecode,
|
|
8
|
+
runLengthDecode,
|
|
9
|
+
unquantize,
|
|
10
|
+
} from '../util/compression';
|
|
11
|
+
|
|
12
|
+
// `HistoricalObject`s require the developer to pass in the
|
|
13
|
+
// field names that'll be tracked and sent down to the client.
|
|
14
|
+
//
|
|
15
|
+
// By default, the historical tracking will round each floating point
|
|
16
|
+
// value to an integer. The developer can specify more or less precision
|
|
17
|
+
// via the `precision` parameter: the table's quantization will maintain
|
|
18
|
+
// less than `1 / 2^precision` error. Note that higher precision values
|
|
19
|
+
// imply less error.
|
|
20
|
+
export type FieldConfig = Array<string | { name: string; precision: number }>;
|
|
21
|
+
|
|
22
|
+
// `HistoricalObject`s support at most 16 fields.
|
|
23
|
+
const MAX_FIELDS = 16;
|
|
24
|
+
|
|
25
|
+
const PACKED_VERSION = 1;
|
|
26
|
+
|
|
27
|
+
type NormalizedFieldConfig = Array<{
|
|
28
|
+
name: string;
|
|
29
|
+
precision: number;
|
|
30
|
+
}>;
|
|
31
|
+
|
|
32
|
+
// The `History` structure represents the history of a continuous
|
|
33
|
+
// value over all bounded time. Each sample represents a line
|
|
34
|
+
// segment that's extends to the previous sample's time inclusively
|
|
35
|
+
// and to the sample's time non-inclusively. We track an `initialValue`
|
|
36
|
+
// that goes to `-\infty` up until the first sample, and the final
|
|
37
|
+
// sample persists out to `+\infty`.
|
|
38
|
+
// ```
|
|
39
|
+
// ^
|
|
40
|
+
// position
|
|
41
|
+
// |
|
|
42
|
+
// samples[0].value - | x---------------o
|
|
43
|
+
// |
|
|
44
|
+
// samples[1].value - | x-------->
|
|
45
|
+
// |
|
|
46
|
+
// initialValue - <---------o
|
|
47
|
+
// |
|
|
48
|
+
// ------------------------------> time
|
|
49
|
+
// | |
|
|
50
|
+
// samples[0].time samples[1].time
|
|
51
|
+
// ```
|
|
52
|
+
export type History = {
|
|
53
|
+
initialValue: number;
|
|
54
|
+
samples: Sample[];
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
export type Sample = {
|
|
58
|
+
time: number;
|
|
59
|
+
value: number;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
// `HistoricalObject` tracks a set of numeric fields over time and
|
|
63
|
+
// supports compressing the fields' histories into a binary buffer.
|
|
64
|
+
// This can be useful for continuous properties like position, where
|
|
65
|
+
// we'd want to smoothly replay their tick-by-tick progress at a high
|
|
66
|
+
// frame rate on the client.
|
|
67
|
+
//
|
|
68
|
+
// `HistoricalObject`s have a few limitations:
|
|
69
|
+
// - Documents in a historical can only have up to 16 fields.
|
|
70
|
+
// - The historical tracking only applies to a specified list of fields,
|
|
71
|
+
// and these fields must match between the client and server.
|
|
72
|
+
export class HistoricalObject<T extends Record<string, number>> {
|
|
73
|
+
startTs?: number;
|
|
74
|
+
|
|
75
|
+
fieldConfig: NormalizedFieldConfig;
|
|
76
|
+
|
|
77
|
+
data: T;
|
|
78
|
+
history: Record<string, History> = {};
|
|
79
|
+
|
|
80
|
+
constructor(fields: FieldConfig, initialValue: T) {
|
|
81
|
+
if (fields.length >= MAX_FIELDS) {
|
|
82
|
+
throw new Error(`HistoricalObject can have at most ${MAX_FIELDS} fields.`);
|
|
83
|
+
}
|
|
84
|
+
this.fieldConfig = normalizeFieldConfig(fields);
|
|
85
|
+
this.checkShape(initialValue);
|
|
86
|
+
this.data = initialValue;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
historyLength() {
|
|
90
|
+
return Object.values(this.history)
|
|
91
|
+
.map((h) => h.samples.length)
|
|
92
|
+
.reduce((a, b) => a + b, 0);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
checkShape(data: any) {
|
|
96
|
+
for (const [key, value] of Object.entries(data)) {
|
|
97
|
+
if (!this.fieldConfig.find((f) => f.name === key)) {
|
|
98
|
+
throw new Error(`Cannot set undeclared field '${key}'`);
|
|
99
|
+
}
|
|
100
|
+
if (typeof value !== 'number') {
|
|
101
|
+
throw new Error(
|
|
102
|
+
`HistoricalObject only supports numeric values, found: ${JSON.stringify(value)}`,
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
update(now: number, data: T) {
|
|
109
|
+
this.checkShape(data);
|
|
110
|
+
for (const [key, value] of Object.entries(data)) {
|
|
111
|
+
const currentValue = this.data[key];
|
|
112
|
+
if (currentValue !== value) {
|
|
113
|
+
let history = this.history[key];
|
|
114
|
+
if (!history) {
|
|
115
|
+
this.history[key] = history = { initialValue: currentValue, samples: [] };
|
|
116
|
+
}
|
|
117
|
+
const { samples } = history;
|
|
118
|
+
let inserted = false;
|
|
119
|
+
if (samples.length > 0) {
|
|
120
|
+
const last = samples[samples.length - 1];
|
|
121
|
+
if (now < last.time) {
|
|
122
|
+
throw new Error(`Server time moving backwards: ${now} < ${last.time}`);
|
|
123
|
+
}
|
|
124
|
+
if (now === last.time) {
|
|
125
|
+
last.value = value;
|
|
126
|
+
inserted = true;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
if (!inserted) {
|
|
130
|
+
samples.push({ time: now, value });
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
this.data = data;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
pack(): ArrayBuffer | null {
|
|
138
|
+
if (this.historyLength() === 0) {
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
return packSampleRecord(this.fieldConfig, this.history);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Pack (normalized) field configuration into a binary buffer.
|
|
146
|
+
//
|
|
147
|
+
// Format:
|
|
148
|
+
// ```
|
|
149
|
+
// [ u8 version ]
|
|
150
|
+
// for each field config:
|
|
151
|
+
// [ u8 field name length ]
|
|
152
|
+
// [ UTF8 encoded field name ]
|
|
153
|
+
// [ u8 precision ]
|
|
154
|
+
// ```
|
|
155
|
+
function packFieldConfig(fields: NormalizedFieldConfig) {
|
|
156
|
+
const out = new ArrayBuffer(1024);
|
|
157
|
+
const outView = new DataView(out);
|
|
158
|
+
let pos = 0;
|
|
159
|
+
|
|
160
|
+
outView.setUint8(pos, PACKED_VERSION);
|
|
161
|
+
pos += 1;
|
|
162
|
+
|
|
163
|
+
const encoder = new TextEncoder();
|
|
164
|
+
for (const fieldConfig of fields) {
|
|
165
|
+
const name = encoder.encode(fieldConfig.name);
|
|
166
|
+
|
|
167
|
+
outView.setUint8(pos, name.length);
|
|
168
|
+
pos += 1;
|
|
169
|
+
|
|
170
|
+
new Uint8Array(out, pos, name.length).set(name);
|
|
171
|
+
pos += name.length;
|
|
172
|
+
|
|
173
|
+
outView.setUint8(pos, fieldConfig.precision);
|
|
174
|
+
pos += 1;
|
|
175
|
+
}
|
|
176
|
+
return out.slice(0, pos);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// Pack a document's sample record into a binary buffer.
|
|
180
|
+
//
|
|
181
|
+
// We encode each field's history with a few layered forms of
|
|
182
|
+
// compression:
|
|
183
|
+
// 1. Quantization: Turn each floating point number into an integer
|
|
184
|
+
// by multiplying by 2^precision and then `Math.floor()`.
|
|
185
|
+
// 2. Delta encoding: Assume that values are continuous and don't
|
|
186
|
+
// abruptly change over time, so their differences will be small.
|
|
187
|
+
// This step turns the large integers from (1) into small ones.
|
|
188
|
+
// 3. Run length encoding (optional): Assume that some quantities
|
|
189
|
+
// in the system will have constant velocity, so encode `k`
|
|
190
|
+
// repetitions of `n` as `[k, n]`. If run length encoding doesn't
|
|
191
|
+
// make (2) smaller, we skip it.
|
|
192
|
+
// 4. Varint encoding: Using FastIntegerCompression.js, we use a
|
|
193
|
+
// variable length integer encoding that uses fewer bytes for
|
|
194
|
+
// smaller numbers.
|
|
195
|
+
//
|
|
196
|
+
// Format:
|
|
197
|
+
// ```
|
|
198
|
+
// [ 4 byte xxhash of packed field config ]
|
|
199
|
+
//
|
|
200
|
+
// for each set field:
|
|
201
|
+
// [ 0 0 0 useRLE? ]
|
|
202
|
+
// [ u4 field number ]
|
|
203
|
+
//
|
|
204
|
+
// Sample timestamps:
|
|
205
|
+
// [ u64le initial timestamp ]
|
|
206
|
+
// [ u16le timestamp buffer length ]
|
|
207
|
+
// [ vint(RLE(delta(remaining timestamps)))]
|
|
208
|
+
//
|
|
209
|
+
// Sample values:
|
|
210
|
+
// [ u16le value buffer length ]
|
|
211
|
+
// [ vint(RLE?(delta([initialValue, ...values])))]
|
|
212
|
+
// ```
|
|
213
|
+
export function packSampleRecord(
|
|
214
|
+
fields: NormalizedFieldConfig,
|
|
215
|
+
sampleRecord: Record<string, History>,
|
|
216
|
+
): ArrayBuffer {
|
|
217
|
+
const out = new ArrayBuffer(65536);
|
|
218
|
+
const outView = new DataView(out);
|
|
219
|
+
let pos = 0;
|
|
220
|
+
|
|
221
|
+
const configHash = xxHash32(new Uint8Array(packFieldConfig(fields)));
|
|
222
|
+
outView.setUint32(pos, configHash, true);
|
|
223
|
+
pos += 4;
|
|
224
|
+
|
|
225
|
+
for (let fieldNumber = 0; fieldNumber < fields.length; fieldNumber += 1) {
|
|
226
|
+
const { name, precision } = fields[fieldNumber];
|
|
227
|
+
const history = sampleRecord[name];
|
|
228
|
+
if (!history || history.samples.length === 0) {
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const timestamps = history.samples.map((s) => Math.floor(s.time));
|
|
233
|
+
const initialTimestamp = timestamps[0];
|
|
234
|
+
const encodedTimestamps = runLengthEncode(deltaEncode(timestamps.slice(1), initialTimestamp));
|
|
235
|
+
const compressedTimestamps = compressSigned(encodedTimestamps);
|
|
236
|
+
if (compressedTimestamps.byteLength >= 1 << 16) {
|
|
237
|
+
throw new Error(`Compressed buffer too long: ${compressedTimestamps.byteLength}`);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const values = [history.initialValue, ...history.samples.map((s) => s.value)];
|
|
241
|
+
const quantized = quantize(values, precision);
|
|
242
|
+
const deltaEncoded = deltaEncode(quantized);
|
|
243
|
+
const runLengthEncoded = runLengthEncode(deltaEncoded);
|
|
244
|
+
|
|
245
|
+
// Decide if we're going to run length encode the values based on whether
|
|
246
|
+
// it actually made the encoded buffer smaller.
|
|
247
|
+
const useRLE = runLengthEncoded.length < deltaEncoded.length;
|
|
248
|
+
let fieldHeader = fieldNumber;
|
|
249
|
+
if (useRLE) {
|
|
250
|
+
fieldHeader |= 1 << 4;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const encoded = useRLE ? runLengthEncoded : deltaEncoded;
|
|
254
|
+
const compressed = compressSigned(encoded);
|
|
255
|
+
if (compressed.byteLength >= 1 << 16) {
|
|
256
|
+
throw new Error(`Compressed buffer too long: ${compressed.byteLength}`);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
outView.setUint8(pos, fieldHeader);
|
|
260
|
+
pos += 1;
|
|
261
|
+
|
|
262
|
+
outView.setBigUint64(pos, BigInt(initialTimestamp), true);
|
|
263
|
+
pos += 8;
|
|
264
|
+
|
|
265
|
+
outView.setUint16(pos, compressedTimestamps.byteLength, true);
|
|
266
|
+
pos += 2;
|
|
267
|
+
|
|
268
|
+
new Uint8Array(out, pos, compressedTimestamps.byteLength).set(
|
|
269
|
+
new Uint8Array(compressedTimestamps),
|
|
270
|
+
);
|
|
271
|
+
pos += compressedTimestamps.byteLength;
|
|
272
|
+
|
|
273
|
+
outView.setUint16(pos, compressed.byteLength, true);
|
|
274
|
+
pos += 2;
|
|
275
|
+
|
|
276
|
+
new Uint8Array(out, pos, compressed.byteLength).set(new Uint8Array(compressed));
|
|
277
|
+
pos += compressed.byteLength;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
return out.slice(0, pos);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export function unpackSampleRecord(fields: FieldConfig, buffer: ArrayBuffer) {
|
|
284
|
+
const view = new DataView(buffer);
|
|
285
|
+
let pos = 0;
|
|
286
|
+
|
|
287
|
+
const normalizedFields = normalizeFieldConfig(fields);
|
|
288
|
+
const expectedConfigHash = xxHash32(new Uint8Array(packFieldConfig(normalizedFields)));
|
|
289
|
+
|
|
290
|
+
const configHash = view.getUint32(pos, true);
|
|
291
|
+
pos += 4;
|
|
292
|
+
|
|
293
|
+
if (configHash !== expectedConfigHash) {
|
|
294
|
+
throw new Error(`Config hash mismatch: ${configHash} !== ${expectedConfigHash}`);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const out = {} as Record<string, History>;
|
|
298
|
+
while (pos < buffer.byteLength) {
|
|
299
|
+
const fieldHeader = view.getUint8(pos);
|
|
300
|
+
pos += 1;
|
|
301
|
+
|
|
302
|
+
const fieldNumber = fieldHeader & 0b00001111;
|
|
303
|
+
const useRLE = (fieldHeader & (1 << 4)) !== 0;
|
|
304
|
+
const fieldConfig = normalizedFields[fieldNumber];
|
|
305
|
+
if (!fieldConfig) {
|
|
306
|
+
throw new Error(`Invalid field number: ${fieldNumber}`);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const initialTimestamp = Number(view.getBigUint64(pos, true));
|
|
310
|
+
pos += 8;
|
|
311
|
+
|
|
312
|
+
const compressedTimestampLength = view.getUint16(pos, true);
|
|
313
|
+
pos += 2;
|
|
314
|
+
|
|
315
|
+
const compressedTimestampBuffer = buffer.slice(pos, pos + compressedTimestampLength);
|
|
316
|
+
pos += compressedTimestampLength;
|
|
317
|
+
|
|
318
|
+
const timestamps = [
|
|
319
|
+
initialTimestamp,
|
|
320
|
+
...deltaDecode(
|
|
321
|
+
runLengthDecode(uncompressSigned(compressedTimestampBuffer)),
|
|
322
|
+
initialTimestamp,
|
|
323
|
+
),
|
|
324
|
+
];
|
|
325
|
+
|
|
326
|
+
const compressedLength = view.getUint16(pos, true);
|
|
327
|
+
pos += 2;
|
|
328
|
+
|
|
329
|
+
const compressedBuffer = buffer.slice(pos, pos + compressedLength);
|
|
330
|
+
pos += compressedLength;
|
|
331
|
+
|
|
332
|
+
const encoded = uncompressSigned(compressedBuffer);
|
|
333
|
+
const deltaEncoded = useRLE ? runLengthDecode(encoded) : encoded;
|
|
334
|
+
const quantized = deltaDecode(deltaEncoded);
|
|
335
|
+
const values = unquantize(quantized, fieldConfig.precision);
|
|
336
|
+
|
|
337
|
+
if (timestamps.length + 1 !== values.length) {
|
|
338
|
+
throw new Error(`Invalid sample record: ${timestamps.length} + 1 !== ${values.length}`);
|
|
339
|
+
}
|
|
340
|
+
const initialValue = values[0];
|
|
341
|
+
const samples = [];
|
|
342
|
+
for (let i = 0; i < timestamps.length; i++) {
|
|
343
|
+
const time = timestamps[i];
|
|
344
|
+
const value = values[i + 1];
|
|
345
|
+
samples.push({ value, time });
|
|
346
|
+
}
|
|
347
|
+
const history = { initialValue, samples };
|
|
348
|
+
out[fieldConfig.name] = history;
|
|
349
|
+
}
|
|
350
|
+
return out;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function normalizeFieldConfig(fields: FieldConfig): NormalizedFieldConfig {
|
|
354
|
+
return fields.map((f) => (typeof f === 'string' ? { name: f, precision: 0 } : f));
|
|
355
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { defineTable } from 'convex/server';
|
|
2
|
+
import { Infer, v } from 'convex/values';
|
|
3
|
+
|
|
4
|
+
const input = v.object({
|
|
5
|
+
// Inputs are scoped to a single engine.
|
|
6
|
+
engineId: v.id('engines'),
|
|
7
|
+
|
|
8
|
+
// Monotonically increasing input number within a world starting at 0.
|
|
9
|
+
number: v.number(),
|
|
10
|
+
|
|
11
|
+
// Name of the input handler to run.
|
|
12
|
+
name: v.string(),
|
|
13
|
+
// Dynamically typed arguments and return value for the input handler. We'll
|
|
14
|
+
// provide type safety at a higher layer.
|
|
15
|
+
args: v.any(),
|
|
16
|
+
returnValue: v.optional(
|
|
17
|
+
v.union(
|
|
18
|
+
v.object({
|
|
19
|
+
kind: v.literal('ok'),
|
|
20
|
+
value: v.any(),
|
|
21
|
+
}),
|
|
22
|
+
v.object({
|
|
23
|
+
kind: v.literal('error'),
|
|
24
|
+
message: v.string(),
|
|
25
|
+
}),
|
|
26
|
+
),
|
|
27
|
+
),
|
|
28
|
+
|
|
29
|
+
// Timestamp when the server received the input. This timestamp is best-effort,
|
|
30
|
+
// since we don't guarantee strict monotonicity here. So, an input may not get
|
|
31
|
+
// assigned to the engine step whose time interval contains this timestamp.
|
|
32
|
+
received: v.number(),
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
export const engine = v.object({
|
|
36
|
+
// What is the current simulation time for the engine? Monotonically increasing.
|
|
37
|
+
currentTime: v.optional(v.number()),
|
|
38
|
+
// What was `currentTime` for the preceding step of the engine?
|
|
39
|
+
lastStepTs: v.optional(v.number()),
|
|
40
|
+
|
|
41
|
+
// How far has the engine processed in the input queue?
|
|
42
|
+
processedInputNumber: v.optional(v.number()),
|
|
43
|
+
|
|
44
|
+
running: v.boolean(),
|
|
45
|
+
|
|
46
|
+
// Monotonically increasing counter that serializes all engine runs. If we ever
|
|
47
|
+
// end up with two steps overlapping in time, this counter will force them to
|
|
48
|
+
// conflict.
|
|
49
|
+
generationNumber: v.number(),
|
|
50
|
+
});
|
|
51
|
+
export type Engine = Infer<typeof engine>;
|
|
52
|
+
|
|
53
|
+
export const engineTables = {
|
|
54
|
+
inputs: defineTable(input).index('byInputNumber', ['engineId', 'number']),
|
|
55
|
+
engines: defineTable(engine),
|
|
56
|
+
};
|
package/convex/http.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { httpRouter } from "convex/server";
|
|
2
|
+
import { streamAiChat } from "./aiChat";
|
|
3
|
+
import { httpAction } from "./_generated/server";
|
|
4
|
+
|
|
5
|
+
const http = httpRouter();
|
|
6
|
+
|
|
7
|
+
http.route({
|
|
8
|
+
path: "/ai-chat-stream",
|
|
9
|
+
method: "POST",
|
|
10
|
+
handler: streamAiChat,
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
http.route({
|
|
14
|
+
path: "/ai-chat-stream",
|
|
15
|
+
method: "OPTIONS",
|
|
16
|
+
handler: httpAction(async (_, request) => {
|
|
17
|
+
const headers = request.headers;
|
|
18
|
+
if (
|
|
19
|
+
headers.get("Origin") !== null &&
|
|
20
|
+
headers.get("Access-Control-Request-Method") !== null &&
|
|
21
|
+
headers.get("Access-Control-Request-Headers") !== null
|
|
22
|
+
) {
|
|
23
|
+
return new Response(null, {
|
|
24
|
+
headers: new Headers({
|
|
25
|
+
"Access-Control-Allow-Origin": "*",
|
|
26
|
+
"Access-Control-Allow-Methods": "POST",
|
|
27
|
+
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
|
28
|
+
"Access-Control-Max-Age": "86400",
|
|
29
|
+
}),
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
return new Response();
|
|
33
|
+
}),
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
export default http;
|
package/convex/init.ts
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { v } from 'convex/values';
|
|
2
|
+
import { internal } from './_generated/api';
|
|
3
|
+
import { DatabaseReader, MutationCtx, mutation } from './_generated/server';
|
|
4
|
+
import { Descriptions } from '../data/characters';
|
|
5
|
+
import * as map from '../data/gentle';
|
|
6
|
+
import { insertInput } from './aiTown/insertInput';
|
|
7
|
+
import { Id } from './_generated/dataModel';
|
|
8
|
+
import { createEngine } from './aiTown/main';
|
|
9
|
+
import { ENGINE_ACTION_DURATION } from './constants';
|
|
10
|
+
const init = mutation({
|
|
11
|
+
args: {
|
|
12
|
+
numAgents: v.optional(v.number()),
|
|
13
|
+
},
|
|
14
|
+
handler: async (ctx, args) => {
|
|
15
|
+
const { worldStatus, engine } = await getOrCreateDefaultWorld(ctx);
|
|
16
|
+
if (worldStatus.status !== 'running') {
|
|
17
|
+
console.warn(
|
|
18
|
+
`Engine ${engine._id} is not active! Run "npx convex run testing:resume" to restart it.`,
|
|
19
|
+
);
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
const shouldCreate = await shouldCreateAgents(
|
|
23
|
+
ctx.db,
|
|
24
|
+
worldStatus.worldId,
|
|
25
|
+
worldStatus.engineId,
|
|
26
|
+
);
|
|
27
|
+
if (shouldCreate) {
|
|
28
|
+
const toCreate = args.numAgents !== undefined ? args.numAgents : Descriptions.length;
|
|
29
|
+
for (let i = 0; i < toCreate; i++) {
|
|
30
|
+
await insertInput(ctx, worldStatus.worldId, 'createAgent', {
|
|
31
|
+
descriptionIndex: i % Descriptions.length,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
export default init;
|
|
38
|
+
|
|
39
|
+
async function getOrCreateDefaultWorld(ctx: MutationCtx) {
|
|
40
|
+
const now = Date.now();
|
|
41
|
+
|
|
42
|
+
let worldStatus = await ctx.db
|
|
43
|
+
.query('worldStatus')
|
|
44
|
+
.filter((q) => q.eq(q.field('isDefault'), true))
|
|
45
|
+
.unique();
|
|
46
|
+
if (worldStatus) {
|
|
47
|
+
const engine = (await ctx.db.get(worldStatus.engineId))!;
|
|
48
|
+
return { worldStatus, engine };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const engineId = await createEngine(ctx);
|
|
52
|
+
const engine = (await ctx.db.get(engineId))!;
|
|
53
|
+
const worldId = await ctx.db.insert('worlds', {
|
|
54
|
+
nextId: 0,
|
|
55
|
+
agents: [],
|
|
56
|
+
conversations: [],
|
|
57
|
+
players: [],
|
|
58
|
+
});
|
|
59
|
+
const worldStatusId = await ctx.db.insert('worldStatus', {
|
|
60
|
+
engineId: engineId,
|
|
61
|
+
isDefault: true,
|
|
62
|
+
lastViewed: now,
|
|
63
|
+
status: 'running',
|
|
64
|
+
worldId: worldId,
|
|
65
|
+
});
|
|
66
|
+
worldStatus = (await ctx.db.get(worldStatusId))!;
|
|
67
|
+
await ctx.db.insert('maps', {
|
|
68
|
+
worldId,
|
|
69
|
+
width: map.mapwidth,
|
|
70
|
+
height: map.mapheight,
|
|
71
|
+
tileSetUrl: map.tilesetpath,
|
|
72
|
+
tileSetDimX: map.tilesetpxw,
|
|
73
|
+
tileSetDimY: map.tilesetpxh,
|
|
74
|
+
tileDim: map.tiledim,
|
|
75
|
+
bgTiles: map.bgtiles,
|
|
76
|
+
objectTiles: map.objmap,
|
|
77
|
+
animatedSprites: map.animatedsprites,
|
|
78
|
+
});
|
|
79
|
+
await ctx.scheduler.runAfter(0, internal.aiTown.main.runStep, {
|
|
80
|
+
worldId,
|
|
81
|
+
generationNumber: engine.generationNumber,
|
|
82
|
+
maxDuration: ENGINE_ACTION_DURATION,
|
|
83
|
+
});
|
|
84
|
+
return { worldStatus, engine };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function shouldCreateAgents(
|
|
88
|
+
db: DatabaseReader,
|
|
89
|
+
worldId: Id<'worlds'>,
|
|
90
|
+
engineId: Id<'engines'>,
|
|
91
|
+
) {
|
|
92
|
+
const world = await db.get(worldId);
|
|
93
|
+
if (!world) {
|
|
94
|
+
throw new Error(`Invalid world ID: ${worldId}`);
|
|
95
|
+
}
|
|
96
|
+
if (world.agents.length > 0) {
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
const unactionedJoinInputs = await db
|
|
100
|
+
.query('inputs')
|
|
101
|
+
.withIndex('byInputNumber', (q) => q.eq('engineId', engineId))
|
|
102
|
+
.order('asc')
|
|
103
|
+
.filter((q) => q.eq(q.field('name'), 'createAgent'))
|
|
104
|
+
.filter((q) => q.eq(q.field('returnValue'), undefined))
|
|
105
|
+
.first();
|
|
106
|
+
if (unactionedJoinInputs) {
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { v } from 'convex/values';
|
|
2
|
+
import { mutation, query } from './_generated/server';
|
|
3
|
+
import { insertInput } from './aiTown/insertInput';
|
|
4
|
+
import { conversationId, playerId } from './aiTown/ids';
|
|
5
|
+
|
|
6
|
+
export const listMessages = query({
|
|
7
|
+
args: {
|
|
8
|
+
worldId: v.id('worlds'),
|
|
9
|
+
conversationId,
|
|
10
|
+
},
|
|
11
|
+
handler: async (ctx, args) => {
|
|
12
|
+
const messages = await ctx.db
|
|
13
|
+
.query('messages')
|
|
14
|
+
.withIndex('conversationId', (q) => q.eq('worldId', args.worldId).eq('conversationId', args.conversationId))
|
|
15
|
+
.collect();
|
|
16
|
+
const out = [];
|
|
17
|
+
for (const message of messages) {
|
|
18
|
+
const playerDescription = await ctx.db
|
|
19
|
+
.query('playerDescriptions')
|
|
20
|
+
.withIndex('worldId', (q) => q.eq('worldId', args.worldId).eq('playerId', message.author))
|
|
21
|
+
.first();
|
|
22
|
+
if (!playerDescription) {
|
|
23
|
+
throw new Error(`Invalid author ID: ${message.author}`);
|
|
24
|
+
}
|
|
25
|
+
out.push({ ...message, authorName: playerDescription.name });
|
|
26
|
+
}
|
|
27
|
+
return out;
|
|
28
|
+
},
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
export const writeMessage = mutation({
|
|
32
|
+
args: {
|
|
33
|
+
worldId: v.id('worlds'),
|
|
34
|
+
conversationId,
|
|
35
|
+
messageUuid: v.string(),
|
|
36
|
+
playerId,
|
|
37
|
+
text: v.string(),
|
|
38
|
+
},
|
|
39
|
+
handler: async (ctx, args) => {
|
|
40
|
+
await ctx.db.insert('messages', {
|
|
41
|
+
conversationId: args.conversationId,
|
|
42
|
+
author: args.playerId,
|
|
43
|
+
messageUuid: args.messageUuid,
|
|
44
|
+
text: args.text,
|
|
45
|
+
worldId: args.worldId,
|
|
46
|
+
});
|
|
47
|
+
await insertInput(ctx, args.worldId, 'finishSendingMessage', {
|
|
48
|
+
conversationId: args.conversationId,
|
|
49
|
+
playerId: args.playerId,
|
|
50
|
+
timestamp: Date.now(),
|
|
51
|
+
});
|
|
52
|
+
},
|
|
53
|
+
});
|