forked from pshenok/server-survival
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
1339 lines (1133 loc) · 49.1 KB
/
game.js
File metadata and controls
1339 lines (1133 loc) · 49.1 KB
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
STATE.sound = new SoundService();
// ==================== BALANCE OVERHAUL FUNCTIONS ====================
function calculateTargetRPS(gameTimeSeconds) {
// Logarithmic curve: fast growth early, plateaus later
// At 0s: 0.5, at 60s: ~2.5, at 180s: ~4, at 300s: ~5, at 600s: ~6.5
const base = CONFIG.survival.baseRPS;
const growth = Math.log(1 + gameTimeSeconds / 30) * 1.8;
return base + growth;
}
function getUpkeepMultiplier() {
if (STATE.gameMode !== 'survival') return 1.0;
if (!CONFIG.survival.upkeepScaling.enabled) return 1.0;
const gameTime = (performance.now() - STATE.gameStartTime) / 1000;
const progress = Math.min(gameTime / CONFIG.survival.upkeepScaling.scaleTime, 1.0);
const base = CONFIG.survival.upkeepScaling.baseMultiplier;
const max = CONFIG.survival.upkeepScaling.maxMultiplier;
// Smooth curve from base to max
return base + (max - base) * progress;
}
function updateFraudSpike(dt) {
if (STATE.gameMode !== 'survival') return;
if (!CONFIG.survival.fraudSpike.enabled) return;
STATE.fraudSpikeTimer += dt;
const interval = CONFIG.survival.fraudSpike.interval;
const duration = CONFIG.survival.fraudSpike.duration;
const warning = CONFIG.survival.fraudSpike.warningTime;
const cycleTime = STATE.fraudSpikeTimer % interval;
// Warning phase
if (cycleTime >= interval - warning && cycleTime < interval - warning + dt && !STATE.fraudSpikeActive) {
showFraudWarning();
}
// Start spike
if (cycleTime < dt && STATE.fraudSpikeTimer > warning) {
startFraudSpike();
}
// End spike
if (STATE.fraudSpikeActive && cycleTime >= duration && cycleTime < duration + dt) {
endFraudSpike();
}
}
function showFraudWarning() {
// Visual warning
const warning = document.createElement('div');
warning.id = 'fraud-warning';
warning.className = 'fixed top-1/3 left-1/2 transform -translate-x-1/2 text-center z-50 pointer-events-none';
warning.innerHTML = `
<div class="text-red-500 text-2xl font-bold animate-pulse">⚠️ DDoS INCOMING ⚠️</div>
<div class="text-red-300 text-sm">Fraud spike in 5 seconds!</div>
`;
document.body.appendChild(warning);
STATE.sound.playTone(400, 'sawtooth', 0.3);
STATE.sound.playTone(300, 'sawtooth', 0.3, 0.15);
setTimeout(() => warning.remove(), 4000);
}
function startFraudSpike() {
STATE.fraudSpikeActive = true;
// Store normal distribution
STATE.normalTrafficDist = { ...STATE.trafficDistribution };
// Apply spike distribution
const fraudPct = CONFIG.survival.fraudSpike.fraudPercent;
const remaining = 1 - fraudPct;
STATE.trafficDistribution = {
WEB: remaining * 0.5,
API: remaining * 0.5,
FRAUD: fraudPct
};
// Visual indicator
const indicator = document.createElement('div');
indicator.id = 'fraud-spike-indicator';
indicator.className = 'fixed top-4 left-1/2 transform -translate-x-1/2 z-40 pointer-events-none';
indicator.innerHTML = `
<div class="bg-red-900/80 border-2 border-red-500 rounded-lg px-4 py-2 animate-pulse">
<span class="text-red-400 font-bold">🔥 DDoS ATTACK ACTIVE 🔥</span>
</div>
`;
document.body.appendChild(indicator);
// Update mix display
const fraudEl = document.getElementById('mix-fraud');
if (fraudEl) fraudEl.className = 'text-red-500 font-bold animate-pulse';
}
function endFraudSpike() {
STATE.fraudSpikeActive = false;
// Restore normal distribution
if (STATE.normalTrafficDist) {
STATE.trafficDistribution = { ...STATE.normalTrafficDist };
STATE.normalTrafficDist = null;
}
// Remove indicator
const indicator = document.getElementById('fraud-spike-indicator');
if (indicator) indicator.remove();
// Reset mix display styling
const fraudEl = document.getElementById('mix-fraud');
if (fraudEl) fraudEl.className = 'text-purple-400';
STATE.sound.playSuccess();
}
// ==================== END BALANCE OVERHAUL FUNCTIONS ====================
const container = document.getElementById('canvas-container');
const scene = new THREE.Scene();
scene.background = new THREE.Color(CONFIG.colors.bg);
scene.fog = new THREE.FogExp2(CONFIG.colors.bg, 0.008);
let isDraggingNode = false;
let draggedNode = null;
let dragOffset = new THREE.Vector3();
const aspect = window.innerWidth / window.innerHeight;
const d = 50;
const camera = new THREE.OrthographicCamera(-d * aspect, d * aspect, d, -d, 1, 1000);
const cameraTarget = new THREE.Vector3(0, 0, 0);
let isIsometric = true;
resetCamera()
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
container.appendChild(renderer.domElement);
const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
scene.add(ambientLight);
const dirLight = new THREE.DirectionalLight(0xffffff, 0.8);
dirLight.position.set(20, 50, 20);
dirLight.castShadow = true;
dirLight.shadow.mapSize.width = 2048;
dirLight.shadow.mapSize.height = 2048;
scene.add(dirLight);
const gridHelper = new THREE.GridHelper(CONFIG.gridSize * CONFIG.tileSize, CONFIG.gridSize, CONFIG.colors.grid, CONFIG.colors.grid);
scene.add(gridHelper);
const serviceGroup = new THREE.Group();
const connectionGroup = new THREE.Group();
const requestGroup = new THREE.Group();
scene.add(serviceGroup);
scene.add(connectionGroup);
scene.add(requestGroup);
const internetGeo = new THREE.BoxGeometry(6, 1, 10);
const internetMat = new THREE.MeshStandardMaterial({ color: 0x111111, emissive: 0x00ffff, emissiveIntensity: 0.7, roughness: 0.2 });
const internetMesh = new THREE.Mesh(internetGeo, internetMat);
internetMesh.position.copy(STATE.internetNode.position);
internetMesh.castShadow = true;
internetMesh.receiveShadow = true;
scene.add(internetMesh);
STATE.internetNode.mesh = internetMesh;
const intRingGeo = new THREE.RingGeometry(7, 7.2, 32);
const intRingMat = new THREE.MeshStandardMaterial({ color: 0x00ffff, transparent: true, opacity: 0.2, side: THREE.DoubleSide });
const internetRing = new THREE.Mesh(intRingGeo, intRingMat);
internetRing.rotation.x = -Math.PI / 2;
internetRing.position.set(internetMesh.position.x, -internetMesh.position.y + 0.1, internetMesh.position.z);
scene.add(internetRing);
STATE.internetNode.ring = internetRing;
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
const plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
let isPanning = false;
let lastMouseX = 0;
let lastMouseY = 0;
const panSpeed = 0.1;
function resetGame(mode = 'survival') {
STATE.sound.init();
STATE.sound.playGameBGM();
STATE.gameMode = mode;
// Set budget based on mode
if (mode === 'sandbox') {
STATE.sandboxBudget = CONFIG.sandbox.defaultBudget;
STATE.money = STATE.sandboxBudget;
STATE.upkeepEnabled = CONFIG.sandbox.upkeepEnabled;
STATE.trafficDistribution = {
WEB: CONFIG.sandbox.trafficDistribution.WEB / 100,
API: CONFIG.sandbox.trafficDistribution.API / 100,
FRAUD: CONFIG.sandbox.trafficDistribution.FRAUD / 100
};
STATE.burstCount = CONFIG.sandbox.defaultBurstCount;
STATE.currentRPS = CONFIG.sandbox.defaultRPS;
} else {
STATE.money = CONFIG.survival.startBudget;
STATE.upkeepEnabled = true;
STATE.trafficDistribution = { ...CONFIG.survival.trafficDistribution };
STATE.currentRPS = 0.5;
}
STATE.reputation = 100;
STATE.requestsProcessed = 0;
STATE.services = [];
STATE.requests = [];
STATE.connections = [];
STATE.score = { total: 0, web: 0, api: 0, fraudBlocked: 0 };
STATE.isRunning = true;
STATE.lastTime = performance.now();
STATE.timeScale = 0;
STATE.spawnTimer = 0;
// Initialize balance overhaul state
STATE.gameStartTime = performance.now();
STATE.fraudSpikeTimer = 0;
STATE.fraudSpikeActive = false;
STATE.normalTrafficDist = null;
// Remove any leftover fraud spike indicators
const fraudWarning = document.getElementById('fraud-warning');
if (fraudWarning) fraudWarning.remove();
const fraudIndicator = document.getElementById('fraud-spike-indicator');
if (fraudIndicator) fraudIndicator.remove();
// Clear visual elements
while (serviceGroup.children.length > 0) {
serviceGroup.remove(serviceGroup.children[0]);
}
while (connectionGroup.children.length > 0) {
connectionGroup.remove(connectionGroup.children[0]);
}
while (requestGroup.children.length > 0) {
requestGroup.remove(requestGroup.children[0]);
}
STATE.internetNode.connections = [];
STATE.internetNode.position.set(
CONFIG.internetNodeStartPos.x,
CONFIG.internetNodeStartPos.y,
CONFIG.internetNodeStartPos.z
);
STATE.internetNode.mesh.position.set(
CONFIG.internetNodeStartPos.x,
CONFIG.internetNodeStartPos.y,
CONFIG.internetNodeStartPos.z
);
// Reset UI
document.querySelectorAll('.time-btn').forEach(b => b.classList.remove('active'));
document.getElementById('btn-pause').classList.add('active');
document.getElementById('btn-play').classList.add('pulse-green');
// Update UI displays
updateScoreUI();
// Mark game as started
STATE.gameStarted = true;
// Show/hide sandbox panel and objectives panel based on mode
const sandboxPanel = document.getElementById('sandboxPanel');
const objectivesPanel = document.getElementById('objectivesPanel');
if (mode === 'sandbox') {
// Show sandbox panel, hide objectives
if (sandboxPanel) {
sandboxPanel.classList.remove('hidden');
// Sync sandbox UI controls
syncInput('budget', STATE.sandboxBudget);
syncInput('rps', STATE.currentRPS);
syncInput('web', STATE.trafficDistribution.WEB * 100);
syncInput('api', STATE.trafficDistribution.API * 100);
syncInput('fraud', STATE.trafficDistribution.FRAUD * 100);
syncInput('burst', STATE.burstCount);
// Reset upkeep toggle button
const upkeepBtn = document.getElementById('upkeep-toggle');
if (upkeepBtn) {
upkeepBtn.textContent = STATE.upkeepEnabled ? 'Upkeep: ON' : 'Upkeep: OFF';
upkeepBtn.classList.toggle('bg-red-900/50', STATE.upkeepEnabled);
upkeepBtn.classList.toggle('bg-green-900/50', !STATE.upkeepEnabled);
}
}
if (objectivesPanel) objectivesPanel.classList.add('hidden');
} else {
// Show objectives, hide sandbox panel
if (sandboxPanel) sandboxPanel.classList.add('hidden');
if (objectivesPanel) objectivesPanel.classList.remove('hidden');
}
// Ensure loop is running
if (!STATE.animationId) {
animate(performance.now());
}
}
function restartGame() {
document.getElementById('modal').classList.add('hidden');
resetGame(STATE.gameMode);
}
// Initial setup - show menu, don't start game loop yet
setTimeout(() => {
showMainMenu();
}, 100);
function getIntersect(clientX, clientY) {
mouse.x = (clientX / window.innerWidth) * 2 - 1;
mouse.y = -(clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObjects(serviceGroup.children, true);
if (intersects.length > 0) {
let obj = intersects[0].object;
while (obj.parent && obj.parent !== serviceGroup) obj = obj.parent;
return { type: 'service', id: obj.userData.id, obj: obj };
}
const intInter = raycaster.intersectObject(STATE.internetNode.mesh);
if (intInter.length > 0) return { type: 'internet', id: 'internet', obj: STATE.internetNode.mesh };
const target = new THREE.Vector3();
raycaster.ray.intersectPlane(plane, target);
return { type: 'ground', pos: target };
}
function snapToGrid(vec) {
const s = CONFIG.tileSize;
return new THREE.Vector3(
Math.round(vec.x / s) * s,
0,
Math.round(vec.z / s) * s
);
}
function getTrafficType() {
const dist = STATE.trafficDistribution;
const total = dist.WEB + dist.API + dist.FRAUD;
if (total === 0) return TRAFFIC_TYPES.WEB;
const r = Math.random() * total;
if (r < dist.WEB) return TRAFFIC_TYPES.WEB;
if (r < dist.WEB + dist.API) return TRAFFIC_TYPES.API;
return TRAFFIC_TYPES.FRAUD;
}
function spawnRequest() {
const type = getTrafficType();
const req = new Request(type);
STATE.requests.push(req);
const conns = STATE.internetNode.connections;
if (conns.length > 0) {
const entryNodes = conns.map(id => STATE.services.find(s => s.id === id));
const wafEntry = entryNodes.find(s => s?.type === 'waf');
const target = wafEntry || entryNodes[Math.floor(Math.random() * entryNodes.length)];
if (target) req.flyTo(target); else failRequest(req);
} else failRequest(req);
}
function updateScore(req, outcome) {
const points = CONFIG.survival.SCORE_POINTS;
if (outcome === 'FRAUD_BLOCKED') {
STATE.score.fraudBlocked += points.FRAUD_BLOCKED_SCORE;
STATE.score.total += points.FRAUD_BLOCKED_SCORE;
STATE.sound.playFraudBlocked();
} else if (req.type === TRAFFIC_TYPES.FRAUD && outcome === 'FRAUD_PASSED') {
STATE.reputation += points.FRAUD_PASSED_REPUTATION;
console.warn(`FRAUD PASSED: ${points.FRAUD_PASSED_REPUTATION} Rep. (Critical Failure)`);
} else if (outcome === 'COMPLETED') {
if (req.type === TRAFFIC_TYPES.WEB) {
STATE.score.web += points.WEB_SCORE;
STATE.score.total += points.WEB_SCORE;
STATE.money += points.WEB_REWARD;
} else if (req.type === TRAFFIC_TYPES.API) {
STATE.score.api += points.API_SCORE;
STATE.score.total += points.API_SCORE;
STATE.money += points.API_REWARD;
}
} else if (outcome === 'FAILED') {
STATE.reputation += points.FAIL_REPUTATION;
STATE.score.total -= (req.type === TRAFFIC_TYPES.API ? points.API_SCORE : points.WEB_SCORE) / 2;
}
updateScoreUI();
}
function finishRequest(req) {
STATE.requestsProcessed++;
updateScore(req, 'COMPLETED');
removeRequest(req);
}
function failRequest(req) {
const failType = req.type === TRAFFIC_TYPES.FRAUD ? 'FRAUD_PASSED' : 'FAILED';
updateScore(req, failType);
STATE.sound.playFail();
req.mesh.material.color.setHex(CONFIG.colors.requestFail);
setTimeout(() => removeRequest(req), 500);
}
function removeRequest(req) {
req.destroy();
STATE.requests = STATE.requests.filter(r => r !== req);
}
function updateScoreUI() {
document.getElementById('total-score-display').innerText = STATE.score.total;
document.getElementById('score-web').innerText = STATE.score.web;
document.getElementById('score-api').innerText = STATE.score.api;
document.getElementById('score-fraud').innerText = STATE.score.fraudBlocked;
}
function flashMoney() {
const el = document.getElementById('money-display');
el.classList.add('text-red-500');
setTimeout(() => el.classList.remove('text-red-500'), 300);
}
function showMainMenu() {
// Ensure sound is initialized if possible (browsers might block until interaction)
if (!STATE.sound.ctx) STATE.sound.init();
STATE.sound.playMenuBGM();
document.getElementById('main-menu-modal').classList.remove('hidden');
document.getElementById('faq-modal').classList.add('hidden');
document.getElementById('modal').classList.add('hidden');
// Check for saved game and show/hide load button
const loadBtn = document.getElementById('load-btn');
const hasSave = localStorage.getItem('serverSurvivalSave') !== null;
if (loadBtn) {
loadBtn.style.display = hasSave ? 'block' : 'none';
}
}
let faqSource = 'menu'; // 'menu' or 'game'
window.showFAQ = (source = 'menu') => {
faqSource = source;
// If called from button (onclick="showFAQ()"), it defaults to 'menu' effectively unless we change the HTML.
// But wait, the button in index.html just calls showFAQ().
// We can check if main menu is visible.
if (!document.getElementById('main-menu-modal').classList.contains('hidden')) {
faqSource = 'menu';
document.getElementById('main-menu-modal').classList.add('hidden');
} else {
faqSource = 'game';
}
document.getElementById('faq-modal').classList.remove('hidden');
};
window.closeFAQ = () => {
document.getElementById('faq-modal').classList.add('hidden');
if (faqSource === 'menu') {
document.getElementById('main-menu-modal').classList.remove('hidden');
}
};
window.startGame = () => {
document.getElementById('main-menu-modal').classList.add('hidden');
resetGame();
};
window.startSandbox = () => {
document.getElementById('main-menu-modal').classList.add('hidden');
resetGame('sandbox');
};
function createService(type, pos) {
if (STATE.money < CONFIG.services[type].cost) { flashMoney(); return; }
if (STATE.services.find(s => s.position.distanceTo(pos) < 1)) return;
STATE.money -= CONFIG.services[type].cost;
STATE.services.push(new Service(type, pos));
STATE.sound.playPlace();
}
function restoreService(serviceData, pos) {
const service = Service.restore(serviceData, pos);
STATE.services.push(service);
STATE.sound.playPlace();
}
function createConnection(fromId, toId) {
if (fromId === toId) return;
const getEntity = (id) => id === 'internet' ? STATE.internetNode : STATE.services.find(s => s.id === id);
const from = getEntity(fromId), to = getEntity(toId);
if (!from || !to || from.connections.includes(toId)) return;
let valid = false;
const t1 = from.type, t2 = to.type;
if (t1 === 'internet' && (t2 === 'waf' || t2 === 'alb')) valid = true;
else if (t1 === 'waf' && t2 === 'alb') valid = true;
else if (t1 === 'waf' && t2 === 'sqs') valid = true;
else if (t1 === 'sqs' && t2 === 'alb') valid = true;
else if (t1 === 'alb' && t2 === 'sqs') valid = true;
else if (t1 === 'sqs' && t2 === 'compute') valid = true;
else if (t1 === 'alb' && t2 === 'compute') valid = true;
else if (t1 === 'compute' && t2 === 'cache') valid = true;
else if (t1 === 'cache' && (t2 === 'db' || t2 === 's3')) valid = true;
else if (t1 === 'compute' && (t2 === 'db' || t2 === 's3')) valid = true;
if (!valid) {
new Audio('assets/sounds/click-9.mp3').play();
console.error("Invalid connection topology: WAF/ALB from Internet -> WAF -> ALB -> Compute -> (RDS/S3)");
return;
}
new Audio('assets/sounds/click-5.mp3').play();
from.connections.push(toId);
const pts = [from.position.clone(), to.position.clone()];
pts[0].y = pts[1].y = 1;
const geo = new THREE.BufferGeometry().setFromPoints(pts);
const mat = new THREE.LineBasicMaterial({ color: CONFIG.colors.line });
const line = new THREE.Line(geo, mat);
connectionGroup.add(line);
STATE.connections.push({ from: fromId, to: toId, mesh: line });
STATE.sound.playConnect();
}
function deleteConnection(fromId, toId) {
const getEntity = (id) => id === 'internet' ? STATE.internetNode : STATE.services.find(s => s.id === id);
const from = getEntity(fromId);
if (!from) return false;
// Check if connection exists
if (!from.connections.includes(toId)) return false;
// Remove from service connections array
from.connections = from.connections.filter(c => c !== toId);
// Find and remove the visual mesh
const conn = STATE.connections.find(c => c.from === fromId && c.to === toId);
if (conn) {
connectionGroup.remove(conn.mesh);
conn.mesh.geometry.dispose();
conn.mesh.material.dispose();
STATE.connections = STATE.connections.filter(c => c !== conn);
}
STATE.sound.playDelete();
return true;
}
function getConnectionAtPoint(clientX, clientY) {
mouse.x = (clientX / window.innerWidth) * 2 - 1;
mouse.y = -(clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
// Get the click point on the ground plane
const clickPoint = new THREE.Vector3();
raycaster.ray.intersectPlane(plane, clickPoint);
clickPoint.y = 1; // Lines are at y=1
// Check each connection for proximity to click
const threshold = 2; // Distance threshold for clicking on a line
for (const conn of STATE.connections) {
const from = (conn.from === 'internet') ? STATE.internetNode : STATE.services.find(s => s.id === conn.from);
const to = (conn.to === 'internet') ? STATE.internetNode : STATE.services.find(s => s.id === conn.to);
if (!from || !to) continue;
const p1 = new THREE.Vector3(from.position.x, 1, from.position.z);
const p2 = new THREE.Vector3(to.position.x, 1, to.position.z);
// Calculate distance from point to line segment
const line = new THREE.Line3(p1, p2);
const closestPoint = new THREE.Vector3();
line.closestPointToPoint(clickPoint, true, closestPoint);
const distance = clickPoint.distanceTo(closestPoint);
if (distance < threshold) {
return conn;
}
}
return null;
}
function deleteObject(id) {
const svc = STATE.services.find(s => s.id === id);
if (!svc) return;
STATE.services.forEach(s => s.connections = s.connections.filter(c => c !== id));
STATE.internetNode.connections = STATE.internetNode.connections.filter(c => c !== id);
const toRemove = STATE.connections.filter(c => c.from === id || c.to === id);
toRemove.forEach(c => connectionGroup.remove(c.mesh));
STATE.connections = STATE.connections.filter(c => !toRemove.includes(c));
svc.destroy();
STATE.services = STATE.services.filter(s => s.id !== id);
STATE.money += Math.floor(svc.config.cost / 2);
STATE.sound.playDelete();
}
/**
* Calculates the percentage if failure based on the load of the node.
* @param {number} load fractions of 1 (0 to 1) of how loaded the node is
* @returns {number} chance of failure (0 to 1)
*/
function calculateFailChanceBasedOnLoad(load) {
if (load <= 0.5) return 0;
return 2 * (load - 0.5);
}
window.setTool = (t) => {
STATE.activeTool = t; STATE.selectedNodeId = null;
document.querySelectorAll('.service-btn').forEach(b => b.classList.remove('active'));
document.getElementById(`tool-${t}`).classList.add('active');
new Audio('assets/sounds/click-9.mp3').play();
};
window.setTimeScale = (s) => {
STATE.timeScale = s;
document.querySelectorAll('.time-btn').forEach(b => b.classList.remove('active'));
if (s === 0) {
document.getElementById('btn-pause').classList.add('active');
document.getElementById('btn-play').classList.add('pulse-green');
} else if (s === 1) {
document.getElementById('btn-play').classList.add('active');
document.getElementById('btn-play').classList.remove('pulse-green');
} else if (s === 3) {
document.getElementById('btn-fast').classList.add('active');
document.getElementById('btn-play').classList.remove('pulse-green');
}
};
window.toggleMute = () => {
const muted = STATE.sound.toggleMute();
const icon = document.getElementById('mute-icon');
const menuIcon = document.getElementById('menu-mute-icon');
const iconText = muted ? '🔇' : '🔊';
if (icon) icon.innerText = iconText;
if (menuIcon) menuIcon.innerText = iconText;
const muteBtn = document.getElementById('tool-mute');
const menuMuteBtn = document.getElementById('menu-mute-btn'); // We need to add ID to menu button
if (muted) {
muteBtn.classList.add('bg-red-900');
muteBtn.classList.add('pulse-green');
if (menuMuteBtn) menuMuteBtn.classList.add('pulse-green');
} else {
muteBtn.classList.remove('bg-red-900');
muteBtn.classList.remove('pulse-green');
if (menuMuteBtn) menuMuteBtn.classList.remove('pulse-green');
}
};
container.addEventListener('contextmenu', (e) => e.preventDefault());
container.addEventListener('mousedown', (e) => {
if (!STATE.isRunning) return;
if (e.button === 2 || e.button === 1) {
isPanning = true;
lastMouseX = e.clientX;
lastMouseY = e.clientY;
container.style.cursor = 'grabbing';
e.preventDefault();
return;
}
const i = getIntersect(e.clientX, e.clientY);
if (STATE.activeTool === 'select') {
const i = getIntersect(e.clientX, e.clientY);
if (i.type === 'service') { draggedNode = STATE.services.find(s => s.id === i.id); }
else if (i.type === 'internet') { draggedNode = STATE.internetNode; }
if (draggedNode) { isDraggingNode = true;
const hit = getIntersect(e.clientX, e.clientY);
if (hit.pos) { dragOffset.copy(draggedNode.position).sub(hit.pos); }
container.style.cursor = 'grabbing';
e.preventDefault();
return;
}
}
else if (STATE.activeTool === 'delete' && i.type === 'service') deleteObject(i.id);
else if (STATE.activeTool === 'unlink') {
const conn = getConnectionAtPoint(e.clientX, e.clientY);
if (conn) {
deleteConnection(conn.from, conn.to);
} else {
new Audio('assets/sounds/click-9.mp3').play();
}
}
else if (STATE.activeTool === 'connect' && (i.type === 'service' || i.type === 'internet')) {
if (STATE.selectedNodeId) { createConnection(STATE.selectedNodeId, i.id); STATE.selectedNodeId = null; }
else { STATE.selectedNodeId = i.id; new Audio('assets/sounds/click-5.mp3').play(); }
} else if (['waf', 'alb', 'lambda', 'db', 's3', 'sqs', 'cache'].includes(STATE.activeTool)) {
// Handle upgrades for compute, db, and cache
if ((STATE.activeTool === 'lambda' && i.type === 'service') ||
(STATE.activeTool === 'db' && i.type === 'service') ||
(STATE.activeTool === 'cache' && i.type === 'service')) {
const svc = STATE.services.find(s => s.id === i.id);
if (svc && ((STATE.activeTool === 'lambda' && svc.type === 'compute') ||
(STATE.activeTool === 'db' && svc.type === 'db') ||
(STATE.activeTool === 'cache' && svc.type === 'cache'))) {
svc.upgrade();
return;
}
}
if (i.type === 'ground') {
const typeMap = {
'waf': 'waf',
'alb': 'alb',
'lambda': 'compute',
'db': 'db',
's3': 's3',
'sqs': 'sqs',
'cache': 'cache'
};
createService(typeMap[STATE.activeTool], snapToGrid(i.pos));
}
}
});
container.addEventListener('mousemove', (e) => {
if (isDraggingNode && draggedNode) {
const hit = getIntersect(e.clientX, e.clientY);
if (hit.pos) {
const newPos = hit.pos.clone().add(dragOffset);
newPos.y = 0;
draggedNode.position.copy(newPos);
if (draggedNode.mesh) {
draggedNode.mesh.position.x = newPos.x;
draggedNode.mesh.position.z = newPos.z;
} else {
STATE.internetNode.mesh.position.x = newPos.x;
STATE.internetNode.mesh.position.z = newPos.z;
STATE.internetNode.ring.position.x = newPos.x;
STATE.internetNode.ring.position.z = newPos.z;
}
updateConnectionsForNode(draggedNode.id);
container.style.cursor = 'grabbing';
}
return;
}
if (isPanning) {
const dx = e.clientX - lastMouseX;
const dy = e.clientY - lastMouseY;
const panX = -dx * (camera.right - camera.left) / window.innerWidth * panSpeed;
const panY = dy * (camera.top - camera.bottom) / window.innerHeight * panSpeed;
if (isIsometric) {
camera.position.x += panX;
camera.position.z += panY;
cameraTarget.x += panX;
cameraTarget.z += panY;
camera.lookAt(cameraTarget);
} else {
camera.position.x += panX;
camera.position.z += panY;
camera.lookAt(camera.position.x, 0, camera.position.z);
}
camera.updateProjectionMatrix(); lastMouseX = e.clientX;
lastMouseY = e.clientY;
document.getElementById('tooltip').style.display = 'none';
return;
}
const i = getIntersect(e.clientX, e.clientY);
const t = document.getElementById('tooltip');
let cursor = 'default';
// Reset all connection colors first
STATE.connections.forEach(c => {
if (c.mesh && c.mesh.material) {
c.mesh.material.color.setHex(CONFIG.colors.line);
}
});
// Handle unlink tool hover
if (STATE.activeTool === 'unlink') {
const conn = getConnectionAtPoint(e.clientX, e.clientY);
if (conn) {
cursor = 'pointer';
// Highlight the connection in red
if (conn.mesh && conn.mesh.material) {
conn.mesh.material.color.setHex(0xff4444);
}
// Get source and target names for tooltip
const from = (conn.from === 'internet') ? STATE.internetNode : STATE.services.find(s => s.id === conn.from);
const to = (conn.to === 'internet') ? STATE.internetNode : STATE.services.find(s => s.id === conn.to);
const fromName = conn.from === 'internet' ? 'Internet' : (from?.config?.name || 'Unknown');
const toName = conn.to === 'internet' ? 'Internet' : (to?.config?.name || 'Unknown');
t.style.display = 'block';
t.style.left = e.clientX + 15 + 'px';
t.style.top = e.clientY + 15 + 'px';
t.innerHTML = `<strong class="text-orange-400">Remove Link</strong><br>
<span class="text-gray-300">${fromName}</span> → <span class="text-gray-300">${toName}</span><br>
<span class="text-red-400 text-xs">Click to remove</span>`;
} else {
t.style.display = 'none';
}
container.style.cursor = cursor;
return;
}
if (i.type === 'service') {
const s = STATE.services.find(s => s.id === i.id);
if (s) {
t.style.display = 'block'; t.style.left = e.clientX + 15 + 'px'; t.style.top = e.clientY + 15 + 'px';
const load = s.processing.length / s.config.capacity;
let loadColor = load > 0.8 ? 'text-red-400' : (load > 0.4 ? 'text-yellow-400' : 'text-green-400');
// Service-specific tooltips
if (s.type === 'cache') {
const hitRate = Math.round((s.config.cacheHitRate || 0.35) * 100);
t.innerHTML = `<strong class="text-red-400">${s.config.name}</strong> <span class="text-xs text-yellow-400">T${s.tier || 1}</span><br>
Queue: <span class="${loadColor}">${s.queue.length}</span><br>
Load: <span class="${loadColor}">${s.processing.length}/${s.config.capacity}</span><br>
Hit Rate: <span class="text-green-400">${hitRate}%</span>`;
} else if (s.type === 'sqs') {
const maxQ = s.config.maxQueueSize || 200;
const fillPercent = Math.round((s.queue.length / maxQ) * 100);
const status = fillPercent > 80 ? 'Critical' : (fillPercent > 50 ? 'Busy' : 'Healthy');
const statusColor = fillPercent > 80 ? 'text-red-400' : (fillPercent > 50 ? 'text-yellow-400' : 'text-green-400');
t.innerHTML = `<strong class="text-orange-400">${s.config.name}</strong><br>
Buffered: <span class="${loadColor}">${s.queue.length}/${maxQ}</span><br>
Processing: ${s.processing.length}/${s.config.capacity}<br>
Status: <span class="${statusColor}">${status}</span>`;
} else {
t.innerHTML = `<strong class="text-blue-300">${s.config.name}</strong> <span class="text-xs text-yellow-400">T${s.tier || 1}</span><br>
Queue: <span class="${loadColor}">${s.queue.length}</span><br>
Load: <span class="${loadColor}">${s.processing.length}/${s.config.capacity}</span>`;
}
// Reset previous highlights
STATE.services.forEach(svc => {
if (svc.mesh.material.emissive) svc.mesh.material.emissive.setHex(0x000000);
});
// Show upgrade option for upgradeable services
if ((STATE.activeTool === 'lambda' && s.type === 'compute') ||
(STATE.activeTool === 'db' && s.type === 'db') ||
(STATE.activeTool === 'cache' && s.type === 'cache')) {
const tiers = CONFIG.services[s.type].tiers;
if (s.tier < tiers.length) {
cursor = 'pointer';
const nextCost = tiers[s.tier].cost;
t.innerHTML += `<br><span class="text-green-300 text-xs font-bold">Upgrade: $${nextCost}</span>`;
if (s.mesh.material.emissive) s.mesh.material.emissive.setHex(0x333333);
} else {
t.innerHTML += `<br><span class="text-gray-500 text-xs">Max Tier</span>`;
}
}
}
} else {
t.style.display = 'none';
// Reset highlights when not hovering service
STATE.services.forEach(svc => {
if (svc.mesh.material.emissive) svc.mesh.material.emissive.setHex(0x000000);
});
}
container.style.cursor = cursor;
});
container.addEventListener('mouseup', (e) => {
if (e.button === 2 || e.button === 1) {
isPanning = false;
container.style.cursor = 'default';
}
if (isDraggingNode && draggedNode) {
isDraggingNode = false;
const snapped = snapToGrid(draggedNode.position);
draggedNode.position.copy(snapped);
if (draggedNode.mesh) {
draggedNode.mesh.position.x = snapped.x;
draggedNode.mesh.position.z = snapped.z;
} else {
STATE.internetNode.mesh.position.x = snapped.x;
STATE.internetNode.mesh.position.z = snapped.z;
STATE.internetNode.ring.position.x = snapped.x;
STATE.internetNode.ring.position.z = snapped.z;
}
updateConnectionsForNode(draggedNode.id);
draggedNode = null;
container.style.cursor = 'default';
return;
}
});
function updateConnectionsForNode(nodeId) {
STATE.connections.forEach(c => {
if (c.from === nodeId || c.to === nodeId) {
const from = (c.from === 'internet') ? STATE.internetNode : STATE.services.find(s => s.id === c.from);
const to = (c.to === 'internet') ? STATE.internetNode : STATE.services.find(s => s.id === c.to);
if (!from || !to) return;
const pts = [
new THREE.Vector3(from.position.x, 1, from.position.z),
new THREE.Vector3(to.position.x, 1, to.position.z)
];
c.mesh.geometry.dispose();
c.mesh.geometry = new THREE.BufferGeometry().setFromPoints(pts);
}
});
}
function animate(time) {
STATE.animationId = requestAnimationFrame(animate);
if (!STATE.isRunning) return;
const dt = ((time - STATE.lastTime) / 1000) * STATE.timeScale;
STATE.lastTime = time;
STATE.services.forEach(s => s.update(dt));
STATE.requests.forEach(r => r.update(dt));
STATE.spawnTimer += dt;
if (STATE.currentRPS > 0 && STATE.spawnTimer > (1 / STATE.currentRPS)) {
STATE.spawnTimer = 0;
spawnRequest();
// Only ramp up in survival mode - use logarithmic growth
if (STATE.gameMode === 'survival') {
const gameTime = (performance.now() - STATE.gameStartTime) / 1000;
const targetRPS = calculateTargetRPS(gameTime);
// Smooth transition to target
STATE.currentRPS += (targetRPS - STATE.currentRPS) * 0.01;
STATE.currentRPS = Math.min(STATE.currentRPS, CONFIG.survival.maxRPS);
}
}
// Update fraud spike system
updateFraudSpike(dt);
document.getElementById('money-display').innerText = `$${Math.floor(STATE.money)}`;
const baseUpkeep = STATE.services.reduce((sum, s) => sum + s.config.upkeep / 60, 0);
const multiplier = typeof getUpkeepMultiplier === 'function' ? getUpkeepMultiplier() : 1.0;
const totalUpkeep = baseUpkeep * multiplier;
const upkeepDisplay = document.getElementById('upkeep-display');
if (upkeepDisplay) {
if (multiplier > 1.05) {
upkeepDisplay.innerText = `-$${totalUpkeep.toFixed(2)}/s (×${multiplier.toFixed(2)})`;
upkeepDisplay.className = 'text-red-400 font-mono';
} else {
upkeepDisplay.innerText = `-$${totalUpkeep.toFixed(2)}/s`;
upkeepDisplay.className = 'text-red-400 font-mono';
}
}
// Update traffic mix display
if (STATE.gameMode === 'survival') {
const webEl = document.getElementById('mix-web');
const apiEl = document.getElementById('mix-api');
const fraudEl = document.getElementById('mix-fraud');
if (webEl) webEl.textContent = Math.round(STATE.trafficDistribution.WEB * 100) + '%';
if (apiEl) apiEl.textContent = Math.round(STATE.trafficDistribution.API * 100) + '%';
if (fraudEl && !STATE.fraudSpikeActive) fraudEl.textContent = Math.round(STATE.trafficDistribution.FRAUD * 100) + '%';
}
STATE.reputation = Math.min(100, STATE.reputation);
document.getElementById('rep-bar').style.width = `${Math.max(0, STATE.reputation)}%`;
document.getElementById('rps-display').innerText = `${STATE.currentRPS.toFixed(1)} req/s`;
if (STATE.internetNode.ring) {
if (STATE.selectedNodeId === 'internet') {
STATE.internetNode.ring.material.opacity = 1.0;
} else {
STATE.internetNode.ring.material.opacity = 0.2;
}