-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy pathRemote-Explorer.ts
390 lines (342 loc) · 10.4 KB
/
Remote-Explorer.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
// organize-imports-ignore
import type { Chunk, WorldCoords } from '@darkforest_eth/types';
//@ts-ignore
import { locationIdFromDecStr } from 'https://cdn.skypack.dev/@darkforest_eth/serde';
import {
html,
render,
useEffect,
useState,
//@ts-ignore
} from 'https://unpkg.com/htm/preact/standalone.module.js';
import type MinerManager from '../src/Backend/Miner/MinerManager';
import type { MinerWorkerMessage } from '../src/_types/global/GlobalTypes';
type ExtendedMinerManager = MinerManager & {
url: string;
id: number;
chunkSize: number;
patternType: string;
};
const {
MinerManager: Miner,
SwissCheesePattern,
SpiralPattern,
TowardsCenterPattern,
TowardsCenterPatternV2,
} = df.getConstructors();
const NEW_CHUNK = 'DiscoveredNewChunk';
function getPattern(coords: WorldCoords, patternType: string, chunkSize: number) {
if (patternType === 'swiss') {
return new SwissCheesePattern(coords, chunkSize);
} else if (patternType === 'spiral') {
return new SpiralPattern(coords, chunkSize);
} else if (patternType === 'towardsCenter') {
return new TowardsCenterPattern(coords, chunkSize);
} else {
return new TowardsCenterPatternV2(coords, chunkSize);
}
}
class RemoteWorker implements Worker {
private url: string;
constructor(url: string) {
this.url = url;
}
async postMessage(msg: string) {
const msgJson: MinerWorkerMessage = JSON.parse(msg);
const resp = await fetch(this.url, {
method: 'POST',
body: JSON.stringify({
chunkFootprint: msgJson.chunkFootprint,
planetRarity: msgJson.planetRarity,
planetHashKey: msgJson.planetHashKey,
}),
headers: {
'Content-Type': 'application/json',
},
});
const exploredChunk = await resp.json();
const chunkCenter = {
x: exploredChunk.chunkFootprint.bottomLeft.x + exploredChunk.chunkFootprint.sideLength / 2,
y: exploredChunk.chunkFootprint.bottomLeft.y + exploredChunk.chunkFootprint.sideLength / 2,
};
exploredChunk.perlin = df.spaceTypePerlin(chunkCenter, false);
for (const planetLoc of exploredChunk.planetLocations) {
planetLoc.hash = locationIdFromDecStr(planetLoc.hash);
planetLoc.perlin = df.spaceTypePerlin({ x: planetLoc.coords.x, y: planetLoc.coords.y }, true);
planetLoc.biomebase = df.biomebasePerlin(
{ x: planetLoc.coords.x, y: planetLoc.coords.y },
true
);
}
this.onmessage({ data: JSON.stringify([exploredChunk, msgJson.jobId]) });
}
onmessage(_a: { data: string }) {
console.warn('Unimplemented: onmessage');
}
terminate() {
console.warn('Unimplemented: terminate');
}
onmessageerror() {
console.warn('Unimplemented: onmessageerror');
}
addEventListener() {
console.warn('Unimplemented: addEventListener');
}
removeEventListener() {
console.warn('Unimplemented: removeEventListener');
}
dispatchEvent(_event: Event): boolean {
return false;
}
onerror() {
console.warn('Unimplemented: onerror');
}
}
function Target() {
const wrapper = {
width: '1em',
height: '1em',
display: 'inline-block',
position: 'relative',
verticalAlign: 'text-bottom',
};
const svg = {
width: '100%',
height: '100%',
};
const path = {
fill: 'white',
};
return html`
<span style=${wrapper}>
<svg
style=${svg}
version="1.1"
xmlns="http://www.w3.org/2000/svg"
width="512"
height="512"
viewBox="0 0 512 512"
>
<path
style=${path}
d="M512 224h-50.462c-13.82-89.12-84.418-159.718-173.538-173.538v-50.462h-64v50.462c-89.12 13.82-159.718 84.418-173.538 173.538h-50.462v64h50.462c13.82 89.12 84.418 159.718 173.538 173.538v50.462h64v-50.462c89.12-13.82 159.718-84.418 173.538-173.538h50.462v-64zM396.411 224h-49.881c-9.642-27.275-31.255-48.889-58.53-58.53v-49.881c53.757 12.245 96.166 54.655 108.411 108.411zM256 288c-17.673 0-32-14.327-32-32s14.327-32 32-32c17.673 0 32 14.327 32 32s-14.327 32-32 32zM224 115.589v49.881c-27.275 9.641-48.889 31.255-58.53 58.53h-49.881c12.245-53.756 54.655-96.166 108.411-108.411zM115.589 288h49.881c9.641 27.275 31.255 48.889 58.53 58.53v49.881c-53.756-12.245-96.166-54.654-108.411-108.411zM288 396.411v-49.881c27.275-9.642 48.889-31.255 58.53-58.53h49.881c-12.245 53.757-54.654 96.166-108.411 108.411z"
></path>
</svg>
</span>
`;
}
function MinerUI({
miner,
onRemove,
}: {
miner: ExtendedMinerManager;
onRemove: (miner: ExtendedMinerManager) => void;
}) {
const [hashRate, setHashRate] = useState(0);
useEffect(() => {
const calcHash = (chunk: Chunk, miningTimeMillis: number) => {
df.addNewChunk(chunk);
const hashRate = chunk.chunkFootprint.sideLength ** 2 / (miningTimeMillis / 1000);
setHashRate(Math.floor(hashRate));
const res = miner.getCurrentlyExploringChunk();
if (res) {
const { bottomLeft, sideLength } = res;
ui?.setExtraMinerLocation?.(miner.id, {
x: bottomLeft.x + sideLength / 2,
y: bottomLeft.y + sideLength / 2,
});
} else {
ui?.removeExtraMinerLocation?.(miner.id);
}
};
miner.on(NEW_CHUNK, calcHash);
return () => {
miner.off(NEW_CHUNK, calcHash);
};
}, [miner]);
const wrapper = {
paddingBottom: '10px',
display: 'flex',
justifyContent: 'space-between',
whiteSpace: 'nowrap',
};
const buttonWrapper = {
width: '50px',
display: 'flex',
justifyContent: 'space-between',
};
const remove = () => {
onRemove(miner);
};
const [targeting, setTargeting] = useState(false);
const target = () => setTargeting(true);
useEffect(() => {
const hover = () => {
const coords = ui.getHoveringOverCoords();
if (coords) {
ui?.setExtraMinerLocation?.(miner.id, coords);
}
};
const click = () => {
window.removeEventListener('mousemove', hover);
window.removeEventListener('click', click);
const coords = ui.getHoveringOverCoords();
if (coords) {
const pattern = getPattern(coords, miner.patternType, miner.chunkSize);
miner.setMiningPattern(pattern);
}
miner.startExplore();
setTargeting(false);
};
if (targeting) {
miner.stopExplore();
window.addEventListener('mousemove', hover);
window.addEventListener('click', click);
}
return () => {
window.removeEventListener('mousemove', hover);
window.removeEventListener('click', click);
};
}, [targeting, miner]);
return html`
<div style=${wrapper}>
<span>${miner.url} - ${hashRate} hashes/sec</span>
<div style=${buttonWrapper}>
<button onClick=${target}><${Target} /></button>
<button onClick=${remove}>X</button>
</div>
</div>
`;
}
function App({
initialMiners = [],
addMiner,
removeMiner,
}: {
initialMiners: ExtendedMinerManager[];
addMiner: (url: string, patternType: string) => ExtendedMinerManager[];
removeMiner: (miner: ExtendedMinerManager) => ExtendedMinerManager[];
}) {
const wrapper = { display: 'flex' };
const input = {
flex: '1',
padding: '5px',
outline: 'none',
color: 'black',
};
const button = {
marginLeft: '5px',
outline: 'none',
};
const select = {
background: 'rgb(8,8,8)',
};
const [miners, setMiners] = useState(initialMiners);
const [nextUrl, setNextUrl] = useState<string | null>(null);
const [patternType, setPatternType] = useState('spiral');
const onChange = (evt: InputEvent) => {
setNextUrl((evt.target as HTMLInputElement).value);
};
const add = () => {
if (nextUrl) {
const miners = addMiner(nextUrl, patternType);
setMiners(miners);
setNextUrl(null);
}
};
const remove = (miner: ExtendedMinerManager) => {
const miners = removeMiner(miner);
setMiners(miners);
};
const changePattern = (evt: InputEvent) => {
setPatternType((evt.target as HTMLSelectElement).value);
};
return html`
<div>
${miners.map(
(miner: ExtendedMinerManager) => html`
<${MinerUI} key=${miner.url} miner=${miner} onRemove=${remove} />
`
)}
<div style=${wrapper}>
<df-text-input
style=${input}
value=${nextUrl}
onInput=${onChange}
placeholder="URL for explore server"
></df-text-input>
<select style=${select} value=${patternType} onChange=${changePattern}>
<option value="spiral">Spiral</option>
<option value="swiss">Swiss</option>
<option value="towardsCenter">TowardsCenter</option>
<option value="towardsCenterV2">TowardsCenterV2</option>
</select>
<df-button style=${button} onClick=${add}>Explore!</df-button>
</div>
</div>
`;
}
class RemoteExplorerPlugin implements DFPlugin {
private miners: ExtendedMinerManager[];
private id: number;
constructor() {
this.miners = [];
this.id = 0;
this.addMiner('http://0.0.0.0:8000/mine', 'spiral', 256);
}
addMiner = (url: string, patternType = 'spiral', chunkSize = 256) => {
// TODO: Somehow set a default coords
const pattern = getPattern({ x: 0, y: 0 }, patternType, chunkSize);
const miner = Miner.create(
df.getChunkStore(),
pattern,
df.getWorldRadius(),
df.planetRarity,
df.getHashConfig(),
false,
() => new RemoteWorker(url)
) as ExtendedMinerManager;
miner.url = url;
miner.id = this.id++;
miner.chunkSize = chunkSize;
miner.patternType = patternType;
miner.startExplore();
this.miners.push(miner);
return this.miners;
};
removeMiner = (miner: ExtendedMinerManager) => {
this.miners = this.miners.filter((m) => {
if (m === miner) {
ui?.removeExtraMinerLocation?.(m.id);
m.stopExplore();
m.destroy();
return false;
} else {
return true;
}
});
return this.miners;
};
async render(container: HTMLDivElement) {
container.style.minWidth = '450px';
container.style.width = 'auto';
render(
html`
<${App}
initialMiners=${this.miners}
addMiner=${this.addMiner}
removeMiner=${this.removeMiner}
/>
`,
container
);
}
destroy() {
for (const miner of this.miners) {
ui?.removeExtraMinerLocation?.(miner.id);
miner.stopExplore();
miner.destroy();
}
}
}
export default RemoteExplorerPlugin;