-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
neat-ts.ts
425 lines (365 loc) · 12 KB
/
neat-ts.ts
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import * as p5 from 'p5';
declare global {
interface Window {
draw?: () => void;
}
interface p5 {
resizeCanvas: any;
text: any;
textSize: any;
BOLD: any;
Text: any;
}
}
/**
* We're using TypeScript for now instead of CoffeeScript or Elixir because TypeScript provides static typing,
* which can help catch errors at compile time rather than at runtime. It also provides better tooling support
* with features like autocompletion and type checking. TypeScript is also a superset of JavaScript, which means
* any valid JavaScript code is also valid TypeScript code. This makes it easier to gradually adopt TypeScript in
* a JavaScript codebase.
*/
interface SpaceDataCache {
[key: string]: any;
}
/**
* This is a runtime instance of a space. They can be dehydrated to JSON
* and re-hydrated over the wire.
*/
class Space {
private _guid: string;
public typeConstructors: {[key: string]: {new(deserializedState: any): any}} = {};
// internal field instance references
private fieldInstances: {[key: string]: any} = {};
// remember the args we were passed at definition time
private fieldDefinitions: {[key: string]: any} = {};
private _hyperAddress: number[];
setHyperAddress(address: number[]): void {
this._hyperAddress = address;
console.warn(`My HyperAddress Is Now ${this._hyperAddress.join('.')}`);
}
// constructor() {
// this._guid = this.generateGUID();
// }
get guid(): string {
if(!this._guid){
this._guid = this.generateGUID();
}
return this._guid;
}
/**
* This is a simple implementation of the UUID v4 algorithm for generating unique identifiers.
* It replaces 'x' and 'y' characters in the template string with random hexadecimal digits,
* ensuring that the resulting string follows the 8-4-4-4-12 format of a UUID.
*/
private generateGUID(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
defineField(fieldName: string, fieldType: string, defaults: {[key: string]: any} = {}){
this.fieldDefinitions[fieldName] = {
fieldType: fieldType,
defaults: defaults
};
if(this.typeConstructors[fieldType]){
this.fieldInstances[fieldName] = new this.typeConstructors[fieldType](defaults);
} else {
console.error('Type ' + fieldType + ' does not exist.');
}
}
}
class KeyboardCommandHandler {
mappings: {command: string, key: string}[] = [{
command: 'moveForward',
key: 'w'
}, {
command: 'moveBackward',
key: 's'
}, {
command: 'moveLeft',
key: 'a'
}, {
command: 'moveRight',
key: 'd'
}, {
command: 'moveUp',
key: ' '
}, {
command: 'moveDown',
key: 'Shift'
}]
constructor(){
window.addEventListener('keydown', this.handleInput.bind(this));
}
private _eventHandlerMap: {[key: string]: Function} = {};
registerEventHandlerMap(eventHandlerMap: {[key: string]: Function}): void {
this._eventHandlerMap = eventHandlerMap;
}
handleInput(event: KeyboardEvent): void {
for(let mapping of this.mappings){
if(event.key === mapping.key){
this._eventHandlerMap[mapping.command]();
}
}
}
}
class Thing extends Space {
private _spaceID: string;
set spaceID(id: string){
this._spaceID = id;
}
get spaceID(): string {
return this._spaceID;
}
}
class Neat {
private loadedSpaceIDs: string[] = [];
private spaceDataCache: SpaceDataCache = {};
public typeConstructors: {[key: string]: new(...args: any[]) => any} = {};
private keyEvents: KeyboardCommandHandler;
constructor() {
console.log('Hello, world!');
this.keyEvents = new KeyboardCommandHandler();
}
public get registerKeymap() {
return (keymap: {[key: string]: Function}): void => {
this.keyEvents.registerEventHandlerMap(keymap);
}
}
newSpace(){
// console.log('newSpace');
let newSpace = new Space();
this.loadedSpaceIDs.push(newSpace.guid);
this.spaceDataCache[newSpace.guid] = newSpace;
return newSpace;
}
createThing(spaceID: string){
if(this.loadedSpaceIDs.includes(spaceID)){
let newThing = new Thing();
// current borrower id
newThing.spaceID = spaceID;
return newThing;
} else {
console.error('Space with ID ' + spaceID + ' does not exist.');
return null;
}
}
defineType(typeName: string, typeConstructor: {new(deserializedState: any): any}){
this.typeConstructors[typeName] = typeConstructor;
}
}
let neat: Neat;
/**
* A special "Thing" that keeps track of states (basically a finite state machine)
*/
class FSMThing extends Thing {
public _state: string;
public set state(state: string){
this._state = state;
}
public get state(): string {
return this._state;
}
}
/**
* A "Viewer" which extends the FSMThing.
* The Viewer holds a cachable, lazily evaluated State.
* State can be observed.
*/
class Viewer extends FSMThing {
// private _stateCache: string;
// public get state(): string {
// if(!this._stateCache){
// this._stateCache = super.state;
// }
// return this._stateCache;
// }
// public set state(state: string){
// this._stateCache = state;
// super.state = state;
// }
// todo: define "States" of Viewer
currentlyViewingHyperAddress: number[] = [0, 0, 0, 0];
constructor(){
super();
this.state = 'new';
}
resize(): void {
resizeCanvas(windowWidth, windowHeight);
}
draw(): void {
// using p5.js, render the currently viewed hyper address as text in white, bold, top left
fill(255);
textSize(32);
textFont('Helvetica');
textStyle(BOLD);
text(`hyperA:`+this.currentlyViewingHyperAddress.join('.'), 10, 100);
}
}
/**
* DeserializedState is a wrapper type for the deserialized state.
*/
type DeserializedState = {
[key: string]: any;
};
class StateSerializer extends Thing {
private _stateKey: string;
private _state: string;
// TODO: dynamic type casting for the deserialized state
private _deserializedState: any;
private _instance: any;
public get instance(): any {
this._instance = this._instance || this.freshInstance();
return this._instance;
}
public freshInstance(): any {
return new neat.typeConstructors[this._stateKey](this._deserializedState);
}
set stateKey(key: string){
this._stateKey = key;
}
get stateKey(): string {
return this._stateKey;
}
saveState(): void {
localStorage.setItem(this._stateKey, JSON.stringify(this._state));
}
loadState(): void {
let maybeNull = localStorage.getItem(this._stateKey);
if(maybeNull && typeof maybeNull === 'string'){
this._state = maybeNull;
}
try {
this._deserializedState = JSON.parse(this._state);
} catch (error) {
console.error('Failed to deserialize state:', error);
}
}
}
class IdentityMatrix {
private _pos: number[];
private _rot: number[];
private _scale: number[];
private _idMatrix: number[][];
constructor() {
this._pos = [0, 0, 0];
this._rot = [0, 0, 0];
this._scale = [1, 1, 1];
this._idMatrix = this.calculateIdentityMatrix();
}
get pos(): number[] {
return this._pos;
}
get rot(): number[] {
return this._rot;
}
get scale(): number[] {
return this._scale;
}
get idMatrix(): number[][] {
return this._idMatrix;
}
calculateIdentityMatrix(): number[][] {
let identityMatrix: number[][] = [
[1, 0, 0, this._pos[0]],
[0, 1, 0, this._pos[1]],
[0, 0, 1, this._pos[2]],
[0, 0, 0, 1]
];
// TODO: Implement rotation and scale transformations
return identityMatrix;
}
private _hash: string;
private _dirty: boolean = true;
toString(): string {
if (this._dirty) {
this._hash = '';
for (let i = 0; i < this._idMatrix.length; i++) {
for (let j = 0; j < this._idMatrix[i].length; j++) {
this._hash += this._idMatrix[i][j].toString(16);
}
}
this._dirty = false;
}
return this._hash;
}
operateOnMatrix(operation: Function): void {
// Implement the operation on the identity matrix
}
}
// domready; make a new Neat instance
document.addEventListener('DOMContentLoaded', function(){
let neat = new Neat();
(window as any).neat = neat;
(window as any).neat.newSpace();
let newThing = (window as any).neat.createThing((window as any).neat.loadedSpaceIDs[0]);
console.log(newThing);
neat.defineType("IdentityMatrix", IdentityMatrix);
// add a new "viewer"
let newViewer = new Viewer();
newViewer.spaceID = (window as any).neat.loadedSpaceIDs[0];
newViewer.state = 'new';
// define state "fields" (properties, valueChannels, valueStreams, Promises, etc...)
// newViewer.defineField('name', 'string');
// newViewer.defineField('viewMatrix', 'IdentityMatrix');
// // The 'modifications' field is an array of 'Modification' objects.
// newViewer.defineField('modifications', 'Modification[]');
// spaces are fractally nested,
// therefore, we only hold references to roots, parents, and children
// the rest of the space is a cacheable, lazily evaluated state
// let's define a root space with 4 nested spaces, each of which will, in turn,
// contain 3 nested spaces each, each of those will contain 2, and the final layer
// will contain 1 space each
// we will keep track (in the viewer) of our coordinates within this hyper-space
// we will use those coordinates as a basis for navigation within the hyper-space
// we will show how we can place arbitrary links between the hyperspaces,
// and how the AI navigation tool can either linearly traverse the hyperspace,
// or walk the tree of links to find the shortest path between two points
// and so much more, but this is just the mvp navigation demo
// so let's get started!
for(let i = 0; i < 4; i++){
for(let j = 0; j < 3; j++){
for(let k = 0; k < 2; k++){
for(let l = 0; l < 1; l++){
let spaceAtPoint = (window as any).neat.newSpace();
spaceAtPoint.setHyperAddress([i, j, k, l]);
}
}
}
}
neat.registerKeymap(
{
moveForward: function(){
newViewer.currentlyViewingHyperAddress[0]++;
},
moveBackward: function(){
newViewer.currentlyViewingHyperAddress[0]--;
},
moveLeft: function(){
newViewer.currentlyViewingHyperAddress[1]--;
},
moveRight: function(){
newViewer.currentlyViewingHyperAddress[1]++;
},
moveUp: function(){
newViewer.currentlyViewingHyperAddress[2]++;
},
moveDown: function(){
newViewer.currentlyViewingHyperAddress[2]--;
}
}
)
(window as any).draw = function(){
newViewer.draw();
} as () => void;
window.draw = function(){
newViewer.draw();
}
window.addEventListener('resize', function(){
newViewer.resize();
})
setTimeout(function(){
newViewer.resize();
},500);
});