-
Notifications
You must be signed in to change notification settings - Fork 0
/
Reality.lua
382 lines (320 loc) · 7.98 KB
/
Reality.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
local json = require('json')
local sqlite3 = require('lsqlite3')
RealityDb = RealityDb or sqlite3.open_memory()
RealityDbAdmin = RealityDbAdmin or require('DbAdmin').new(RealityDb)
--#region Initialization
SQLITE_TABLE_REALITY_ENTITIES = [[
CREATE TABLE IF NOT EXISTS Entities (
Id TEXT PRIMARY KEY,
LastUpdated INTEGER NOT NULL,
Position TEXT NOT NULL,
Type TEXT NOT NULL,
Metadata TEXT NOT NULL,
StateCode INTEGER NOT NULL DEFAULT 2
);
]]
-- State Codes
-- 0 - Hidden
-- 1 - VisibleAlways
-- 2 - VisibleRecent
function RealityDbInit()
RealityDb:exec(SQLITE_TABLE_REALITY_ENTITIES)
end
RealityInitialized = RealityInitialized or false
if (not RealityInitialized) then
RealityDbInit()
RealityInitialized = true
end
function SetStateCode(timestamp, entityId, stateCode)
RealityDbAdmin:exec(string.format([[
UPDATE Entities
SET StateCode = %d,
LastUpdated = %d
WHERE Id = '%s'
]],
stateCode or 2,
timestamp,
entityId
))
end
--#endregion
--#region Model
RealityInfo = RealityInfo or {
Parent = nil,
Name = 'UnknownReality',
Dimensions = 0,
Spawn = {},
['Render-With'] = '0D-Null',
}
RealityParameters = RealityParameters or {}
RealityEntitiesStatic = RealityEntitiesStatic or {}
--#endregion
--#region ReadHandlers
Handlers.add(
"Reality.Info",
Handlers.utils.hasMatchingTag("Action", "Reality.Info"),
function(msg)
print("Reality.Info")
Handlers.utils.reply(json.encode(RealityInfo))(msg)
end
)
Handlers.add(
"Reality.Parameters",
Handlers.utils.hasMatchingTag("Action", "Reality.Parameters"),
function(msg)
print("Reality.Parameters")
Handlers.utils.reply(json.encode(RealityParameters))(msg)
end
)
Handlers.add(
"Reality.EntitiesStatic",
Handlers.utils.hasMatchingTag("Action", "Reality.EntitiesStatic"),
function(msg)
print("Reality.EntitiesStatic")
Handlers.utils.reply(json.encode(RealityEntitiesStatic))(msg)
end
)
Handlers.add(
"Reality.EntitiesDynamic",
Handlers.utils.hasMatchingTag("Action", "Reality.EntitiesDynamic"),
function(msg)
print("Reality.EntitiesDynamic")
local data = json.decode(msg.Data)
if (not data) then
ReplyError(msg, "Invalid Data")
return
end
local queryTimestamp = data.Timestamp
-- Validate timestamp
if (type(queryTimestamp) ~= "number") then
ReplyError(msg, "Invalid Timestamp")
return
end
local isInitial = data.Initial or false
local additionalQuery = "LastUpdated > ?"
if (isInitial) then
additionalQuery = "(LastUpdated > ? AND StateCode == 2) OR StateCode == 1"
end
local query = RealityDb:prepare([[
SELECT *
FROM Entities
WHERE Id == ? OR ]] .. additionalQuery
)
query:bind_values(msg.From, queryTimestamp)
local entities = {}
for row in query:nrows() do
entities[row.Id] = {
Position = json.decode(row.Position),
Type = row.Type,
Metadata = json.decode(row.Metadata),
StateCode = row.StateCode,
}
end
Handlers.utils.reply(json.encode(entities))(msg)
end
)
--#endregion
--#region WriteHandlers
function ReplyError(msg, error)
print("[" .. msg.From .. " => " .. msg.Id .. "] Error: " .. error)
Send({
Target = msg.From,
Tags = {
MsgRef = msg.Id,
Result = "Error",
},
Error = error,
})
end
function ZeroesArray(size)
local arr = {}
for i = 1, size do
arr[i] = 0
end
return arr
end
function ValidatePosition(Position)
if (not Position) then
return false, "Position not found"
end
if (#Position ~= RealityInfo.Dimensions) then
return false, "Invalid Position length"
end
for i = 1, #Position do
if (type(Position[i]) ~= "number") then
return false, "Invalid Position value"
end
end
return true
end
ValidTypes = { "Unknown", "Avatar", "Hidden" }
function ValidateType(Type)
for i = 1, #ValidTypes do
if (Type == ValidTypes[i]) then
return true
end
end
return false
end
Handlers.add(
"Reality.EntityCreate",
Handlers.utils.hasMatchingTag("Action", "Reality.EntityCreate"),
function(msg)
print("Reality.EntityCreate")
local entityId = msg.From
local data = json.decode(msg.Data)
local Position = RealityInfo.Spawn or ZeroesArray(RealityInfo.Dimensions)
if (data.Position) then
local valid, error = ValidatePosition(data.Position)
if (not valid) then
ReplyError(msg, error)
return
end
Position = data.Position
end
local Type = "Unknown"
if (data.Type) then
if (not ValidateType(data.Type)) then
ReplyError(msg, "Invalid Type")
return
end
Type = data.Type
end
-- Is it necessary to validate this?
local Metadata = data.Metadata or {}
-- Ugly workaround for empty tables!
Metadata['_'] = false;
local stmt = RealityDb:prepare([[
INSERT INTO Entities (Id, LastUpdated, Position, Type, Metadata)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(Id) DO UPDATE SET
LastUpdated = excluded.LastUpdated,
Type = excluded.Type,
Metadata = excluded.Metadata,
StateCode = CASE WHEN StateCode == 0 THEN 2 ELSE StateCode END
]])
-- StateCode is reset to default, if it was hidden
stmt:bind_values(
entityId,
msg.Timestamp,
json.encode(Position),
Type,
json.encode(Metadata)
)
stmt:step()
stmt:finalize()
local result = {
[entityId] = {
Position = Position,
Type = Type,
Metadata = Metadata
}
}
Send({
Target = msg.From,
Tags = {
MsgRef = msg.Id,
Result = "OK",
},
Data = json.encode(result),
})
end
)
Handlers.add(
"Reality.EntityUpdatePosition",
Handlers.utils.hasMatchingTag("Action", "Reality.EntityUpdatePosition"),
function(msg)
print("Reality.EntityUpdatePosition")
local entityId = msg.From
local dbEntry = RealityDbAdmin:exec(string.format([[
SELECT * FROM Entities WHERE Id = '%s'
]],
entityId
))[1]
if (not dbEntry) then
ReplyError(msg, "Entity not found")
return
end
local data = json.decode(msg.Data)
local Position = data.Position
local valid, error = ValidatePosition(Position)
if (not valid) then
ReplyError(msg, error)
return
end
RealityDbAdmin:exec(string.format([[
UPDATE Entities
SET LastUpdated = %d, Position = '%s'
WHERE Id = '%s'
]],
msg.Timestamp,
json.encode(Position),
entityId
))
local result = {
[entityId] = {
Position = Position,
}
}
Send({
Target = msg.From,
Tags = {
MsgRef = msg.Id,
Result = "OK",
},
Data = json.encode(result),
})
end
)
Handlers.add(
"Reality.EntityHide",
Handlers.utils.hasMatchingTag("Action", "Reality.EntityHide"),
function(msg)
print("Reality.EntityHide")
local entityId = msg.Tags['EntityId'] or msg.From
local dbEntry = RealityDbAdmin:exec(string.format([[
SELECT * FROM Entities WHERE Id = '%s'
]],
entityId
))[1]
if (not dbEntry) then
ReplyError(msg, "Entity not found")
return
end
SetStateCode(msg.Timestamp, entityId, 0)
Send({
Target = msg.From,
Tags = {
MsgRef = msg.Id,
Result = "OK",
},
})
end
)
Handlers.add(
"Reality.EntityFix",
Handlers.utils.hasMatchingTag("Action", "Reality.EntityFix"),
function(msg)
print("Reality.EntityFix")
local entityId = msg.Tags['EntityId'] or msg.From
local dbEntry = RealityDbAdmin:exec(string.format([[
SELECT * FROM Entities WHERE Id = '%s'
]],
entityId
))[1]
if (not dbEntry) then
ReplyError(msg, "Entity not found")
return
end
SetStateCode(msg.Timestamp, entityId, 1)
Send({
Target = msg.From,
Tags = {
MsgRef = msg.Id,
Result = "OK",
},
})
end
)
--#endregion
return "Loaded Reality Protocol"