-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphysplay.js
More file actions
1730 lines (1427 loc) · 46.8 KB
/
physplay.js
File metadata and controls
1730 lines (1427 loc) · 46.8 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
// NOTES:
//
// - Adjust the DraggableSelector value below to make elements draggable based on selector.
// - Add the a data-phys attribute to any elements to also make them draggable. e.g. <div data-phys>...</div>
// - To prevent an otherwise draggable element from being draggable, set data-phys="none".
//
const defaultPhysConfigValues = {
// ====== EDIT DEFAULT VALUES HERE ======
// Or temporarily change values at the bottom of the page.
ShowPhysDebugUI: false,
ShowSoundDebugUI: false,
MouseCanDragElements: false,
DebugPageElements: false,
DebugPhysics: false,
AutoEquipGravGun: false,
NoYoutube: false,
DraggableSelector: [
"[data-phys]",
"img",
"video",
".tab",
"#testGravBox",
"#maincontent section h2",
"#maincontent section h3",
"#maincontent section h4",
"#maincontent section p",
"#maincontent section > ul > li",
// "#halflife-logo-footer",
".language-button > a",
// ".main_footer li",
// "#valve-logo",
"#fixes li",
".youtube-container",
".buttonstack a",
"#invite > *",
"#intro h2",
].join(", "),
NeverDraggableSelector: [
"[data-phys=none]",
".decoration .top img",
".lightbox *",
"footer.main_footer *",
].join(", "),
EnableTextBounds: true,
TextBoundedSelectors: [
"[data-phys-bounds=text]",
"#maincontent section h2",
"#maincontent section h3",
"#maincontent section h4",
"#maincontent section p",
"#maincontent section > ul > li",
"#invite > *",
"#intro h2",
].join(", "),
// HoverScale: 1.02,
HoverScale: 1,
MinMouseDragDistance: 5,
GravityHoverDebounceDelay: 200, // ms
};
const isFirefox = navigator.userAgent.toLowerCase().includes('firefox');
class PhysPlayElement {
phys; // PhysPlay instance
elem; // HTMLElement
elemPlaceholder; // HTMLElement
body = null; // Matter.Body
isHoveringOverElement = false; // boolean
isHoveringOverPickupBounds = false; // boolean
isMouseDown = false; // boolean
hasHoverStyle = false; // boolean
preHoverTransformStyle = null; // TransformStyle
preExtractionTransformStyle = null; // TransformStyle
preExtractionBounds = null; // DOMRect (factors in css transform style)
preExtractionClientSize = null; // { width, height } (factors in layout, excludes css transform rotation/scale)
originalOpacity = 1;
updateCount = 1;
localBodyOffset = { x: 0, y: 0 };
constructor(phys, elem) {
this.phys = phys;
this.elem = elem;
// Prevent native dragging of this element when dragging would otherwise extract the physics element.
elem.addEventListener("dragstart", (event) => {
if (this.isExtractable || this.isExtracted) {
event.preventDefault();
event.stopPropagation();
}
});
this.elem.classList.add(physPlayClassNames.PhysElement);
elem.addEventListener("mousemove", (event) => this.onMouseMove(event));
elem.addEventListener("mouseenter", (event) => this.onMouseEnter(event));
elem.addEventListener("mouseleave", (event) => this.onMouseLeave(event));
elem.addEventListener("mousedown", (event) => this.onMouseDown(event));
}
get isExtracted() { return ( this.body != null ); }
get isExtractable() {
if (this.isExtracted) {
return false;
}
if (this.phys.config.values.MouseCanDragElements) {
return true;
}
if (this.phys.gun.equipped) {
return true;
}
return false;
}
updateHoverStyle() {
const bExtractable = this.isExtractable;
const bShouldHaveHoverStyle = ((this.isHoveringOverPickupBounds || this.isMouseDown) && bExtractable);
if (this.hasHoverStyle == bShouldHaveHoverStyle) {
return;
}
this.hasHoverStyle = bShouldHaveHoverStyle;
PhysPlayUtil.setElementClass(this.elem, physPlayClassNames.PhysElement_Extractable, bShouldHaveHoverStyle);
if (bShouldHaveHoverStyle) {
if (this.preHoverTransformStyle == null) {
this.preHoverTransformStyle = new TransformStyle(this.elem);
}
const trs = this.preHoverTransformStyle.clone();
trs.scale *= phys.config.values.HoverScale;
trs.translate.y -= 4;
trs.applyToElement(this.elem);
} else {
this.preHoverTransformStyle?.applyToElement(this.elem);
}
}
isPointOverGrabbableRegion(clientX, clientY) {
if (this.shouldUseTextBounds()) {
const textBounds = this.getTextBoundingClientRect();
return (
textBounds != null &&
clientX >= textBounds.left &&
clientX <= textBounds.right &&
clientY >= textBounds.top &&
clientY <= textBounds.bottom
);
} else {
const elems = document.elementsFromPoint(event.clientX, event.clientY) ?? [];
return elems.includes(this.elem);
}
}
onMouseMove(mouseEvent) {
if (!this.isExtractable || !this.isHoveringOverElement || !this.shouldUseTextBounds()) {
return;
}
if (this.getParentPhysElements().length > 0) {
// In the scenario of an extractable element inside of another,
// always prefer to drag the parent.
return;
}
this.isHoveringOverPickupBounds = this.isPointOverGrabbableRegion(mouseEvent.clientX, mouseEvent.clientY);
this.updateHoverStyle();
}
onMouseEnter(mouseEvent) {
if (!this.isExtractable) {
return;
}
if (this.getParentPhysElements().length > 0) {
// In the scenario of an extractable element inside of another,
// always prefer to drag the parent.
return;
}
this.isHoveringOverElement = true;
if (!this.shouldUseTextBounds()) {
this.isHoveringOverPickupBounds = true;
}
this.updateHoverStyle();
}
onMouseLeave(mouseEvent) {
this.isHoveringOverElement = false;
this.isHoveringOverPickupBounds = false;
this.updateHoverStyle();
}
onMouseDown(mouseDownEvent) {
if (this.phys.gun.equipped) {
// Gravgun itself handles mouse events.
return;
}
if (this.getParentPhysElements().length > 0) {
// In the scenario of one extractable element inside of another,
// always prefer to extract+drag the parent.
return;
}
if (!this.isPointOverGrabbableRegion(mouseDownEvent.clientX, mouseDownEvent.clientY)) {
return;
}
const onDocumentMouseMove = (mouseMoveEvent) => {
if (mouseDownEvent.extractedElement) {
return;
}
const delta = {
x: mouseMoveEvent.clientX - mouseDownEvent.clientX,
y: mouseMoveEvent.clientY - mouseDownEvent.clientY,
};
const dist = Math.sqrt( delta.x * delta.x + delta.y * delta.y );
// Require a small minimum drag distance to make just clicking on links easier.
if (this.isExtractable && dist >= this.phys.config.values.MinMouseDragDistance) {
mouseDownEvent.extractedElement = true;
this.extractElement(mouseDownEvent);
}
};
const onDocumentMouseUp = (mouseUpEvent) => {
this.elem.ownerDocument.removeEventListener("mousemove", onDocumentMouseMove);
this.elem.ownerDocument.removeEventListener("mouseup", onDocumentMouseUp);
this.isMouseDown = false;
this.updateHoverStyle();
};
this.elem.ownerDocument.addEventListener("mousemove", onDocumentMouseMove);
this.elem.ownerDocument.addEventListener("mouseup", onDocumentMouseUp);
this.isMouseDown = true;
this.updateHoverStyle();
}
playExtractionSoundEffect() {
if (this.elem.attributes['data-phys-pickup-sound']) {
soundEffects.playSound(this.elem.attributes['data-phys-pickup-sound'].value);
}
}
async extractElement(mouseDownEvent /* optional, to start dragging immediately */) {
if (this.isExtracted) {
return;
}
if (mouseDownEvent && !this.isPointOverGrabbableRegion(mouseDownEvent.clientX, mouseDownEvent.clientY)) {
return Promise.reject();
}
this.handlePreExtractionSideEffects();
const computedStyle = getComputedStyle(this.elem);
this.preExtractionTransformStyle = new TransformStyle(this.elem);
this.preExtractionBounds = this.elem.getBoundingClientRect();
if (computedStyle.display != "inline") {
// We need the client size (and not any other size metric) because we want the actual size of the
// element irrespective of any rotation it has, and before any present transform styles are applied
// (since we read and modify those separately).
this.preExtractionClientSize = { width: this.elem.clientWidth, height: this.elem.clientHeight };
} else {
// But in the case of inline elements, their client size is 0 so our next best option is just to
// take the screens-apce bounding client rect. Let's hope the inline text we're extracting doesn't
// have any fancy transform styles applied directly to it...
const bounds = this.elem.getBoundingClientRect();
this.preExtractionClientSize = { width: bounds.width, height: bounds.height };
}
this.createMatterBody();
Matter.Body.setStatic(this.body, true); // Until the element finishes extraction, which is async.
// Deep clone the element into a new off-screen element that will become
// the layout placeholder.
this.elemPlaceholder = PhysPlayUtil.deepCloneElement(this.elem, true);
this.elemPlaceholder.classList.add(physPlayClassNames.Placeholder);
this.elemPlaceholder.classList.remove(physPlayClassNames.PhysElement);
// Before we remove the real element from its current hierarchy, we need to
// bake in the layout and computed styles (incl. css vars and calcs) of its
// children, otherwise its appearance will likely change.
await PhysPlayUtil.bakeComputedElementStyles(this.elem);
// Before we put our element back in the new container, lock down its
// outer size to its previous in-layout size.
PhysPlayUtil.forceFixedElementLayoutSize(
this.elem,
this.preExtractionClientSize.width + 2, // Account for rounding-down.
this.preExtractionClientSize.height + 2,
);
// On firefox, once reparented it'll quickly flicker in the top left of the page otherwise.
this.originalOpacity = this.elem.style.opacity;
if (isFirefox) {
this.elem.style.opacity = 0;
}
// Now pull an Indiana Jones.
this.elem.replaceWith(this.elemPlaceholder);
this.elem.style.position = "absolute";
this.elem.style.top = "0px";
this.elem.style.left = "0px";
this.elem.style.bottom = "initial";
this.elem.style.right = "initial";
this.elem.style.margin = "initial";
this.elem.style.transformOrigin = "initial";
this.elem.classList.add(physPlayClassNames.PhysElement_Extracted);
// If the extracted elem is a list item, it won't display correctly not unside its list
// container (its bullet will be inside its bounds, not outside like it should be). So
// downgrade it to a block so that it displays correctly, without a floating bullet point.
if (this.elem.style?.display == "list-item") {
this.elem.style.display = "block";
}
PhysPlayUtil.preventDefaultClicks(this.elemPlaceholder);
this.elemPlaceholder.addEventListener("mouseup", (event) => {
event.preventDefault();
event.stopPropagation();
event.cancelBubble = true;
}, {capture: false});
this.elem.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
}, {capture: true});
// How we'll start dragging the element *after* it's been extracted off the page.
this.elem.addEventListener("mousedown", (event) => {
if (this.phys.gun.equipped) {
// Gravgun itself handles mouse events.
return;
}
event.preventDefault();
event.stopPropagation();
this.phys.render.mouse.mousedown(event);
}, {capture: true});
this.phys.mapExtractedElements.set(this.elem, this);
this.phys.elemPhysContainer.appendChild(this.elem);
Matter.Body.setStatic(this.body, false);
if (mouseDownEvent) {
// Starts dragging this new body immediately, but from the initial mousedown position.
this.phys.render.mouse.mousedown(mouseDownEvent);
Matter.MouseConstraint.update(this.phys.mouseConstraint, [this.body]);
}
this.updateTransform(true);
this.playExtractionSoundEffect();
}
handlePreExtractionSideEffects() {
if (this.elem.matches("#crowbar3 .crowbar-isolated")) {
document.querySelector("#crowbar3 .crowbar").classList.add(physPlayClassNames.NoShadow);
}
if (this != this.phys?.trash && !this.phys.trash?.isExtracted &&
this.phys.trash.elem.getBoundingClientRect().bottom < window.innerHeight) {
this.phys.trash.extractElement();
}
}
getTextBoundingClientRect() {
return PhysPlayUtil.getTextBounds(this.elem) ?? this.preExtractionBounds;
}
shouldUseTextBounds() {
return (this.phys.config.values.EnableTextBounds && this.elem.matches(this.phys.config.values.TextBoundedSelectors));
}
createMatterBody() {
let bodyPositionCenter;
let bodySize;
const elementCenter = {
x: this.preExtractionBounds.x + (this.preExtractionBounds.width / 2),
y: this.preExtractionBounds.y + (this.preExtractionBounds.height / 2),
};
if (this.shouldUseTextBounds()) {
const textBounds = this.getTextBoundingClientRect();
const textPositionCenter = {
x: textBounds.x + (textBounds.width / 2),
y: textBounds.y + (textBounds.height / 2),
};
this.localBodyOffset = {
x: textPositionCenter.x - elementCenter.x,
y: textPositionCenter.y - elementCenter.y,
};
this.localBodyOffset.x /= this.preExtractionTransformStyle.scale;
this.localBodyOffset.y /= this.preExtractionTransformStyle.scale;
bodyPositionCenter = textPositionCenter;
bodySize = {
width: textBounds.width,
height: textBounds.height,
};
} else {
bodyPositionCenter = elementCenter;
bodySize = {
width: this.preExtractionClientSize.width * this.preExtractionTransformStyle.scale,
height: this.preExtractionClientSize.height * this.preExtractionTransformStyle.scale,
};
}
// Move from client space to physics world space
bodyPositionCenter.x += this.phys.render.bounds.min.x;
bodyPositionCenter.y += this.phys.render.bounds.min.y;
this.body = Matter.Bodies.rectangle(
bodyPositionCenter.x, bodyPositionCenter.y,
bodySize.width, bodySize.height,
{
render: {
fillStyle: "aqua",
opacity: 0.5,
}
});
Matter.Body.setAngle(this.body, this.preExtractionTransformStyle.rotate);
Matter.Composite.add(this.phys.engine.world, [this.body]);
}
updateTransform(force) {
if (this.body == null || (!force && this.body.isSleeping)) {
return;
}
if (!force &&
this.body.angle == this.body.anglePrev &&
this.body.position.x == this.body.positionPrev.x &&
this.body.position.y == this.body.positionPrev.y &&
(!isFirefox || this.updateCount > 3)) {
return;
}
const trs = new TransformStyle(
{
x: this.body.position.x - (0.5 * this.preExtractionClientSize.width) - this.phys.render.bounds.min.x,
y: this.body.position.y - (0.5 * this.preExtractionClientSize.height) - this.phys.render.bounds.min.y,
},
this.body.angle,
this.preExtractionTransformStyle.scale,
);
let css = trs.getCSS();
if (this.localBodyOffset.x != 0 || this.localBodyOffset.y != 0) {
css += ` translate(${-this.localBodyOffset.x}px, ${-this.localBodyOffset.y}px) `;
}
this.elem.style.transform = css;
if (isFirefox && this.updateCount >= 3) {
this.elem.style.opacity = this.originalOpacity;
}
this.updateCount++;
}
getParentPhysElements() {
const parentPhysPlayElements = [];
for (let elem = this.elem.parentElement; elem != null; elem = elem.parentElement) {
if (this.phys.mapPageElements.has(elem)) {
parentPhysPlayElements.push(this.phys.mapPageElements.get(elem));
}
}
return parentPhysPlayElements;
}
remove() {
if (this.body != null) {
const body = this.body;
this.body = null;
Matter.Composite.remove(this.phys.engine.world, [body]);
}
this.phys.mapExtractedElements.delete(this.elem);
this.phys.mapPageElements.delete(this.elem);
if (this.elem) {
this.elem?.parentElement?.removeChild(this.elem);
this.elem = null;
}
}
onBodyRemoved() {
this.remove();
}
}
class PhysPlay {
config = new PhysPlayConfig();
gun = new PhysPlayGun(this);
can = null; // PhysPlayCan
trash = null; // PhysPlayTrash
engine; // Matter.Engine
render; // Matter.Render
mapPageElements = new Map(); // Map<HTMLElement, PhysPlayElement>
mapExtractedElements = new Map(); // Map<PhysPlayElement, PhysPlayElement>;
setCanElements = new Set(); // Set<PhysPlayElement>
elemPhysContainer; // HTMLDivElement
elemCanvas; // HTMLCanvasElement
elemFooter; // HTMLDivElement
bodyGround; // Matter.Body
mouseConstraint; // Matter.MouseConstraint
constructor() {
this.elemPhysContainer = document.querySelector("#physContainer");
this.elemFooter = document.querySelector("footer.main_footer");
this.config.onupdate = () => this.onConfigUpdate();
this.onConfigUpdate();
this.initializeEngine();
this.initializeWrapping();
this.createGroundAndCeiling();
document.addEventListener('mousemove', (event) => {
if (this.gun.equipped) {
// GravGun handles this.
return;
}
this.render.mouse.mousemove(event);
});
document.addEventListener('mouseup', (event) => {
if (this.gun.equipped) {
// GravGun handles this.
return;
}
this.render.mouse.mouseup(event);
});
this.initializeExtractableElements();
if (this.config.values.AutoEquipGravGun) {
this.gun.setEquipped(true);
}
}
onConfigUpdate() {
PhysPlayUtil.setElementClass(document.body, physPlayClassNames.DebugPageElements, this.config.values.DebugPageElements);
PhysPlayUtil.setElementClass(document.body, physPlayClassNames.DebugPhysics, this.config.values.DebugPhysics);
PhysPlayUtil.setElementClass(document.body, physPlayClassNames.ShowPhysDebugUI, this.config.values.ShowPhysDebugUI);
PhysPlayUtil.setElementClass(document.body, physPlayClassNames.ShowSoundDebugUI, this.config.values.ShowSoundDebugUI);
if (this.render) {
this.render.options = {
...this.render.options,
...this.desiredMatterRenderOptions(),
};
}
this.initializeExtractableElements();
if (this.config.values.NoYoutube) {
document.querySelectorAll(".youtube-container").forEach((elem) => {
elem.remove();
});
}
}
desiredMatterRenderOptions() {
return {
enabled: this.config.values.DebugPhysics,
showDebug: this.config.values.DebugPhysics,
};
}
initializeEngine() {
this.engine = Matter.Engine.create();
this.render = Matter.Render.create({
element: this.elemPhysContainer,
engine: this.engine,
options: {
width: window.innerWidth,
height: window.innerHeight,
background: "transparent",
wireframes: false,
showAngleIndicator: false,
...this.desiredMatterRenderOptions(),
}
});
this.elemCanvas = this.render.canvas;
this.elemCanvas.id = 'physCanvas';
// Create the Matter.js mouse object and mouse constraint
const mouse = Matter.Mouse.create(this.elemCanvas);
this.mouseConstraint = Matter.MouseConstraint.create(this.engine, {
mouse: mouse,
constraint: {
stiffness: 0.1,
length: 0,
angularStiffness: 0,
render: { visible: true }
}
});
Matter.Composite.add(this.engine.world, this.mouseConstraint);
this.render.mouse = mouse;
// Run the renderer and engine
Matter.Render.run(this.render);
const runner = Matter.Runner.create();
Matter.Runner.run(runner, this.engine);
// Resize canvas when window is resized
window.addEventListener('scroll', this.updateGroundPosition.bind(this));
window.addEventListener('resize', this.resizeCanvas.bind(this));
this.resizeCanvas();
Matter.Events.on(this.engine.world, 'afterRemove', (event) => {
event.object.forEach((obj) => this.onBodyRemoved(obj));
});
requestAnimationFrame( () => this.onAnimationFrame() );
setTimeout(() => this.updateGroundPosition(), 1000);
}
onAnimationFrame() {
PhysPlayUtil.setElementClass(document.body, physPlayClassNames.HasPhysBodies, this.mapExtractedElements.size > 0);
for (const pair of this.mapExtractedElements) {
pair[1].updateTransform();
}
requestAnimationFrame( () => this.onAnimationFrame() );
}
initializeWrapping() {
Matter.use('matter-wrap');
Matter.Events.on(this.engine.world, 'afterAdd', (event) => {
event.object.forEach((obj) => this.initializeWrappingForBody(obj));
});
}
initializeWrappingForBody(body) {
body.plugin.wrap = {
min: { x: this.render.bounds.min.x, y: this.render.bounds.min.y - 100000 },
max: { x: this.render.bounds.max.x, y: this.render.bounds.max.y },
};
}
resizeCanvas() {
this.render.bounds.max.x = window.innerWidth;
this.render.bounds.max.y = window.innerHeight;
this.render.options.width = window.innerWidth;
this.render.options.height = window.innerHeight;
this.render.canvas.width = window.innerWidth;
this.render.canvas.height = window.innerHeight;
this.updateGroundPosition();
for (const body of this.engine.world.bodies) {
this.initializeWrappingForBody(body);
}
Matter.Render.lookAt(this.render, {
min: { x: 0, y: 0 },
max: { x: window.innerWidth, y: window.innerHeight },
});
}
createGroundAndCeiling() {
this.bodyGround = Matter.Bodies.rectangle(
0, 0,
100000, 10000,
{
isStatic: true,
render: {
fillStyle: "orange",
opacity: 0.5,
}
},
);
const bodyCeiling = Matter.Bodies.rectangle(
0, -500 - 1000,
100000, 1000,
{ isStatic: true },
);
Matter.Composite.add(this.engine.world, [this.bodyGround, bodyCeiling]);
this.updateGroundPosition();
}
updateGroundPosition() {
if (!this.bodyGround) {
return;
}
const groundEdgeY = Math.min(window.innerHeight, this.elemFooter.getBoundingClientRect().top);
const groundCenterY = groundEdgeY + 5000;
if (this.bodyGround.position.y != 0 && this.bodyGround.position.y != groundCenterY) {
const groundDeltaY = groundCenterY - this.bodyGround.position.y;
for (const physElem of this.mapExtractedElements.values()) {
if (!physElem.body) {
continue;
}
Matter.Body.setPosition(physElem.body, Matter.Vector.create(physElem.body.position.x, physElem.body.position.y + groundDeltaY), false);
physElem.updateTransform(true);
}
}
Matter.Body.setPosition(this.bodyGround, Matter.Vector.create(0, groundCenterY));
}
initializeExtractableElements() {
document.querySelectorAll(this.config.values.DraggableSelector).forEach((elem) => {
this.makeElementExtractable(elem);
});
const observer = new MutationObserver((mutationsList, observer) => {
for (const mutation of mutationsList) {
if (mutation.type != "childList") {
continue;
}
for (const node of mutation.addedNodes) {
if (!node?.matches?.(this.config.values.DraggableSelector)) {
continue;
}
this.makeElementExtractable(node);
}
}
});
observer.observe(document, { childList: true, subtree: true });
}
makeElementExtractable(elem) {
if (this.mapPageElements.has(elem) || this.mapExtractedElements.has(elem)) {
return;
}
if (elem.classList.contains(physPlayClassNames.Placeholder)) {
return;
}
if (elem.matches(this.config.values.NeverDraggableSelector)) {
return;
}
let pageElem;
if (elem.classList.contains("can")) {
const bPrimaryCan = (elem.id == "can");
pageElem = new PhysPlayCan(this, elem, bPrimaryCan);
this.setCanElements.add(pageElem);
if (bPrimaryCan) {
this.can = pageElem;
}
} else if (elem.id == "trashcan") {
pageElem = new PhysPlayTrash(this, elem);
this.trash = pageElem;
} else {
pageElem = new PhysPlayElement(this, elem);
}
this.mapPageElements.set(elem, pageElem);
}
onBodyRemoved(body) {
for (const physElem of this.mapExtractedElements.values()) {
if (body && physElem.body === body) {
physElem.onBodyRemoved();
}
}
}
}
class PhysPlayGun {
phys; // PhysPlay
elemButton; // HTMLDivElement
elemPhysGunContainer; // HTMLDivElement
elemPhysGun; // HTMLDivElement
transform = new TransformStyle();
equipped = false;
everEquipped = false;
heldItem = null; // PhysPlayElement
hoveredItem = null; // PhysPlayElement
closeTimeout = null; // number (timeout handle)
touchingButton = false;
touchEndTimeout = null;
constructor(phys) {
this.phys = phys;
this.elemButton = document.querySelector("#gravgunimage");
this.elemPhysGunContainer = document.createElement("div");
this.elemPhysGunContainer.className = physPlayClassNames.GravGun_Container;
document.body.appendChild(this.elemPhysGunContainer);
this.elemPhysGun = document.createElement("div");
this.elemPhysGun.className = physPlayClassNames.GravGun;
this.elemPhysGunContainer.appendChild(this.elemPhysGun);
document.addEventListener("click", (event) => {
if (this.equipped) {
// Prevent links from being followed, etc.
event.preventDefault();
}
}, {capture: true});
document.addEventListener("contextmenu", (event) => {
if (this.equipped) {
// Prevent standard right-click context menu.
event.preventDefault();
}
}, {capture: true});
document.addEventListener("mousedown", (event) => this.onMouseDown(event));
document.addEventListener("mousemove", (event) => this.onMouseMove(event));
document.addEventListener("mouseup", (event) => this.onMouseUp(event));
this.elemButton.addEventListener("mouseenter", () => {
if (this.touchingButton) {
return;
}
soundEffects.playSound("weaponswitch");
});
this.elemButton.addEventListener("mousedown", () => {
if (this.touchingButton) {
return;
}
this.setEquipped(!this.equipped);
});
this.elemButton.addEventListener("touchstart", (event) => {
this.touchingButton = true;
this.showTouchMessage(true);
soundEffects.playSound("dryfire");
clearTimeout(this.touchEndTimeout);
});
this.elemButton.addEventListener("touchend", (event) => {
clearTimeout(this.touchEndTimeout);
this.touchEndTimeout = setTimeout(() => {
this.touchingButton = event.touches.length > 0;
}, 100);
});
}
showTouchMessage(wiggleGravGun) {
const elemMessage = document.querySelector("#mobilemessage");
if (!elemMessage) {
return;
}
const bMobile = (document.body.clientWidth <= Number.parseInt("700px"));
document.querySelector("#mobilemessage .use-mouse").style.display = bMobile ? "none" : "inline";
document.querySelector("#mobilemessage .use-desktop").style.display = bMobile ? "inline" : "none";
PhysPlayUtil.setElementClass(document.body, physPlayClassNames.ShowGravGunMessage, true);
if (wiggleGravGun) {
PhysPlayUtil.setElementClass(this.elemButton, physPlayClassNames.GravGunButton_ButtonWiggle, false);
setTimeout(() => PhysPlayUtil.setElementClass(this.elemButton, physPlayClassNames.GravGunButton_ButtonWiggle, true), 0);
}
}
hideTouchMessage() {
PhysPlayUtil.setElementClass(document.body, physPlayClassNames.ShowGravGunMessage, false);
}
setEquipped(bEquip) {
if (this.equipped == bEquip) {
return;
}
this.equipped = bEquip;
this.updateClasses();
this.everEquipped = this.everEquipped || bEquip;
if (bEquip) {
soundEffects.playSound("select");
this.hideTouchMessage();
} else {
soundEffects.playSound("weaponswitch");
}
if (bEquip && this.hoveredItem != null) {
this.playOpenSound();
}
}
async pickupItem(physPlayElement, mouseEvent) {
if (!physPlayElement) {
return;
}
if (this.heldItem != null) {
this.dropItem();
}
if (!physPlayElement.isExtracted) {
await physPlayElement.extractElement();
}
this.heldItem = physPlayElement;
this.updateClasses();
soundEffects.playSound("pickup");
soundEffects.playSound("holdloop");
this.phys.render.mouse.mousedown(mouseEvent);
Matter.MouseConstraint.update(this.phys.mouseConstraint, [this.heldItem.body]);
this.recoil();
}
dropItem(mouseEvent) {
this.phys.render.mouse.mouseup(mouseEvent);
if (!this.heldItem) {
return;
}
this.heldItem = null;
this.updateClasses();
soundEffects.stopSound("holdloop");
soundEffects.playSound("drop");
clearTimeout(this.closeTimeout);
this.closeTimeout = null;
// this.recoil();
}
dryFire(mouseEvent) {
soundEffects.playSound("dryfire");
this.recoil();
}
recoil() {
PhysPlayUtil.setElementClass(this.elemPhysGun, physPlayClassNames.GravGun_Recoil, false);
setTimeout(() => PhysPlayUtil.setElementClass(this.elemPhysGun, physPlayClassNames.GravGun_Recoil, true), 0);
}
onMouseDown(event) {
this.updatePosition(event.clientX, event.clientY);
if (!this.equipped) {
return;
}
if (this.hoveredItem && (this.hoveredItem.isExtractable || this.hoveredItem.isExtracted)) {
this.pickupItem(this.hoveredItem, event).catch(() => this.dryFire());
} else {
this.dryFire();
}
}
onMouseMove(event) {
this.updatePosition(event.clientX, event.clientY);
if (!this.equipped) {
return;
}
this.phys.render.mouse.mousemove(event);
}