repo_name stringlengths 1 62 | dataset stringclasses 1 value | lang stringclasses 11 values | pr_id int64 1 20.1k | owner stringlengths 2 34 | reviewer stringlengths 2 39 | diff_hunk stringlengths 15 262k | code_review_comment stringlengths 1 99.6k |
|---|---|---|---|---|---|---|---|
mrjs | github_2023 | javascript | 581 | Volumetrics-io | hanbollar | @@ -124,7 +136,9 @@ export class MRModelEntity extends MRDivEntity {
this.loading = false;
- if (modelChange) {
+ this.loaded = true; | having both of these as variables can be a little confusing, can you change one of their names to be more distinct (or if one of them is no longer used, remove the redundant one) |
mrjs | github_2023 | javascript | 576 | Volumetrics-io | hanbollar | @@ -227,7 +238,7 @@ export class MREntity extends MRElement {
rotation = {
get: () => {
- return this.dataset.rotation;
+ return mrjsUtils.string.stringToVector(this.dataset.position); | typo, looks like a misplaced copy-paste - this should still have `this.dataset.rotation` inside the utils function |
mrjs | github_2023 | javascript | 573 | Volumetrics-io | hanbollar | @@ -105,11 +105,11 @@ export class MRDivEntity extends MREntity {
* @description Removing an entity as a sub-object of this panel (for example an mr-model, button, etc).
* @param {MREntity} entity - the entity to be removed added.
*/
- remove(entity) {
+ removeEntity(entity) {
// `this` must have `mr-panel` as its closest parent entity for threejs to handle positioning appropriately.
let panel = this.closest('mr-panel');
if (panel && entity instanceof MRDivEntity) {
- panel.remove(entity);
+ panel.removeEntity(entity);
} else {
this.object3D.remove(entity.object3D); | the `let panel` line should probably be within the if statement instead and if no panel exists, we should throw an error (mrjsUtils.error.err) since an mrdiv element cannot exist without a panel |
mrjs | github_2023 | javascript | 546 | Volumetrics-io | michaelthatsit | @@ -56,183 +41,124 @@ export class MRTextAreaEntity extends MRTextInputEntity {
*/
fillInHiddenInputElementWithUserData() {
// name: The name associated with the <textarea> for form submission and backend processing.
- this.hiddenInput.name = this.getAttribute('name') ?? this.defaults.name;
+ this.hiddenInput.name = this.getAttribute('name') ?? undefined;
// rows and cols: These attributes control the size of the <textarea> in terms of the number of text rows and columns visible.
- this.hiddenInput.rows = this.getAttribute('rows') ?? this.defaults.rows;
+ this.hiddenInput.rows = this.getAttribute('rows') ?? undefined;
// placeholder: Provides a hint to the user about what they should type into the <textarea>.
- this.hiddenInput.placeholder = this.getAttribute('placeholder') ?? this.defaults.placeholder;
+ this.hiddenInput.placeholder = this.getAttribute('placeholder') ?? undefined;
// readonly: Makes the <textarea> uneditable, allowing the text to be only read, not modified.
- this.hiddenInput.readonly = this.getAttribute('readonly') ?? this.defaults.readonly;
+ this.hiddenInput.readonly = this.getAttribute('readonly') ?? undefined;
// disabled: Disables the text area so it cannot be interacted with or submitted.
- this.hiddenInput.disabled = this.getAttribute('disabled') ?? this.defaults.disabled;
+ this.hiddenInput.disabled = this.getAttribute('disabled') ?? undefined;
// maxlength: Specifies the maximum number of characters that the user can enter.
- this.hiddenInput.maxlength = this.getAttribute('maxlength') ?? this.defaults.maxlength;
+ this.hiddenInput.maxlength = this.getAttribute('maxlength') ?? undefined;
// wrap: Controls how text is wrapped in the textarea, with values like soft and hard affecting form submission.
- this.hiddenInput.wrap = this.getAttribute('wrap') ?? this.defaults.wrap;
+ this.hiddenInput.wrap = this.getAttribute('wrap') ?? undefined;
// overflowwrap : Controls how wrap breaks, at whitespace characters or in the middle of words.
- this.textObj.overflowWrap = this.getAttribute('overflowWrap') ?? this.defaults.overflowWrap;
+ this.hiddenInput.overflowWrap = this.getAttribute('overflowWrap') ?? undefined;
// whitespace : Controls if text wraps with the overflowWrap feature or not.
- this.textObj.whiteSpace = this.getAttribute('whitespace') ?? this.defaults.whiteSpace;
- }
-
- /**
- * Overrides the connected method to include setup for handling multiline text.
- * @function
- * @description (async) sets up the textObject of the text item.
- */
- async connected() {
- await super.connected();
+ this.hiddenInput.whiteSpace = this.getAttribute('whitespace') ?? undefined;
}
/**
*
*/
updateTextDisplay() {
- // Determine the maximum number of characters per line based on renderable area (example given)
- const maxCharsPerLine = 50; // This should be dynamically calculated
-
- const lines = this.hiddenInput.value.split('\n').map((line) => {
- // Truncate or split lines here based on maxCharsPerLine if implementing horizontal scrolling
- return line.substring(0, maxCharsPerLine);
- });
-
- // Existing logic to determine visibleLines based on scrollOffset and maxVisibleLines
- const visibleLines = lines.slice(this.scrollOffset, this.scrollOffset + this.maxVisibleLines);
- const visibleText = visibleLines.join('\n');
+ // XXX - add scrolling logic in here for areas where text is greater than
+ // the width/domain the user creates visually
- this.textObj.text = visibleText;
- // console.log('text updated: ', this.textObj.text);
-
- // Logic to adjust scrollOffset for new input, ensuring the latest text is visible
- if (lines.length > this.maxVisibleLines && this.hiddenInput === document.activeElement) {
- this.scrollOffset = Math.max(0, lines.length - this.maxVisibleLines);
- }
-
- this.updateCursorPosition();
+ this.textObj.text = this.hiddenInput.value;
}
/**
- * Handles keydown events for scrolling and cursor navigation.
+ * Handles keydown events for scrolling and cursor navigation. Note
+ * that this is different than an input event which for our purposes,
+ * handles the non-navigation key-presses.
* @param {event} event - the keydown event
*/
handleKeydown(event) { | This really shouldn't be necessary if we're using the `hiddenInput`, right? you can get the selection (cursor position) directly from that. |
mrjs | github_2023 | javascript | 561 | Volumetrics-io | michaelthatsit | @@ -40,10 +40,10 @@ export class MRTextEntity extends MRDivEntity {
/**
* @function
- * @description (async) sets up the textObject of the text item.
+ * @description Helper for anytime text is manually touched - in connected and by use of `innerText`.
+ * Handles setting `innerText` like expected, sanitizing it for our use, and also making sure the updates are called.
*/
- async connected() {
- await super.connected();
+ _textWasManuallyUpdated() { | Why is this needed? Aren't we checking `entity.textContent == entity.textObj.text` every frame? |
mrjs | github_2023 | javascript | 557 | Volumetrics-io | hanbollar | @@ -33,6 +33,8 @@ window.mobileCheck = function () {
return mrjsUtils.display.mobileCheckFunction();
};
+const GLOBAL_UPDATE_EVENTS = ['enterxr', 'exitxr', 'load', 'anchored', 'panelupdate', 'engine-started', 'resize']; | add documentation note for why here and why order |
mrjs | github_2023 | javascript | 557 | Volumetrics-io | hanbollar | @@ -393,22 +382,32 @@ export class MREntity extends MRElement {
this.triggerMaterialStyleUpdate();
});
- const intersectionObserver = new IntersectionObserver((entries) => {
- for (const entry of entries) {
- this._boundingClientRect = entry.boundingClientRect;
- }
- // Refresh the rect info to keep it up-to-date as much as possible.
- // It seems that the callback is always called once soon after observe() is called,
- // regardless of the intersection state of the entity.
- // TODO: Confirm whether this behavior is intended. If it is not, there may be future
- // behavior changes or it may not work as intended on certain platforms.
- intersectionObserver.disconnect();
- intersectionObserver.observe(this);
- });
- intersectionObserver.observe(this);
-
- this.dispatchEvent(new CustomEvent('new-entity', { bubbles: true }));
- this.connected();
+ // TODO: find alternative solution. This breaks with the switch to asychronous entity initialization
+ // const intersectionObserver = new IntersectionObserver((entries) => {
+ // for (const entry of entries) {
+ // this._boundingClientRect = entry.boundingClientRect;
+ // }
+ // // Refresh the rect info to keep it up-to-date as much as possible.
+ // // It seems that the callback is always called once soon after observe() is called,
+ // // regardless of the intersection state of the entity.
+ // // TODO: Confirm whether this behavior is intended. If it is not, there may be future
+ // // behavior changes or it may not work as intended on certain platforms.
+ // intersectionObserver.disconnect();
+ // intersectionObserver.observe(this);
+ // });
+ // intersectionObserver.observe(this);
+
+ if (mrjsUtils.physics.initialized) {
+ await this.connected();
+ this.dispatchEvent(new CustomEvent('new-entity', { bubbles: true }));
+ this.loadAttributes();
+ } else {
+ document.addEventListener('engine-started', async (event) => {
+ await this.connected();
+ this.loadAttributes();
+ this.dispatchEvent(new CustomEvent('new-entity', { bubbles: true })); | add small comment here explaining why |
mrjs | github_2023 | javascript | 557 | Volumetrics-io | hanbollar | @@ -111,6 +97,17 @@ export class MRSystem {
*/
eventUpdate() {}
+ /**
+ *
+ * @param entity
+ */ | look at the jsdoc warnings in the files section of github - make sure theyre filled out |
mrjs | github_2023 | javascript | 557 | Volumetrics-io | hanbollar | @@ -120,10 +117,10 @@ export class MRSystem {
/**
* @function
- * @description Called when the entity component is initialized
+ * @description (async) Called when the entity component is initialized | i like that you added this here in the documentation 💛 |
mrjs | github_2023 | javascript | 557 | Volumetrics-io | hanbollar | @@ -307,13 +307,13 @@ export class MREntity extends MRElement {
* @function
* @description Callback function of MREntity - does nothing. Is called by the connectedCallback.
*/
- connected() {}
+ async connected() {}
/**
* @function
* @description The connectedCallback function that runs whenever this entity component becomes connected to something else. | can you add `(async)` to the description like you did for the other newly async functions? |
mrjs | github_2023 | javascript | 557 | Volumetrics-io | hanbollar | @@ -307,13 +307,13 @@ export class MREntity extends MRElement {
* @function
* @description Callback function of MREntity - does nothing. Is called by the connectedCallback. | can you add `(async)` to the description like you did for the other newly async functions? |
mrjs | github_2023 | javascript | 557 | Volumetrics-io | hanbollar | @@ -145,9 +142,9 @@ export class MRSystem {
* @description Handles the component and registry aspect of the event when an entity component attaches to this system. | can you add `(async)` to the description like you did for the other newly async functions? |
mrjs | github_2023 | javascript | 557 | Volumetrics-io | hanbollar | @@ -42,8 +42,18 @@ export class AnimationSystem extends MRSystem {
* @description Called when the entity component is initialized | can you add `(async)` to the description like you did for the other newly async functions? |
mrjs | github_2023 | javascript | 557 | Volumetrics-io | hanbollar | @@ -42,8 +42,18 @@ export class AnimationSystem extends MRSystem {
* @description Called when the entity component is initialized
* @param {object} entity - the entity being attached/initialized.
*/
- attachedComponent(entity) {
+ async attachedComponent(entity) {
let comp = entity.components.get('animation');
+
+ await new Promise((resolve) => {
+ const interval = setInterval(() => {
+ if (entity.loaded) {
+ clearInterval(interval);
+ resolve();
+ }
+ }, 100); // Checks every 100ms | add expln in docs for why we need to keep checking |
mrjs | github_2023 | javascript | 557 | Volumetrics-io | hanbollar | @@ -119,7 +119,7 @@ export class MRDivEntity extends MREntity {
* @function
* @description Callback function of MREntity - connects the background geometry of this item to an actual UIPlane geometry. | can you add `(async)` to the description like you did for the other newly async functions? |
mrjs | github_2023 | javascript | 557 | Volumetrics-io | hanbollar | @@ -53,7 +53,7 @@ export default class MRHyperlinkEntity extends MRTextEntity {
* @description Callback function of MREntity - makes sure the link object is created and sets up event | can you add `(async)` to the description like you did for the other newly async functions? |
mrjs | github_2023 | javascript | 557 | Volumetrics-io | hanbollar | @@ -43,7 +43,8 @@ export class MRImageEntity extends MRMediaEntity {
* @function
* @description Callback function of MREntity - handles setting up this Image and associated 3D geometry style (from css) once it is connected to run as an entity component. | can you add `(async)` to the description like you did for the other newly async functions? |
mrjs | github_2023 | javascript | 557 | Volumetrics-io | hanbollar | @@ -22,7 +22,7 @@ export class MRLightEntity extends MREntity {
* @function
* @description Callback function of MREntity - handles setting up this Light once it is connected to run as an entity component. | can you add `(async)` to the description like you did for the other newly async functions? |
mrjs | github_2023 | javascript | 557 | Volumetrics-io | hanbollar | @@ -117,7 +117,7 @@ export class MRMediaEntity extends MRDivEntity {
* @function
* @description Callback function of MREntity - handles setting up this media and associated 3D geometry style (from css) once it is connected to run as an entity component. | can you add `(async)` to the description like you did for the other newly async functions? |
mrjs | github_2023 | javascript | 557 | Volumetrics-io | hanbollar | @@ -54,7 +54,8 @@ export class MRPanelEntity extends MRDivEntity {
* @description Callback function of MREntity - handles setting up this Panel once it is connected to run as an entity component. | can you add `(async)` to the description like you did for the other newly async functions? |
mrjs | github_2023 | javascript | 557 | Volumetrics-io | hanbollar | @@ -57,7 +57,8 @@ export class MRSkyBoxEntity extends MREntity {
* @description Lifecycle method that is called when the entity is connected. | can you add `(async)` to the description like you did for the other newly async functions? |
mrjs | github_2023 | javascript | 557 | Volumetrics-io | hanbollar | @@ -78,8 +78,8 @@ export class MRTextAreaEntity extends MRTextInputEntity {
/**
* Overrides the connected method to include setup for handling multiline text. | this function needs proper jsdoc descriptions not just function body
@function
@description
and - can you add `(async)` to the description like you did for the other newly async functions? |
mrjs | github_2023 | javascript | 557 | Volumetrics-io | hanbollar | @@ -51,7 +51,8 @@ export class MRTextInputEntity extends MRTextEntity {
* @function
* @description Callback function of MREntity - handles setting up this textarea once it is connected to run as an entity component. | can you add `(async)` to the description like you did for the other newly async functions? |
mrjs | github_2023 | javascript | 557 | Volumetrics-io | hanbollar | @@ -59,7 +59,8 @@ export class MRVideoEntity extends MRMediaEntity {
* @function
* @description Callback function of MREntity - handles setting up this video and associated 3D geometry style (from css) once it is connected to run as an entity component. | can you add `(async)` to the description like you did for the other newly async functions? |
mrjs | github_2023 | javascript | 557 | Volumetrics-io | hanbollar | @@ -42,9 +42,14 @@ export class MRTextEntity extends MRDivEntity {
* @function
* @description Callback function of MREntity - sets up the textObject of the text item.
*/
- connected() {
- const text = this.textContent.trim();
+ async connected() {
+ await super.connected();
+ const text = this.textContent
+ .replace(/(\n)\s+/g, '$1')
+ .replace(/(\r\n|\n|\r)/gm, ' ')
+ .trim();
this.textObj.text = text.length > 0 ? text : ' ';
+ this.dispatchEvent(new CustomEvent('new-entity', { bubbles: true })); | reminder - pls remove this `dispatchEvent` line - you told me to say this 👀 |
mrjs | github_2023 | javascript | 551 | Volumetrics-io | hanbollar | @@ -92,6 +92,14 @@ export class MRModelEntity extends MRDivEntity {
this.loaded = true;
+ this.object3D.traverse(object => { | if you're traversing over `this.object3D` make sure to use `MREntity`'s [`traverseObjects`](https://github.com/Volumetrics-io/mrjs/blob/main/src/core/MREntity.js#L542) instead of just `object3D.traverse`
it adds in an extra check for if it's the actual root object to reduce redunant checks |
mrjs | github_2023 | javascript | 549 | Volumetrics-io | hanbollar | @@ -30,10 +30,10 @@ export class MREntity extends MRElement {
constructor() {
super();
- Object.defineProperty(this, 'isApp', {
- value: false,
- writable: false,
- });
+ // Object.defineProperty(this, 'isApp', {
+ // value: false,
+ // writable: false,
+ // }); | delete commented code - or if leaving for later, add comment as to why |
mrjs | github_2023 | javascript | 549 | Volumetrics-io | hanbollar | @@ -47,7 +47,7 @@ export class MREntity extends MRElement {
this.scale = 1;
- this.componentMutated = this.componentMutated.bind(this);
+ // this.componentMutated = this.componentMutated.bind(this); | delete commented code - or if leaving for later, add comment as to why |
mrjs | github_2023 | javascript | 545 | Volumetrics-io | hanbollar | @@ -267,7 +269,11 @@ export class PhysicsSystem extends MRSystem {
updateUIBody(entity) {
this.tempBBox.setFromCenterAndSize(entity.object3D.position, new THREE.Vector3(entity.width, entity.height, 0.002));
- this.tempWorldScale.setFromMatrixScale(entity.object3D.matrixWorld);
+ if (entity instanceof MRPanelEntity) {
+ this.tempWorldScale.setFromMatrixScale(entity.panel.matrixWorld);
+ } else {
+ this.tempWorldScale.setFromMatrixScale(entity.object3D.matrixWorld);
+ } | it would be better to do this as
```
this.tempWorldScale.setFromMatrixScale( (entity instanceof MRPanelEntity) ? entity.panel.matrixWorld : entity.object3D.matrixWorld );
``` |
mrjs | github_2023 | javascript | 508 | Volumetrics-io | hanbollar | @@ -0,0 +1,59 @@
+import { mrjsUtils } from 'mrjs';
+import { MRSystem } from 'mrjs/core/MRSystem';
+import { MRStats } from 'mrjs/core/entities/MRStats';
+
+import Stats from 'stats.js';
+
+import { HTMLMesh } from 'three/addons/interactive/HTMLMesh.js';
+import { InteractiveGroup } from 'three/addons/interactive/InteractiveGroup.js';
+
+// TODO: JSDoc
+
+export class StatsSystem extends MRSystem {
+ constructor() {
+ super(false);
+ this.statsEntities = [];
+ }
+
+ update() {
+ for (const entity of this.statsEntities) {
+ if (entity.stats === null && this.app) {
+ entity.stats = new Stats();
+ entity.stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
+ document.body.appendChild(entity.stats.dom);
+
+ // Note: InteractiveGroup API is refactored in the newer Three.js rev.
+ // Don't forget to update the followings when upgrading Three.js
+ entity.interactiveGroup = new InteractiveGroup(this.app.renderer, this.app.camera);
+ entity.object3D.add(entity.interactiveGroup);
+
+ // Note: HTMLMesh seems to have a bug that image is not displayed at a correct position.
+ // in Three.js r161 or older.
+ // TODO: Upgrade Three.js to fix
| Unless @michaelthatsit states otherwise - seems a worthwhile bump for our purposes 👍 |
mrjs | github_2023 | javascript | 508 | Volumetrics-io | hanbollar | @@ -0,0 +1,20 @@
+import { MRDivEntity } from '../MRDivEntity';
+
+// TODO: JSDoc
+
+export class MRStats extends MRDivEntity {
| MRStats should be an `MREntity` instead of `MRDivEntity`
think of `MRDivEntity` items to be (except for MRModel) the UI elements - that is theyre the ones that are situated on an mr-panel almost as if that mr-panel is a website in 3D space
Since we want MRStats to be its own object regardless of an mr-panel and to act for the app as a whole - `MREntity` is better |
mrjs | github_2023 | javascript | 508 | Volumetrics-io | hanbollar | @@ -113,7 +114,15 @@ export class MRApp extends MRElement {
this.observer = new MutationObserver(this.mutationCallback);
this.observer.observe(this, { attributes: true, childList: true });
+ if (this.getAttribute('stats')) {
+ const statsEl = document.createElement('mr-stats');
+ statsEl.setAttribute('data-comp-anchor', 'type: plane; label: wall;');
+ statsEl.setAttribute('data-position', '0 0.2 0.01');
+ this.appendChild(statsEl);
+ }
+ | this would be better off in the constructor of `StatsSystem` as we should only have a stats system if `this.getAttribute('stats')` is true |
mrjs | github_2023 | javascript | 508 | Volumetrics-io | hanbollar | @@ -0,0 +1,59 @@
+import { mrjsUtils } from 'mrjs';
+import { MRSystem } from 'mrjs/core/MRSystem';
+import { MRStats } from 'mrjs/core/entities/MRStats';
+
+import Stats from 'stats.js';
+
+import { HTMLMesh } from 'three/addons/interactive/HTMLMesh.js';
+import { InteractiveGroup } from 'three/addons/interactive/InteractiveGroup.js';
+
+// TODO: JSDoc
+
+export class StatsSystem extends MRSystem {
+ constructor() {
+ super(false);
+ this.statsEntities = [];
+ }
+
+ update() {
+ for (const entity of this.statsEntities) {
+ if (entity.stats === null && this.app) {
| this section should be in the entity's `connected` function - this is the function that gets called when the entity is 'connected to an app (meaning the app exists and <mr-stats> is in the html within it)
[mr-hyperlink's use of connected ](https://github.com/Volumetrics-io/mrjs/blob/main/src/core/entities/MRHyperlink.js#L39)is a good example of this |
mrjs | github_2023 | javascript | 508 | Volumetrics-io | hanbollar | @@ -0,0 +1,59 @@
+import { mrjsUtils } from 'mrjs';
+import { MRSystem } from 'mrjs/core/MRSystem';
+import { MRStats } from 'mrjs/core/entities/MRStats';
+
+import Stats from 'stats.js';
+
+import { HTMLMesh } from 'three/addons/interactive/HTMLMesh.js';
+import { InteractiveGroup } from 'three/addons/interactive/InteractiveGroup.js';
+
+// TODO: JSDoc
+
+export class StatsSystem extends MRSystem {
+ constructor() {
+ super(false);
+ this.statsEntities = [];
+ }
+
+ update() {
+ for (const entity of this.statsEntities) {
+ if (entity.stats === null && this.app) {
+ entity.stats = new Stats();
+ entity.stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
+ document.body.appendChild(entity.stats.dom);
+
+ // Note: InteractiveGroup API is refactored in the newer Three.js rev.
+ // Don't forget to update the followings when upgrading Three.js
+ entity.interactiveGroup = new InteractiveGroup(this.app.renderer, this.app.camera);
+ entity.object3D.add(entity.interactiveGroup);
+
+ // Note: HTMLMesh seems to have a bug that image is not displayed at a correct position.
+ // in Three.js r161 or older.
+ // TODO: Upgrade Three.js to fix
+
+ // Question: Circle pointer doesn't seem to be displayed on the Stats panel object
+ // and the clickable area seems to be a difference place from the panel object, why?
+ // TODO: Fix it
+ entity.statsMesh = new HTMLMesh(entity.stats.dom);
+ entity.interactiveGroup.add(entity.statsMesh);
+ }
+
+ if (entity.stats) {
+ entity.stats.update();
+ if (mrjsUtils.xr.isPresenting) {
+ entity.statsMesh.visible = true;
+ entity.statsMesh.material.map.update();
+ } else {
+ entity.statsMesh.visible = false;
+ }
+ }
+ }
+ }
+
+ onNewEntity(entity) {
+ // Question: How can we detect the removal of entities?
+ if (entity instanceof MRStats) {
+ this.statsEntities.push(entity);
+ }
| every MRSystem has a 'this.registry' which is a set for every entity associated with a system
`this.statsEntities.push(entity)` --> `this.registry.add(entity);`
----
an additional note:
at the moment, we do not remove entities from this set once theyre added
in future if we ever have live entity deletion that will need to happen, but it will probably be by use of an additional system we add to handle all the locations an entity is included
|
mrjs | github_2023 | javascript | 508 | Volumetrics-io | hanbollar | @@ -0,0 +1,59 @@
+import { mrjsUtils } from 'mrjs';
+import { MRSystem } from 'mrjs/core/MRSystem';
+import { MRStats } from 'mrjs/core/entities/MRStats';
+
+import Stats from 'stats.js';
+
+import { HTMLMesh } from 'three/addons/interactive/HTMLMesh.js';
+import { InteractiveGroup } from 'three/addons/interactive/InteractiveGroup.js';
+
+// TODO: JSDoc
+
+export class StatsSystem extends MRSystem {
+ constructor() {
+ super(false);
+ this.statsEntities = [];
+ }
+
+ update() {
+ for (const entity of this.statsEntities) {
+ if (entity.stats === null && this.app) {
+ entity.stats = new Stats();
+ entity.stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
+ document.body.appendChild(entity.stats.dom);
+
+ // Note: InteractiveGroup API is refactored in the newer Three.js rev.
+ // Don't forget to update the followings when upgrading Three.js
+ entity.interactiveGroup = new InteractiveGroup(this.app.renderer, this.app.camera);
+ entity.object3D.add(entity.interactiveGroup);
+
+ // Note: HTMLMesh seems to have a bug that image is not displayed at a correct position.
+ // in Three.js r161 or older.
+ // TODO: Upgrade Three.js to fix
+
+ // Question: Circle pointer doesn't seem to be displayed on the Stats panel object
+ // and the clickable area seems to be a difference place from the panel object, why?
| not entirely sure at first glance - i'll take a quick look in headset and get back to you on that |
mrjs | github_2023 | javascript | 516 | Volumetrics-io | michaelthatsit | @@ -0,0 +1,81 @@
+import { MRSystem } from 'mrjs/core/MRSystem';
+import { MRDivEntity } from 'mrjs/core/MRDivEntity';
+import { MRPanel } from 'mrjs/core/entities/MRPanel';
+
+/**
+ * @function
+ * @description Observe a target MRDivEntity and make the associated object visible only if it is in visible position in a root MRDivEntity
+ * @param {MRDivEntity} root
+ * @param {MRDivEntity} target
+ */
+const observe = (root, target) => {
+ // TODO: Callback is fired asynchronously so no guaranteed to be called immediately when the
+ // visibility from the layout position changes. Therefore, the visibility of the associated
+ // Object3D's might be updated a few frames later after when it really need to be. It might
+ // affect the user experience. Fix it if possible.
+ const observer = new IntersectionObserver(
+ (entries) => {
+ for (const entry of entries) {
+ // TODO: Endure the visibility set by other systems is not overridden. For example,
+ // even if another system has made an entity visible within the panel for some reasons,
+ // this system makes it visible. This issue should be fixed.
+ entry.target.object3D.visible = entry.intersectionRatio > 0;
+ }
+ },
+ {
+ root: root,
+ threshold: 0.0,
+ }
+ );
+ observer.observe(target);
+};
+
+/**
+ * @class BoundaryVisibilitySystem
+ * @classdesc Makes the entities invisible if they are outside of their parent panels
+ * @augments MRSystem
+ */
+export class BoundaryVisibilitySystem extends MRSystem { | ROVSystem (Region of Visibility)? |
mrjs | github_2023 | javascript | 516 | Volumetrics-io | michaelthatsit | @@ -0,0 +1,81 @@
+import { MRSystem } from 'mrjs/core/MRSystem';
+import { MRDivEntity } from 'mrjs/core/MRDivEntity';
+import { MRPanel } from 'mrjs/core/entities/MRPanel';
+
+/**
+ * @function
+ * @description Observe a target MRDivEntity and make the associated object visible only if it is in visible position in a root MRDivEntity
+ * @param {MRDivEntity} root
+ * @param {MRDivEntity} target
+ */
+const observe = (root, target) => {
+ // TODO: Callback is fired asynchronously so no guaranteed to be called immediately when the
+ // visibility from the layout position changes. Therefore, the visibility of the associated
+ // Object3D's might be updated a few frames later after when it really need to be. It might
+ // affect the user experience. Fix it if possible.
+ const observer = new IntersectionObserver(
+ (entries) => {
+ for (const entry of entries) {
+ // TODO: Endure the visibility set by other systems is not overridden. For example,
+ // even if another system has made an entity visible within the panel for some reasons,
+ // this system makes it visible. This issue should be fixed.
+ entry.target.object3D.visible = entry.intersectionRatio > 0; | oof. so this overrides the other systems? Calling it earlier in the Systems order might fix it. They're stepped sequentially, so any subsequent system would override this one. |
mrjs | github_2023 | javascript | 516 | Volumetrics-io | hanbollar | @@ -0,0 +1,81 @@
+import { MRSystem } from 'mrjs/core/MRSystem';
+import { MRDivEntity } from 'mrjs/core/MRDivEntity';
+import { MRPanel } from 'mrjs/core/entities/MRPanel';
+
+/**
+ * @function
+ * @description Observe a target MRDivEntity and make the associated object visible only if it is in visible position in a root MRDivEntity
+ * @param {MRDivEntity} root
+ * @param {MRDivEntity} target
+ */
+const observe = (root, target) => {
+ // TODO: Callback is fired asynchronously so no guaranteed to be called immediately when the
+ // visibility from the layout position changes. Therefore, the visibility of the associated
+ // Object3D's might be updated a few frames later after when it really need to be. It might
+ // affect the user experience. Fix it if possible. | I think that delay is fine for now - as long as fixing the order per [link](https://github.com/Volumetrics-io/mrjs/pull/516/files#r1536268465) lets things run smoothly (ie the other systems can override / run what they need to) then it should be okay |
mrjs | github_2023 | javascript | 516 | Volumetrics-io | hanbollar | @@ -0,0 +1,90 @@
+import { MRSystem } from 'mrjs/core/MRSystem';
+import { MRDivEntity } from 'mrjs/core/MRDivEntity';
+import { MRPanel } from 'mrjs/core/entities/MRPanel';
+
+/**
+ * @function
+ * @description Observe a target MRDivEntity and make the associated object visible only if it is in visible position in a root MRDivEntity
+ * @param {MRDivEntity} root
+ * @param {MRDivEntity} target
+ */
+const observe = (root, target) => {
+ // TODO: Callback is fired asynchronously so no guaranteed to be called immediately when the
+ // visibility from the layout position changes. Therefore, the visibility of the associated
+ // Object3D's might be updated a few frames later after when it really need to be. It might
+ // affect the user experience. Fix it if possible.
+ const observer = new IntersectionObserver(
+ (entries) => {
+ for (const entry of entries) {
+ // TODO: Ensure to avoid the visibility set up collision. If multiple systems set up the visibility
+ // independently, only the last system before render call can have an effect. This callback
+ // is fired asynchronously so it may be said that this callback is executed before all the
+ // sync systems.
+ entry.target.object3D.visible = entry.intersectionRatio > 0;
+ }
+ // Somehow callback is sometimes not fired even though crossing the threshold so as fallback
+ // always refresh the info as much as possible to keep it up-to-date.
+ // It seems that the callback is always called once soon after observe() is called,
+ // regardless of the intersection state of the entity.
+ // TODO: Confirm whether this behavior is intended. If it is not, there may be future | noting this todo as important |
mrjs | github_2023 | javascript | 125 | Volumetrics-io | takahirox | @@ -315,7 +315,7 @@ export default class Entity extends MRElement {
const children = Array.from(this.children);
for (const child of children) {
// if o is an object, traverse it again
- if (!child instanceof Entity) {
+ if ((!child) instanceof Entity) { | Is this change intentional? `!child` would be boolean (true/false) then `((!child) instanceof Entity)` would be always false. I guess you wanted to write `!(child instanceof Entity)`. |
mrjs | github_2023 | javascript | 511 | Volumetrics-io | takahirox | @@ -202,6 +202,16 @@ export class MRApp extends MRElement {
this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
this.renderer.toneMappingExposure = 1;
this.renderer.localClippingEnabled = true;
+ if (this.getAttribute('preserve-drawing-buffer') ?? false) {
+ // There's issues in the timing to enable taking screenshots of threejs scenes unless you have direct access to the code.
+ // Using the preserveDrawingBuffer to ignore timing issues is the best approach instead. Though this has a performance hit,
+ // we're allowing it to be enabled by users when necessary.
+ //
+ // References:
+ // https://stackoverflow.com/questions/15558418/how-do-you-save-an-image-from-a-three-js-canvas
+ // https://stackoverflow.com/questions/30628064/how-to-toggle-preservedrawingbuffer-in-three-js
+ this.renderer.preserveDrawingBuffer = true; | `preserveDrawingBuffer` flag must be passed via the `WebGLRenderer` constructor.
https://threejs.org/docs/#api/en/renderers/WebGLRenderer |
mrjs | github_2023 | javascript | 511 | Volumetrics-io | michaelthatsit | @@ -193,6 +195,19 @@ export class MRApp extends MRElement {
*/
init() {
this.debug = this.getAttribute('debug') ?? false;
+
+ this.renderer = new THREE.WebGLRenderer({
+ antialias: true,
+ alpha: true,
+ // There's issues in the timing to enable taking screenshots of threejs scenes unless you have direct access to the code.
+ // Using the preserveDrawingBuffer to ignore timing issues is the best approach instead. Though this has a performance hit,
+ // we're allowing it to be enabled by users when necessary.
+ //
+ // References:
+ // https://stackoverflow.com/questions/15558418/how-do-you-save-an-image-from-a-three-js-canvas
+ // https://stackoverflow.com/questions/30628064/how-to-toggle-preservedrawingbuffer-in-three-js
+ preserveDrawingBuffer: this.getAttribute('preserve-drawing-buffer') ?? false, | Maybe we shorten it to `preserve-buffer`? Could just be my aversion to long attribute names. |
mrjs | github_2023 | javascript | 306 | Volumetrics-io | takahirox | @@ -45,6 +45,23 @@ export class MRTextEntity extends MRDivEntity {
this.needsStyleUpdate = true;
}
}
+
+ /**
+ * @function
+ * @description Runs the passed through function on this object and every child of this object.
+ * @param {Function} callBack - the function to run recursively.
+ */
+ traverse(callBack) {
+ callBack(this);
+ const children = Array.from(this.object3D.children); | Is this `this.object3D.children` (Three.js Object3D collection) intentional although parent `MREntity` traverses `.children` (HTMLElement collection)? I guess it isn't. This function it very trouble some because callback function doesn't expect `Object3D` argument if this method is called from parent entities. |
mrjs | github_2023 | javascript | 497 | Volumetrics-io | michaelthatsit | @@ -49,36 +49,31 @@ export class PhysicsSystem extends MRSystem {
}
}
+ /**
+ * @function
+ * @description The per global scene event update call. Based on the captured physics events for the frame, handles all items appropriately.
+ */
eventUpdate = () => {
+ mrjsUtils.physics.world.step(mrjsUtils.physics.eventQueue);
+
for (const entity of this.registry) {
if (entity.physics?.body == null) {
continue;
}
- if (entity instanceof MRModel) {
- this.updateSimpleBody(entity);
- } else if (entity instanceof MRDivEntity) {
- this.updateUIBody(entity);
- }
+ this.updateBody(entity);
}
+
+ this.updateDebugRenderer();
};
/**
* @function
- * @description The generic system update call. Based on the captured physics events for the frame, handles all items appropriately.
+ * @description The per-frame system update call. Based on the captured physics events for the frame, handles all items appropriately.
* @param {number} deltaTime - given timestep to be used for any feature changes
* @param {object} frame - given frame information to be used for any feature changes
*/
update(deltaTime, frame) {
- mrjsUtils.physics.world.step(mrjsUtils.physics.eventQueue);
-
- for (const entity of this.registry) {
- if (entity.physics?.body == null) {
- continue;
- }
- this.updateBody(entity);
- }
-
- this.updateDebugRenderer();
+ this.eventUpdate(); | `eventUpdate` is only meant to be called on events, not per frame. |
mrjs | github_2023 | javascript | 497 | Volumetrics-io | michaelthatsit | @@ -49,36 +49,31 @@ export class PhysicsSystem extends MRSystem {
}
}
+ /**
+ * @function
+ * @description The per global scene event update call. Based on the captured physics events for the frame, handles all items appropriately.
+ */
eventUpdate = () => {
+ mrjsUtils.physics.world.step(mrjsUtils.physics.eventQueue);
+
for (const entity of this.registry) {
if (entity.physics?.body == null) {
continue;
}
- if (entity instanceof MRModel) {
- this.updateSimpleBody(entity);
- } else if (entity instanceof MRDivEntity) {
- this.updateUIBody(entity);
- } | We need to keep the updates here. Updating colliders per frame causes a significant hit to performance. |
mrjs | github_2023 | javascript | 494 | Volumetrics-io | hanbollar | @@ -52,6 +52,7 @@ export class MREntity extends MRElement {
});
this.object3D = new THREE.Group();
+ this.object3D.userData.isEntityObject3DRoot = true; | one shorter solution is leaning into the assumption that if object3D is a group, then object3D.children[0] is the root in question
reasoning - when the entities are set up it'll be either the first background object for any mrdiv or the 'object' that should be representing the entity itself given how we instantiate the items in the 'connected' functions - meaning it would actually be the root object
but i'm hesitant to lean towards that as it becomes more overhead long term - and if a user does any of their own javascript modifications or we change the architecture in future, that logic will become a huge edge case
i think what you have, though it's a flag, is straight forward enough for now
in future if/when we can lean into traversing over the entities directly instead of the object3Ds (if that is ever possible) then that reduces our need for the flag, but that's not worth a dive through at the moment. |
mrjs | github_2023 | javascript | 492 | Volumetrics-io | hanbollar | @@ -66,82 +134,88 @@ export class MaskingSystem extends MRSystem {
// leave for when needed.
}
+ /**
+ * @function
+ * @description Copy the source world matrices to the objects writing to stencil buffer
+ */
+ sync() {
+ // TODO: Move to update().
+ // This method needs to be called after the matrices of the main scene are updated.
+ // However, currently the matrices are updated MRApp after running systems' update(),
+ // so the conditions are not met when executed in update(). Therefore, as a
+ // temporary workaround, a new method has been added and is explicitly called
+ // from MRApp. Moving this code into the update() method would reduce the specialities
+ // and improve maintainability.
+ for (const child of this.scene.children) {
+ const source = this.sourceElementMap.get(child).background;
+
+ // TODO: Consider a properer way.
+ // It seems that the geometry of a source object can be replaced with a different
+ // geometry by other systems, so this check and replacing are needed. However,
+ // replacing the geometry is not an appropriate use of the Three.js API. We
+ // should consider a more robust approach to copying the shape of the source object.
+ if (child.geometry !== source.geometry) {
+ child.geometry = source.geometry;
+ }
+
+ child.matrixWorld.copy(source.matrixWorld);
+ }
+ }
+
/**
* @function
* @description Called when a new entity is added to the scene. Handles masking elements to their panel.
* @param {MREntity} entity - the entity being added.
*/
onNewEntity(entity) {
if (entity instanceof MRPanel) {
- // Using an array for the panels in case we need them for more manipulations down the line instead
- // of using the system's registry.
- this.panels.push(entity);
-
- // Need to set stencilRef for the children of this panel to match that of this panel so
- // that when rendering the children they only mask based on the panel's geometry location instead
- // of all panel geometry locations.
- //
- // stencilRef needs to be > 0 as 0 is the webgl default and -1 is our manual default of 'not set yet'.
- // We're basing our stencilRef on the 1+index location (ie length of array at adding) of the panel entity.
- // Even though we're not manually using this stencilRef in the render loop, threejs handles its use
- // internally.
- const stencilRef = this.panels.length;
-
- // Currently this setup will not be able to handle properly if there is a panel within another
- // panel in the html setup. Defaulting that case to be based on whichever panel is the entity
- // passed through this function since that case is an edge case that will not be expected.
-
- /**
- *
- * @param child
- */
- function runTheTraversal(child) {
+ if (this.panelCount >= MAX_PANEL_NUM) {
+ console.warn('Masking system supports up to eight panels.');
+ return;
+ }
+
+ // Ignoring panel removal for now.
+ // TODO: Handle panel removal
+ const stencilRefShift = this.panelCount;
+ this.panelCount++;
+
+ entity.traverse((child) => {
if (child instanceof MRPanel && child.object3D.isGroup) {
// The panel entity should contain a group object where the first panel child we hit is this panel itself.
// We need to mask based off the background mesh of this object.
- let mesh = child.background;
- if (this.app.debug && mesh.material.color) {
- mesh.material.color.set(0xff00ff); // pink
- }
- mesh.material.stencilWrite = this.panelStencilMaterial.stencilWrite;
- mesh.material.stencilFunc = this.panelStencilMaterial.stencilFunc;
- mesh.material.stencilRef = stencilRef;
- mesh.material.stencilZPass = this.panelStencilMaterial.stencilZPass;
+ const sourceObj = child.background;
+
+ // TODO: Optimize material.
+ // Since only needs to write to the stencil buffer, no need to write to the color buffer,
+ // therefore, we can use a simpler material than MeshBasicMaterial. Should we use
+ // ShaderMaterial? | I think switching to ShaderMaterial would be good but if I remember correctly when I've done that before in mrjs it can hit a weird edge case for some aspect of physics our bounding box updates (i forget exactly where)
just noting this here for future if that ends up being something you'd want to chase down
not blocker or priority for this pr though |
mrjs | github_2023 | javascript | 492 | Volumetrics-io | hanbollar | @@ -66,82 +134,88 @@ export class MaskingSystem extends MRSystem {
// leave for when needed.
}
+ /**
+ * @function
+ * @description Copy the source world matrices to the objects writing to stencil buffer
+ */
+ sync() {
+ // TODO: Move to update().
+ // This method needs to be called after the matrices of the main scene are updated.
+ // However, currently the matrices are updated MRApp after running systems' update(),
+ // so the conditions are not met when executed in update(). Therefore, as a | A bit confused by this comment - Where is this? We might be able to do a workaround to get the sync back into the update loop
Not a blocker if this isnt possible in the current setup - just want to make sure im understanding and maybe we can find a way for it to work as you're proposing in the TODO. |
mrjs | github_2023 | javascript | 464 | Volumetrics-io | michaelthatsit | @@ -0,0 +1,242 @@
+import * as THREE from 'three';
+
+import { MRDivEntity } from 'mrjs/core/MRDivEntity';
+
+import { mrjsUtils } from 'mrjs';
+
+/**
+ * @class MRMedia
+ * @classdesc Base html media entity represented in 3D space. `mr-media`
+ * @augments MRDivEntity
+ */
+export class MRMedia extends MRDivEntity {
+ /**
+ * @class
+ * @description Constructs a base media entity using a UIPlane and other 3D elements as necessary.
+ */
+ constructor() {
+ super();
+ this.attachShadow({ mode: 'open' });
+
+ // Create the object3D. Dont need default value for geometry
+ // until the connected call since this will get overwritten anyways.
+ let material = new THREE.MeshStandardMaterial({
+ side: 0,
+ transparent: true,
+ });
+ // Object3D for MRMedia (mrimage,mrvideo,etc) is the actual image/video/etc itself in 3D space
+ this.object3D = new THREE.Mesh(undefined, material);
+ this.object3D.receiveShadow = true;
+ this.object3D.renderOrder = 3;
+ this.object3D.name = 'media';
+
+ // the media to be filled out.
+ // for ex: document.createElement('video') or document.createElement('img');
+ this.media = null;
+
+ // This is a reference to the texture that is used as part of the
+ // threejs material. Separating it out for easier updating after it is loaded.
+ // The texture is filled-in in the connected function.
+ this.texture = null;
+
+ // This is used to aid in the formatting for certain object-fit setups
+ // ex: contain, scale-down
+ this.subMediaMesh = null;
+ }
+
+ /**
+ * @function
+ * @description Calculates the width of the img based on the img tag in the shadow root
+ * @returns {number} - the resolved width
+ */
+ get width() {
+ let width = this.objectFitDimensions?.width;
+ return width > 0 ? width : super.width;
+ }
+
+ /**
+ * @function
+ * @description Calculates the height of the img based on the img tag in the shadow root
+ * @returns {number} - the resolved height
+ */
+ get height() {
+ let height = this.objectFitDimensions?.height;
+ return height > 0 ? height : super.height;
+ }
+
+ get mediaWidth() {
+ // to be filled in in children
+ }
+
+ get mediaHeight() {
+ // to be filled in in children
+ }
+
+ generateNewMediaPlaneGeometry() {
+ if (this.object3D.geometry !== undefined) {
+ this.object3D.geometry.dispose();
+ }
+ this.object3D.geometry = mrjsUtils.geometry.UIPlane(this.width, this.height, this.borderRadii, 18);
+ }
+
+ loadMediaTexture() {
+ // filled in by MRMedia children (MRImage,MRVideo,etc)
+ }
+
+ /**
+ * @function
+ * @description Callback function of MREntity - handles setting up this Image and associated 3D geometry style (from css) once it is connected to run as an entity component.
+ */
+ connected() {
+ this.media.setAttribute('src', mrjsUtils.html.resolvePath(this.getAttribute('src')));
+ this.media.setAttribute('style', 'object-fit:inherit; width:inherit');
+
+ this.objectFitDimensions = { height: 0, width: 0 };
+ if (this.getAttribute('src') !== undefined) {
+ this.computeObjectFitDimensions();
+ this.generateNewMediaPlaneGeometry();
+ this.loadMediaTexture();
+ }
+ }
+
+ _mutationCheck() {
+ // to be filled in by children
+ }
+
+ /**
+ * @function
+ * @description Callback function of MREntity - Updates the image's cover,fill,etc based on the mutation request.
+ * @param {object} mutation - the update/change/mutation to be handled.
+ */
+ mutated(mutation) {
+ super.mutated();
+
+ // moving the if 'mutation' handling check to the children, since
+ // mutations are only understood by their actual type. Any mutation
+ // passed through MRMedia directly is undefined since it is not
+ // a direct element for users.
+ //
+ // those functions can do the if (mutation.type ....) handling and
+ // their specific cases and then call back up to here to run the below functionality. | super is a good solution! |
mrjs | github_2023 | javascript | 464 | Volumetrics-io | takahirox | @@ -82,13 +82,39 @@ material.loadTextureAsync = function (src) {
};
material.loadVideoTextureAsync = function (video) {
+ video.src = html.resolvePath(video.src);
+
+ video.muted = true; // Mute the video to allow autoplay
+ video.autoplay = false; //true; // Attempt to autoplay
+
return new Promise((resolve, reject) => {
- try {
- const textureLoader = new THREE.VideoTexture(video);
- resolve(textureLoader);
- } catch(err) {
- reject(err);
- }
+ // Event listener to ensure video is ready
+ video.onloadeddata = () => {
+ try {
+ const textureLoader = new THREE.VideoTexture(video); | Nit for an existing issue: Isn't the name `textureLoader` for `VideoTexture` instance confusing because Three.js has `TextureLoader` class? Maybe `texture` or `videoTexture` would be clearer? |
mrjs | github_2023 | javascript | 464 | Volumetrics-io | takahirox | @@ -36,6 +36,9 @@ export class MaterialStyleSystem extends MRSystem {
if (entity instanceof MRDivEntity) {
this.setBackground(entity);
}
+ if (entity instanceof MRVideo && entity.playing) {
+ entity.texture.needsUpdate = true;
+ } | Is a texture of `MRVideo` guaranteed to be as `VideoTexture`? If so we may not need to manually call `texture.needsUpdate = true` because it's automatically (and more efficiently with [requestVideoFrameCallback](https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement/requestVideoFrameCallback)) set
https://threejs.org/docs/#api/en/textures/VideoTexture.needsUpdate
Even if it isn't guaranteed, we may add a guard like
```
if (entity instanceof MRVideo && entity.playing && !entity.texture.isVideoTexture) {
entity.texture.needsUpdate = true;
}
``` |
mrjs | github_2023 | others | 464 | Volumetrics-io | takahirox | @@ -37,81 +28,74 @@
<footer>
<script>
- let rig = document.querySelector('#rig')
- let panels = document.querySelectorAll('.layout')
+ let rig = document.querySelector('#rig');
+ let panels = document.querySelectorAll('.layout');
+ let videoEl = document.querySelector('#videoEl');
- let frontIndex = 0
+ let frontIndex = 0;
function playVideo() {
- let videoEl = document.querySelector('#videoEl')
- videoEl.play()
+ videoEl.play();; | Nit: Duplicated ";" |
mrjs | github_2023 | javascript | 464 | Volumetrics-io | takahirox | @@ -0,0 +1,242 @@
+import * as THREE from 'three';
+
+import { MRDivEntity } from 'mrjs/core/MRDivEntity';
+
+import { mrjsUtils } from 'mrjs';
+
+/**
+ * @class MRMedia
+ * @classdesc Base html media entity represented in 3D space. `mr-media`
+ * @augments MRDivEntity
+ */
+export class MRMedia extends MRDivEntity {
+ /**
+ * @class
+ * @description Constructs a base media entity using a UIPlane and other 3D elements as necessary.
+ */
+ constructor() {
+ super();
+ this.attachShadow({ mode: 'open' });
+
+ // Create the object3D. Dont need default value for geometry
+ // until the connected call since this will get overwritten anyways.
+ let material = new THREE.MeshStandardMaterial({ | I would like to suggest to always use `const` specifier instead of `let` for immutable variables to avoid unexpected reassignment. (Depending on the team coding style tho) |
mrjs | github_2023 | javascript | 464 | Volumetrics-io | takahirox | @@ -0,0 +1,242 @@
+import * as THREE from 'three';
+
+import { MRDivEntity } from 'mrjs/core/MRDivEntity';
+
+import { mrjsUtils } from 'mrjs';
+
+/**
+ * @class MRMedia
+ * @classdesc Base html media entity represented in 3D space. `mr-media`
+ * @augments MRDivEntity
+ */
+export class MRMedia extends MRDivEntity {
+ /**
+ * @class
+ * @description Constructs a base media entity using a UIPlane and other 3D elements as necessary.
+ */
+ constructor() {
+ super();
+ this.attachShadow({ mode: 'open' });
+
+ // Create the object3D. Dont need default value for geometry
+ // until the connected call since this will get overwritten anyways.
+ let material = new THREE.MeshStandardMaterial({
+ side: 0, | Using named Three.js constants, `THREE.FrontSide` in this case, would be more readable |
mrjs | github_2023 | javascript | 464 | Volumetrics-io | takahirox | @@ -0,0 +1,242 @@
+import * as THREE from 'three';
+
+import { MRDivEntity } from 'mrjs/core/MRDivEntity';
+
+import { mrjsUtils } from 'mrjs';
+
+/**
+ * @class MRMedia
+ * @classdesc Base html media entity represented in 3D space. `mr-media`
+ * @augments MRDivEntity
+ */
+export class MRMedia extends MRDivEntity {
+ /**
+ * @class
+ * @description Constructs a base media entity using a UIPlane and other 3D elements as necessary.
+ */
+ constructor() {
+ super();
+ this.attachShadow({ mode: 'open' });
+
+ // Create the object3D. Dont need default value for geometry
+ // until the connected call since this will get overwritten anyways.
+ let material = new THREE.MeshStandardMaterial({
+ side: 0,
+ transparent: true,
+ });
+ // Object3D for MRMedia (mrimage,mrvideo,etc) is the actual image/video/etc itself in 3D space
+ this.object3D = new THREE.Mesh(undefined, material);
+ this.object3D.receiveShadow = true;
+ this.object3D.renderOrder = 3; | Not a review comment but just a question for existing code so not blocking: What is this `renderOrder = 3` for? Adding a comment would be helpful to users. |
mrjs | github_2023 | javascript | 464 | Volumetrics-io | takahirox | @@ -0,0 +1,242 @@
+import * as THREE from 'three';
+
+import { MRDivEntity } from 'mrjs/core/MRDivEntity';
+
+import { mrjsUtils } from 'mrjs';
+
+/**
+ * @class MRMedia
+ * @classdesc Base html media entity represented in 3D space. `mr-media`
+ * @augments MRDivEntity
+ */
+export class MRMedia extends MRDivEntity {
+ /**
+ * @class
+ * @description Constructs a base media entity using a UIPlane and other 3D elements as necessary.
+ */
+ constructor() {
+ super();
+ this.attachShadow({ mode: 'open' });
+
+ // Create the object3D. Dont need default value for geometry
+ // until the connected call since this will get overwritten anyways.
+ let material = new THREE.MeshStandardMaterial({
+ side: 0,
+ transparent: true,
+ });
+ // Object3D for MRMedia (mrimage,mrvideo,etc) is the actual image/video/etc itself in 3D space
+ this.object3D = new THREE.Mesh(undefined, material);
+ this.object3D.receiveShadow = true;
+ this.object3D.renderOrder = 3;
+ this.object3D.name = 'media';
+
+ // the media to be filled out.
+ // for ex: document.createElement('video') or document.createElement('img');
+ this.media = null;
+
+ // This is a reference to the texture that is used as part of the
+ // threejs material. Separating it out for easier updating after it is loaded.
+ // The texture is filled-in in the connected function.
+ this.texture = null;
+
+ // This is used to aid in the formatting for certain object-fit setups
+ // ex: contain, scale-down
+ this.subMediaMesh = null;
+ }
+
+ /**
+ * @function
+ * @description Calculates the width of the img based on the img tag in the shadow root
+ * @returns {number} - the resolved width
+ */
+ get width() {
+ let width = this.objectFitDimensions?.width;
+ return width > 0 ? width : super.width;
+ }
+
+ /**
+ * @function
+ * @description Calculates the height of the img based on the img tag in the shadow root
+ * @returns {number} - the resolved height
+ */
+ get height() {
+ let height = this.objectFitDimensions?.height;
+ return height > 0 ? height : super.height;
+ }
+
+ get mediaWidth() {
+ // to be filled in in children | Nit, not blocking issue: Do we want to throw an error here? We may be able to more easily detect in cases if we forgot to override this method in child classes. |
mrjs | github_2023 | javascript | 464 | Volumetrics-io | takahirox | @@ -82,13 +82,39 @@ material.loadTextureAsync = function (src) {
};
material.loadVideoTextureAsync = function (video) {
+ video.src = html.resolvePath(video.src);
+
+ video.muted = true; // Mute the video to allow autoplay
+ video.autoplay = false; //true; // Attempt to autoplay
+
return new Promise((resolve, reject) => {
- try {
- const textureLoader = new THREE.VideoTexture(video);
- resolve(textureLoader);
- } catch(err) {
- reject(err);
- }
+ // Event listener to ensure video is ready
+ video.onloadeddata = () => {
+ try {
+ const textureLoader = new THREE.VideoTexture(video);
+ textureLoader.needsUpdate = true; // Ensure the texture updates when the video plays
+
+ video
+ .play()
+ .then(() => {
+ console.log('Video playback started');
+ })
+ .catch((e) => {
+ console.error('Error trying to play the video:', e);
+ reject(e);
+ });
+ resolve(textureLoader);
+ } catch (err) { | Curious, which line above in try can throw an un-caught error? video play error stuffs seems to be caught above. |
mrjs | github_2023 | others | 436 | Volumetrics-io | michaelthatsit | @@ -0,0 +1,120 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <meta charset="utf-8">
+ <title>mr.js - video</title>
+ <meta name="description" content="mr.js example - video">
+ <script src="/mr.js"></script>
+ <link rel="stylesheet" type="text/css" href="video-style.css" />
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ </head>
+ <body >
+ <mr-app>
+ <mr-entity id="rig" data-comp-anchor="type: fixed;">
+ <mr-panel id="tabbar" data-position="0 0 0.001"> <!--TODO: move Z offset to css z-index-->
+ <mr-button onclick="playVideo()" class="col-1">Play</mr-button>
+ <mr-button onclick="stopVideo()" class="col-2">Stop</mr-button>
+ <mr-button onclick="screenShare()" class="col-3">Screenshare</mr-button> | This is really cool! but probably shouldn't make it into the simple example. Also it doesn't work when in headset. Maybe we replace it with a loop button? |
mrjs | github_2023 | javascript | 436 | Volumetrics-io | michaelthatsit | @@ -0,0 +1,211 @@
+import * as THREE from 'three';
+
+import { MRDivEntity } from 'mrjs/core/MRDivEntity';
+
+import { mrjsUtils } from 'mrjs';
+
+/**
+ * @class MRVideo
+ * @classdesc Base html video represented in 3D space. `mr-video`
+ * @augments MRDivEntity
+ */
+export class MRVideo extends MRDivEntity { | @hanbollar you're currently working on the fix for `object-fit`, MRVideo should be treated the same as MRImage. Perhaps we can extract their common features out into MRMedia? that wouldn't need to be exposed as a tag itself, but might make it easy for us to apply the same responsiveness logic to both. |
mrjs | github_2023 | javascript | 403 | Volumetrics-io | hanbollar | @@ -102,7 +102,7 @@ export class LayoutSystem extends MRSystem {
if (entity.compStyle.zIndex != 'auto') {
// default zIndex values in css are in the 1000s - using this arbitrary divide to convert to an actual usable threejs value.
- entity.object3D.position.setZ(parseFloat(entity.compStyle.zIndex / 1000));
+ entity.object3D.position.setZ(parseFloat(entity.compStyle.zIndex) / 1000); | do we also need this fix in the panel system? |
mrjs | github_2023 | others | 382 | Volumetrics-io | hanbollar | @@ -9,21 +9,20 @@
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body >
- <mr-app debug="false">
+ <mr-app debug="true"> | switch this back |
mrjs | github_2023 | others | 382 | Volumetrics-io | hanbollar | @@ -9,21 +9,20 @@
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body >
- <mr-app>
+ <mr-app debug="true"> | this should be swapped back |
mrjs | github_2023 | others | 382 | Volumetrics-io | hanbollar | @@ -2,34 +2,33 @@
<html>
<head>
<meta charset="utf-8">
- <title>mr.js - anchors</title>
- <meta name="description" content="mr.js example - anchors">
+ <title>mr.js - panels</title>
+ <meta name="description" content="mr.js example - panels">
<script src="/mr.js"></script>
<link rel="stylesheet" type="text/css" href="panels-style.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body >
- <mr-app debug="false">
+ <mr-app debug="true"> | are all examples debug=true now? (just realized a lot of them switched to this - if yes, ignore my prev comments, if no, just make sure to swap the rest of them and i'll stop commenting as part of the review here to not overspam) |
mrjs | github_2023 | javascript | 382 | Volumetrics-io | hanbollar | @@ -89,29 +90,210 @@ export class ControlSystem extends MRSystem {
this.leftHand.setMesh();
this.rightHand.setMesh();
+ mrjsUtils.physics.eventQueue.drainCollisionEvents((handle1, handle2, started) => {
+ /* Handle the collision event. */
+
+ if (started) {
+ this.onContactStart(handle1, handle2);
+ } else {
+ this.onContactEnd(handle1, handle2);
+ }
+ });
+
this.leftHand.update();
this.rightHand.update();
+ this.checkCollisions(this.leftHand)
+ this.checkCollisions(this.rightHand)
+
if (mrjsUtils.xr.isPresenting) {
- this.origin.setFromMatrixPosition(this.app.userOrigin.matrixWorld);
- this.direction.setFromMatrixPosition(this.activeHand.pointer.matrixWorld).sub(this.origin).normalize();
+ this.pointerRay()
+ }
+ }
- this.ray.origin = { ...this.origin };
- this.ray.dir = { ...this.direction };
+ checkCollisions(hand) {
+ for( let jointCursor of hand.jointCursors) {
+ this.app.physicsWorld.contactPairsWith(jointCursor.collider, (collider2) => {
+ const entity = mrjsUtils.physics.COLLIDER_ENTITY_MAP[collider2.handle];
+
+ if (entity) {
+ if (!jointCursor.name.includes('hover') && entity.touch) {
+ this.tempPreviousPosition.copy(this.tempLocalPosition);
+
+ this.tempLocalPosition.copy(jointCursor.collider.translation());
+ entity.object3D.worldToLocal(this.tempLocalPosition);
+
+ this.touchDelta.subVectors(this.tempLocalPosition, this.tempPreviousPosition);
+
+ entity.dispatchEvent(
+ new CustomEvent('touch', {
+ bubbles: true,
+ detail: {
+ joint: jointCursor.name,
+ worldPosition: jointCursor.collider.translation(),
+ position: this.tempLocalPosition,
+ delta: this.touchDelta,
+ },
+ })
+ );
+ }
+ }
+ });
+ }
+ }
- this.hit = this.app.physicsWorld.castRayAndGetNormal(this.ray, 100, true, null, mrjsUtils.physics.CollisionGroups.UI, null, null);
- if (this.hit != null) {
- this.hitPosition.copy(this.ray.pointAt(this.hit.toi));
- this.hitNormal.copy(this.hit.normal);
- this.cursorViz.visible = true;
- this.cursorViz.position.copy(this.hitPosition);
+ /**
+ * @function
+ * @description Handles the start of collisions between two different colliders.
+ * @param {number} handle1 - the first collider
+ * @param {number} handle2 - the second collider
+ */
+ onContactStart = (handle1, handle2) => {
+ const collider1 = this.app.physicsWorld.colliders.get(handle1);
+ const collider2 = this.app.physicsWorld.colliders.get(handle2);
- this.cursorViz.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), this.hit.normal);
+ const joint = mrjsUtils.physics.INPUT_COLLIDER_HANDLE_NAMES[handle1];
+ const entity = mrjsUtils.physics.COLLIDER_ENTITY_MAP[handle2];
- this.interact(mrjsUtils.physics.COLLIDER_ENTITY_MAP[this.hit.collider.handle]);
- } else {
- this.cursorViz.visible = false;
- }
+ if (joint && entity && !joint.includes('hover')) {
+ this.touchStart(collider1, collider2, entity);
+ return;
+ }
+
+ if (joint && entity && joint.includes('hover')) {
+ this.hoverStart(collider1, collider2, entity);
+ } | this should be simplified for readability and better branching to:
```
if (joint && entity) {
if (joint.includes('hover')) {
this.touchStart...
} else {
this.hoverStart...
}
}
``` |
mrjs | github_2023 | javascript | 382 | Volumetrics-io | hanbollar | @@ -89,29 +90,210 @@ export class ControlSystem extends MRSystem {
this.leftHand.setMesh();
this.rightHand.setMesh();
+ mrjsUtils.physics.eventQueue.drainCollisionEvents((handle1, handle2, started) => {
+ /* Handle the collision event. */
+
+ if (started) {
+ this.onContactStart(handle1, handle2);
+ } else {
+ this.onContactEnd(handle1, handle2);
+ }
+ });
+
this.leftHand.update();
this.rightHand.update();
+ this.checkCollisions(this.leftHand)
+ this.checkCollisions(this.rightHand)
+
if (mrjsUtils.xr.isPresenting) {
- this.origin.setFromMatrixPosition(this.app.userOrigin.matrixWorld);
- this.direction.setFromMatrixPosition(this.activeHand.pointer.matrixWorld).sub(this.origin).normalize();
+ this.pointerRay()
+ }
+ }
- this.ray.origin = { ...this.origin };
- this.ray.dir = { ...this.direction };
+ checkCollisions(hand) {
+ for( let jointCursor of hand.jointCursors) {
+ this.app.physicsWorld.contactPairsWith(jointCursor.collider, (collider2) => {
+ const entity = mrjsUtils.physics.COLLIDER_ENTITY_MAP[collider2.handle];
+
+ if (entity) {
+ if (!jointCursor.name.includes('hover') && entity.touch) {
+ this.tempPreviousPosition.copy(this.tempLocalPosition);
+
+ this.tempLocalPosition.copy(jointCursor.collider.translation());
+ entity.object3D.worldToLocal(this.tempLocalPosition);
+
+ this.touchDelta.subVectors(this.tempLocalPosition, this.tempPreviousPosition);
+
+ entity.dispatchEvent(
+ new CustomEvent('touch', {
+ bubbles: true,
+ detail: {
+ joint: jointCursor.name,
+ worldPosition: jointCursor.collider.translation(),
+ position: this.tempLocalPosition,
+ delta: this.touchDelta,
+ },
+ })
+ );
+ }
+ }
+ });
+ }
+ }
- this.hit = this.app.physicsWorld.castRayAndGetNormal(this.ray, 100, true, null, mrjsUtils.physics.CollisionGroups.UI, null, null);
- if (this.hit != null) {
- this.hitPosition.copy(this.ray.pointAt(this.hit.toi));
- this.hitNormal.copy(this.hit.normal);
- this.cursorViz.visible = true;
- this.cursorViz.position.copy(this.hitPosition);
+ /**
+ * @function
+ * @description Handles the start of collisions between two different colliders.
+ * @param {number} handle1 - the first collider
+ * @param {number} handle2 - the second collider
+ */
+ onContactStart = (handle1, handle2) => {
+ const collider1 = this.app.physicsWorld.colliders.get(handle1);
+ const collider2 = this.app.physicsWorld.colliders.get(handle2);
- this.cursorViz.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), this.hit.normal);
+ const joint = mrjsUtils.physics.INPUT_COLLIDER_HANDLE_NAMES[handle1];
+ const entity = mrjsUtils.physics.COLLIDER_ENTITY_MAP[handle2];
- this.interact(mrjsUtils.physics.COLLIDER_ENTITY_MAP[this.hit.collider.handle]);
- } else {
- this.cursorViz.visible = false;
- }
+ if (joint && entity && !joint.includes('hover')) {
+ this.touchStart(collider1, collider2, entity);
+ return;
+ }
+
+ if (joint && entity && joint.includes('hover')) {
+ this.hoverStart(collider1, collider2, entity);
+ }
+ };
+
+ /**
+ * @function
+ * @description Handles the end of collisions between two different colliders.
+ * @param {number} handle1 - the first collider
+ * @param {number} handle2 - the second collider
+ */
+ onContactEnd = (handle1, handle2) => {
+ const joint = mrjsUtils.physics.INPUT_COLLIDER_HANDLE_NAMES[handle1];
+ const entity = mrjsUtils.physics.COLLIDER_ENTITY_MAP[handle2];
+
+ if (joint && entity && !joint.includes('hover')) {
+ this.touchEnd(entity);
+ return;
+ }
+
+ if (joint && entity && joint.includes('hover')) {
+ this.hoverEnd(entity);
+ }
+ }; | same comment as before for the if () { if else } - and if there will eventually be more logic here, this should be separated out in another function, if this is the main plan for these then no need to separate out |
mrjs | github_2023 | javascript | 382 | Volumetrics-io | hanbollar | @@ -89,29 +90,210 @@ export class ControlSystem extends MRSystem {
this.leftHand.setMesh();
this.rightHand.setMesh();
+ mrjsUtils.physics.eventQueue.drainCollisionEvents((handle1, handle2, started) => {
+ /* Handle the collision event. */
+
+ if (started) {
+ this.onContactStart(handle1, handle2);
+ } else {
+ this.onContactEnd(handle1, handle2);
+ }
+ });
+
this.leftHand.update();
this.rightHand.update();
+ this.checkCollisions(this.leftHand)
+ this.checkCollisions(this.rightHand)
+
if (mrjsUtils.xr.isPresenting) {
- this.origin.setFromMatrixPosition(this.app.userOrigin.matrixWorld);
- this.direction.setFromMatrixPosition(this.activeHand.pointer.matrixWorld).sub(this.origin).normalize();
+ this.pointerRay()
+ }
+ }
- this.ray.origin = { ...this.origin };
- this.ray.dir = { ...this.direction };
+ checkCollisions(hand) {
+ for( let jointCursor of hand.jointCursors) {
+ this.app.physicsWorld.contactPairsWith(jointCursor.collider, (collider2) => {
+ const entity = mrjsUtils.physics.COLLIDER_ENTITY_MAP[collider2.handle];
+
+ if (entity) {
+ if (!jointCursor.name.includes('hover') && entity.touch) {
+ this.tempPreviousPosition.copy(this.tempLocalPosition);
+
+ this.tempLocalPosition.copy(jointCursor.collider.translation());
+ entity.object3D.worldToLocal(this.tempLocalPosition);
+
+ this.touchDelta.subVectors(this.tempLocalPosition, this.tempPreviousPosition);
+
+ entity.dispatchEvent(
+ new CustomEvent('touch', {
+ bubbles: true,
+ detail: {
+ joint: jointCursor.name,
+ worldPosition: jointCursor.collider.translation(),
+ position: this.tempLocalPosition,
+ delta: this.touchDelta,
+ },
+ })
+ );
+ }
+ }
+ });
+ }
+ }
- this.hit = this.app.physicsWorld.castRayAndGetNormal(this.ray, 100, true, null, mrjsUtils.physics.CollisionGroups.UI, null, null);
- if (this.hit != null) {
- this.hitPosition.copy(this.ray.pointAt(this.hit.toi));
- this.hitNormal.copy(this.hit.normal);
- this.cursorViz.visible = true;
- this.cursorViz.position.copy(this.hitPosition);
+ /**
+ * @function
+ * @description Handles the start of collisions between two different colliders.
+ * @param {number} handle1 - the first collider
+ * @param {number} handle2 - the second collider
+ */
+ onContactStart = (handle1, handle2) => {
+ const collider1 = this.app.physicsWorld.colliders.get(handle1);
+ const collider2 = this.app.physicsWorld.colliders.get(handle2);
- this.cursorViz.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), this.hit.normal);
+ const joint = mrjsUtils.physics.INPUT_COLLIDER_HANDLE_NAMES[handle1];
+ const entity = mrjsUtils.physics.COLLIDER_ENTITY_MAP[handle2];
- this.interact(mrjsUtils.physics.COLLIDER_ENTITY_MAP[this.hit.collider.handle]);
- } else {
- this.cursorViz.visible = false;
- }
+ if (joint && entity && !joint.includes('hover')) {
+ this.touchStart(collider1, collider2, entity);
+ return;
+ }
+
+ if (joint && entity && joint.includes('hover')) {
+ this.hoverStart(collider1, collider2, entity);
+ }
+ };
+
+ /**
+ * @function
+ * @description Handles the end of collisions between two different colliders.
+ * @param {number} handle1 - the first collider
+ * @param {number} handle2 - the second collider
+ */
+ onContactEnd = (handle1, handle2) => {
+ const joint = mrjsUtils.physics.INPUT_COLLIDER_HANDLE_NAMES[handle1];
+ const entity = mrjsUtils.physics.COLLIDER_ENTITY_MAP[handle2];
+
+ if (joint && entity && !joint.includes('hover')) {
+ this.touchEnd(entity);
+ return;
+ }
+
+ if (joint && entity && joint.includes('hover')) {
+ this.hoverEnd(entity);
+ }
+ };
+
+ /**
+ * @function
+ * @description Handles the start of touch between two different colliders and the current entity.
+ * @param {number} collider1 - the first collider
+ * @param {number} collider2 - the second collider
+ * @param {MREntity} entity - the current entity
+ */
+ touchStart = (collider1, collider2, entity) => {
+ entity.touch = true;
+ this.app.physicsWorld.contactPair(collider1, collider2, (manifold, flipped) => {
+ this.tempLocalPosition.copy(manifold.localContactPoint2(0));
+ this.tempWorldPosition.copy(manifold.localContactPoint2(0));
+ entity.object3D.localToWorld(this.tempWorldPosition);
+ entity.classList.remove('hover');
+
+ entity.dispatchEvent(
+ new CustomEvent('touch-start', {
+ bubbles: true,
+ detail: {
+ worldPosition: this.tempWorldPosition,
+ position: this.tempLocalPosition,
+ },
+ })
+ );
+ });
+ };
+
+ /**
+ * @function
+ * @description Handles the end of touch for the current entity
+ * @param {MREntity} entity - the current entity
+ */
+ touchEnd = (entity) => {
+ // Contact information can be read from `manifold`. | what does this comment mean? |
mrjs | github_2023 | javascript | 382 | Volumetrics-io | hanbollar | @@ -58,230 +57,160 @@ export class PhysicsSystem extends MRSystem {
* @param {object} frame - given frame information to be used for any feature changes
*/
update(deltaTime, frame) {
- this.app.physicsWorld.step(this.eventQueue);
-
- this.eventQueue.drainCollisionEvents((handle1, handle2, started) => {
- /* Handle the collision event. */
-
- if (started) {
- this.onContactStart(handle1, handle2);
- } else {
- this.onContactEnd(handle1, handle2);
- }
- });
+ this.app.physicsWorld.step(mrjsUtils.physics.eventQueue);
for (const entity of this.registry) {
if (entity.physics?.body == null) {
continue;
}
this.updateBody(entity);
- this.app.physicsWorld.contactPairsWith(entity.physics.collider, (collider2) => {
- const joint = mrjsUtils.physics.INPUT_COLLIDER_HANDLE_NAMES[collider2.handle];
-
- if (joint) {
- if (!joint.includes('hover') && entity.touch) {
- this.tempPreviousPosition.copy(this.tempLocalPosition);
-
- this.tempLocalPosition.copy(collider2.translation());
- entity.object3D.worldToLocal(this.tempLocalPosition);
-
- this.touchDelta.subVectors(this.tempLocalPosition, this.tempPreviousPosition);
-
- entity.dispatchEvent(
- new CustomEvent('touch', {
- bubbles: true,
- detail: {
- joint,
- worldPosition: collider2.translation(),
- position: this.tempLocalPosition,
- delta: this.touchDelta,
- },
- })
- );
- }
- }
- });
}
this.updateDebugRenderer();
}
+
/**
* @function
- * @description Handles the start of collisions between two different colliders.
- * @param {number} handle1 - the first collider
- * @param {number} handle2 - the second collider
+ * @description When a new entity is created, adds it to the physics registry and initializes the physics aspects of the entity.
+ * @param {MREntity} entity - the entity being set up
*/
- onContactStart = (handle1, handle2) => {
- const collider1 = this.app.physicsWorld.colliders.get(handle1);
- const collider2 = this.app.physicsWorld.colliders.get(handle2);
-
- const joint = mrjsUtils.physics.INPUT_COLLIDER_HANDLE_NAMES[handle1];
- const entity = mrjsUtils.physics.COLLIDER_ENTITY_MAP[handle2];
-
- if (joint && entity && !joint.includes('hover')) {
- // if(this.currentEntity) {
- // return
- // }
- // TODO - can the above commented code be deleted? - TBD
- this.touchStart(collider1, collider2, entity);
+ onNewEntity(entity) {
+ if (entity.physics.type == 'none') {
return;
}
- if (joint && entity && joint.includes('hover')) {
- this.hoverStart(collider1, collider2, entity);
+ if(entity instanceof MRDivEntity) {
+ this.initPhysicsBody(entity);
+ this.registry.add(entity);
}
- };
+ }
/**
* @function
- * @description Handles the end of collisions between two different colliders.
- * @param {number} handle1 - the first collider
- * @param {number} handle2 - the second collider
+ * @description Initializes the rigid body used by the physics part of the entity
+ * @param {MREntity} entity - the entity being updated
*/
- onContactEnd = (handle1, handle2) => {
- const joint = mrjsUtils.physics.INPUT_COLLIDER_HANDLE_NAMES[handle1];
- const entity = mrjsUtils.physics.COLLIDER_ENTITY_MAP[handle2];
+ initPhysicsBody(entity) {
- if (joint && entity && !joint.includes('hover')) {
- this.touchEnd(entity);
- return;
- }
+ if(entity instanceof MRModel){
+ this.initSimpleBody(entity)
- if (joint && entity && joint.includes('hover')) {
- this.hoverEnd(entity);
+ } else if( entity instanceof MRDivEntity) {
+ this.initUIEntityBody(entity) | we have the open issue of MRModel possibly being moved to inherit from MRDivEntity instead of MREntity - will there be a case where MRModel also needs initUIEntityBody? if so, make sure this reflects that or has a todo comment to warn for when we make that change |
mrjs | github_2023 | javascript | 382 | Volumetrics-io | hanbollar | @@ -58,230 +57,160 @@ export class PhysicsSystem extends MRSystem {
* @param {object} frame - given frame information to be used for any feature changes
*/
update(deltaTime, frame) {
- this.app.physicsWorld.step(this.eventQueue);
-
- this.eventQueue.drainCollisionEvents((handle1, handle2, started) => {
- /* Handle the collision event. */
-
- if (started) {
- this.onContactStart(handle1, handle2);
- } else {
- this.onContactEnd(handle1, handle2);
- }
- });
+ this.app.physicsWorld.step(mrjsUtils.physics.eventQueue);
for (const entity of this.registry) {
if (entity.physics?.body == null) {
continue;
}
this.updateBody(entity);
- this.app.physicsWorld.contactPairsWith(entity.physics.collider, (collider2) => {
- const joint = mrjsUtils.physics.INPUT_COLLIDER_HANDLE_NAMES[collider2.handle];
-
- if (joint) {
- if (!joint.includes('hover') && entity.touch) {
- this.tempPreviousPosition.copy(this.tempLocalPosition);
-
- this.tempLocalPosition.copy(collider2.translation());
- entity.object3D.worldToLocal(this.tempLocalPosition);
-
- this.touchDelta.subVectors(this.tempLocalPosition, this.tempPreviousPosition);
-
- entity.dispatchEvent(
- new CustomEvent('touch', {
- bubbles: true,
- detail: {
- joint,
- worldPosition: collider2.translation(),
- position: this.tempLocalPosition,
- delta: this.touchDelta,
- },
- })
- );
- }
- }
- });
}
this.updateDebugRenderer();
}
+
/**
* @function
- * @description Handles the start of collisions between two different colliders.
- * @param {number} handle1 - the first collider
- * @param {number} handle2 - the second collider
+ * @description When a new entity is created, adds it to the physics registry and initializes the physics aspects of the entity.
+ * @param {MREntity} entity - the entity being set up
*/
- onContactStart = (handle1, handle2) => {
- const collider1 = this.app.physicsWorld.colliders.get(handle1);
- const collider2 = this.app.physicsWorld.colliders.get(handle2);
-
- const joint = mrjsUtils.physics.INPUT_COLLIDER_HANDLE_NAMES[handle1];
- const entity = mrjsUtils.physics.COLLIDER_ENTITY_MAP[handle2];
-
- if (joint && entity && !joint.includes('hover')) {
- // if(this.currentEntity) {
- // return
- // }
- // TODO - can the above commented code be deleted? - TBD
- this.touchStart(collider1, collider2, entity);
+ onNewEntity(entity) {
+ if (entity.physics.type == 'none') {
return;
}
- if (joint && entity && joint.includes('hover')) {
- this.hoverStart(collider1, collider2, entity);
+ if(entity instanceof MRDivEntity) {
+ this.initPhysicsBody(entity);
+ this.registry.add(entity);
}
- };
+ }
/**
* @function
- * @description Handles the end of collisions between two different colliders.
- * @param {number} handle1 - the first collider
- * @param {number} handle2 - the second collider
+ * @description Initializes the rigid body used by the physics part of the entity
+ * @param {MREntity} entity - the entity being updated
*/
- onContactEnd = (handle1, handle2) => {
- const joint = mrjsUtils.physics.INPUT_COLLIDER_HANDLE_NAMES[handle1];
- const entity = mrjsUtils.physics.COLLIDER_ENTITY_MAP[handle2];
+ initPhysicsBody(entity) {
- if (joint && entity && !joint.includes('hover')) {
- this.touchEnd(entity);
- return;
- }
+ if(entity instanceof MRModel){
+ this.initSimpleBody(entity)
- if (joint && entity && joint.includes('hover')) {
- this.hoverEnd(entity);
+ } else if( entity instanceof MRDivEntity) {
+ this.initUIEntityBody(entity)
}
- };
- /**
- * @function
- * @description Handles the start of touch between two different colliders and the current entity.
- * @param {number} collider1 - the first collider
- * @param {number} collider2 - the second collider
- * @param {MREntity} entity - the current entity
- */
- touchStart = (collider1, collider2, entity) => {
- this.currentEntity = entity;
- entity.touch = true;
- this.app.physicsWorld.contactPair(collider1, collider2, (manifold, flipped) => {
- this.tempLocalPosition.copy(manifold.localContactPoint2(0));
- this.tempWorldPosition.copy(manifold.localContactPoint2(0));
- entity.object3D.localToWorld(this.tempWorldPosition);
- entity.classList.remove('hover');
-
- entity.dispatchEvent(
- new CustomEvent('touch-start', {
- bubbles: true,
- detail: {
- worldPosition: this.tempWorldPosition,
- position: this.tempLocalPosition,
- },
- })
- );
- });
- };
+ entity.object3D.getWorldPosition(this.tempWorldPosition);
+ entity.object3D.getWorldQuaternion(this.tempWorldQuaternion);
- /**
- * @function
- * @description Handles the end of touch for the current entity
- * @param {MREntity} entity - the current entity
- */
- touchEnd = (entity) => {
- this.currentEntity = null;
- // Contact information can be read from `manifold`.
- this.tempPreviousPosition.set(0, 0, 0);
- this.tempLocalPosition.set(0, 0, 0);
- this.tempWorldPosition.set(0, 0, 0);
- entity.touch = false;
- entity.click();
-
- entity.dispatchEvent(
- new CustomEvent('touch-end', {
- bubbles: true,
- })
- );
- };
+ entity.physics.body.setTranslation(...this.tempWorldPosition, true);
+ entity.physics.body.setRotation(this.tempWorldQuaternion, true);
+
+ }
/**
* @function
- * @description Handles the start of hovering over/around a specific entity.
- * @param {number} collider1 - the first collider
- * @param {number} collider2 - the second collider
- * @param {MREntity} entity - the current entity
+ * @description Initializes the rigid body used by the physics for div or Model entity
+ * @param {MREntity} entity - the entity being updated
*/
- hoverStart = (collider1, collider2, entity) => {
- entity.classList.add('hover');
- this.app.physicsWorld.contactPair(collider1, collider2, (manifold, flipped) => {
- this.tempLocalPosition.copy(manifold.localContactPoint2(0));
- this.tempWorldPosition.copy(manifold.localContactPoint2(0));
- entity.object3D.localToWorld(this.tempWorldPosition);
- entity.dispatchEvent(
- new CustomEvent('hover-start', {
- bubbles: true,
- detail: {
- worldPosition: this.tempWorldPosition,
- position: this.tempLocalPosition,
- },
- })
- );
-
- entity.dispatchEvent(new MouseEvent('mouseover'));
- });
- };
+ initUIEntityBody(entity) {
+ entity.physics.halfExtents = new THREE.Vector3()
+ this.tempBBox.setFromCenterAndSize(entity.object3D.position, new THREE.Vector3(entity.width, entity.height, 0.002));
+
+ this.tempWorldScale.setFromMatrixScale(entity.object3D.matrixWorld);
+ this.tempBBox.getSize(this.tempSize);
+ this.tempSize.multiply(this.tempWorldScale);
+
+ entity.physics.halfExtents.copy(this.tempSize);
+ entity.physics.halfExtents.divideScalar(2);
+
+ const rigidBodyDesc = mrjsUtils.physics.RAPIER.RigidBodyDesc.fixed()
+ entity.physics.body = this.app.physicsWorld.createRigidBody(rigidBodyDesc);
+
+ let colliderDesc = mrjsUtils.physics.RAPIER.ColliderDesc.cuboid(...entity.physics.halfExtents);
+ colliderDesc.setCollisionGroups(mrjsUtils.physics.CollisionGroups.UI);
+ entity.physics.collider = this.app.physicsWorld.createCollider(colliderDesc, entity.physics.body);
+ mrjsUtils.physics.COLLIDER_ENTITY_MAP[entity.physics.collider.handle] = entity;
+ entity.physics.collider.setActiveCollisionTypes(mrjsUtils.physics.RAPIER.ActiveCollisionTypes.DEFAULT | mrjsUtils.physics.RAPIER.ActiveCollisionTypes.KINEMATIC_FIXED);
+ entity.physics.collider.setActiveEvents(mrjsUtils.physics.RAPIER.ActiveEvents.COLLISION_EVENTS);
+
+
+ }
/**
* @function
- * @description Handles the end of hovering over/around a specific entity.
- * @param {MREntity} entity - the current entity
+ * @description Initializes a simple bounding box collider based on the visual bounds of the entity
+ * @param {MREntity} entity - the entity being updated
*/
- hoverEnd = (entity) => {
- entity.classList.remove('hover');
- entity.dispatchEvent(
- new CustomEvent('hover-end', {
- bubbles: true,
- })
- );
+ initSimpleBody(entity) {
+ entity.physics.halfExtents = new THREE.Vector3()
+ this.tempBBox.setFromObject(entity.object3D, true);
+
+ this.tempBBox.getSize(this.tempSize);
+
+ entity.physics.halfExtents.copy(this.tempSize);
+ entity.physics.halfExtents.divideScalar(2);
+
+ const rigidBodyDesc = mrjsUtils.physics.RAPIER.RigidBodyDesc.fixed()
+ entity.physics.body = this.app.physicsWorld.createRigidBody(rigidBodyDesc);
+
+ let colliderDesc = mrjsUtils.physics.RAPIER.ColliderDesc.cuboid(...entity.physics.halfExtents);
+ colliderDesc.setCollisionGroups(mrjsUtils.physics.CollisionGroups.UI);
+ entity.physics.collider = this.app.physicsWorld.createCollider(colliderDesc, entity.physics.body);
+ mrjsUtils.physics.COLLIDER_ENTITY_MAP[entity.physics.collider.handle] = entity;
+ entity.physics.collider.setActiveCollisionTypes(mrjsUtils.physics.RAPIER.ActiveCollisionTypes.DEFAULT | mrjsUtils.physics.RAPIER.ActiveCollisionTypes.KINEMATIC_FIXED);
+ entity.physics.collider.setActiveEvents(mrjsUtils.physics.RAPIER.ActiveEvents.COLLISION_EVENTS);
- entity.dispatchEvent(new MouseEvent('mouseleave'));
- };
+
+ }
/**
* @function
- * @description When a new entity is created, adds it to the physics registry and initializes the physics aspects of the entity.
- * @param {MREntity} entity - the entity being set up
+ * @description Initializes a Rigid Body detailed convexMesh collider for the entity
+ * NOTE: not currently in use until we can sync it with animations
+ * @param {MREntity} entity - the entity being updated
*/
- onNewEntity(entity) {
- this.initPhysicsBody(entity);
- this.registry.add(entity);
+ initDetailedBody(entity) {
+
+ const rigidBodyDesc = mrjsUtils.physics.RAPIER.RigidBodyDesc.fixed()
+ entity.physics.body = this.app.physicsWorld.createRigidBody(rigidBodyDesc);
+
+ entity.physics.colliders = []
+
+ entity.object3D.traverse((child) => {
+ if(child.isMesh) {
+ let collider = this.app.physicsWorld.createCollider(this.initConvexMeshCollider(child, entity.compStyle.scale), entity.physics.body)
+ collider.setCollisionGroups(mrjsUtils.physics.CollisionGroups.UI);
+ entity.physics.colliders.push(collider)
+ mrjsUtils.physics.COLLIDER_ENTITY_MAP[collider.handle] = entity;
+ collider.setActiveCollisionTypes(mrjsUtils.physics.RAPIER.ActiveCollisionTypes.DEFAULT | mrjsUtils.physics.RAPIER.ActiveCollisionTypes.KINEMATIC_FIXED);
+ collider.setActiveEvents(mrjsUtils.physics.RAPIER.ActiveEvents.COLLISION_EVENTS);
+
+ }
+ })
+
}
- /**
+ /**
* @function
- * @description Initializes the rigid body used by the physics part of the entity
+ * @description Initializes a convexMesh collider from a THREE.js geometry
+ * NOTE: not currently in use until we can sync it with animations
* @param {MREntity} entity - the entity being updated
*/
- initPhysicsBody(entity) {
- if (entity.physics.type == 'none') {
- return;
+ initConvexMeshCollider(object3D, scale) {
+ const positionAttribute = object3D.geometry.getAttribute('position');
+ const vertices = [];
+ for (let i = 0; i < positionAttribute.count; i++) {
+ const vertex = new THREE.Vector3().fromBufferAttribute(positionAttribute, i).multiplyScalar(scale).multiplyScalar(mrjsUtils.app.scale);
+ vertices.push([vertex.x, vertex.y, vertex.z]); | it's better to use threejs's `toArray` function here instead of [vertex.x, vertex.y, vertex.z] |
mrjs | github_2023 | javascript | 382 | Volumetrics-io | hanbollar | @@ -290,49 +219,65 @@ export class PhysicsSystem extends MRSystem {
* @param {MREntity} entity - the entity being updated
*/
updateBody(entity) {
- if (entity.physics.type == 'none') {
+ if (!entity.physics.body) {
return;
}
- entity.object3D.getWorldPosition(this.tempWorldPosition);
+
+ if(entity.compStyle.visibility == 'hidden' && entity.physics.body.isEnabled()) {
+ entity.physics.body.setEnabled(false)
+ } else if (!entity.physics.body.isEnabled()) {
+ entity.physics.body.setEnabled(false)
+ }
+
+ if (entity instanceof MRPanel) {
+ entity.panel.getWorldPosition(this.tempWorldPosition);
+ } else {
+ entity.object3D.getWorldPosition(this.tempWorldPosition);
+ }
entity.physics.body.setTranslation({ ...this.tempWorldPosition }, true);
entity.object3D.getWorldQuaternion(this.tempWorldQuaternion);
entity.physics.body.setRotation(this.tempWorldQuaternion, true);
- entity.updatePhysicsData();
- this.updateCollider(entity);
+ if(entity instanceof MRModel) {
+ this.updateSimpleBody(entity);
+ } else if (entity instanceof MRDivEntity) {
+ this.updateUIBody(entity);
+ } | this is the same commentary as before:
we have the open issue of MRModel possibly being moved to inherit from MRDivEntity instead of MREntity - make sure this reflects that or has a todo comment to warn for when we make that change |
mrjs | github_2023 | others | 378 | Volumetrics-io | hanbollar | @@ -1,18 +1,18 @@

-An extensible WebComponents library for the Spatial Web
+An extensible Web Components library for the Spatial Web | Components should be singular here (--> Component) |
mrjs | github_2023 | others | 378 | Volumetrics-io | hanbollar | @@ -50,24 +50,24 @@ npm run server
### Documentation:
-Check [docs.mrjs.io](https://docs.mrjs.io) for the full documentation or our [repository](https://github.com/Volumetrics-io/documentation).
+Check [docs.mrjs.io](https://docs.mrjs.io) for the full documentation, or our [repository](https://github.com/Volumetrics-io/documentation). | We should actually just change this to :
Check [docs.mrjs.io](https://docs.mrjs.io) or our [repository](https://github.com/Volumetrics-io/documentation) for the full documentation. |
mrjs | github_2023 | others | 378 | Volumetrics-io | hanbollar | @@ -169,9 +168,9 @@ customElements.get('mr-spacecraft') || customElements.define('mr-spacecraft', Sp
#### Systems
-A System contains logic that is applied to all entities that have a corresponding Component, using the data stored by the component. Unlike Entities & Components, Systems have no HTML representation and are implemented entirely in JS.
+A System contains logic that is applied to all entities that have a corresponding Component, using the data stored by the component. Unlike Entities & Components, Systems have no HTML representation and are implemented entirely in JavaScript.
-When a component is attached or detatched from an entity, it is added or removed from its System's registry of entities.
+When a component is attached or detached from an entity, it is added or removed from its System's registry of entities. | need to add a to after attached, so - `attached to` , since we have detached from |
mrjs | github_2023 | javascript | 369 | Volumetrics-io | hanbollar | @@ -226,12 +228,12 @@ export class MRApp extends MRElement {
// allows embedded mr-app to be independently scrollable
if (this.compStyle.overflow == 'scroll') {
- this.renderer.domElement.addEventListener('wheel', (event) => {
- // Assuming vertical scrolling
- this.scrollTop += event.deltaY;
- // Prevent the default scroll behavior of the front element
- event.preventDefault();
- });
+ // this.renderer.domElement.addEventListener('wheel', (event) => {
+ // // Assuming vertical scrolling
+ // this.scrollTop += event.deltaY;
+ // // Prevent the default scroll behavior of the front element
+ // event.preventDefault();
+ // }); | if this commented code isnt needed anymore - dont forget to remove ~ |
mrjs | github_2023 | javascript | 369 | Volumetrics-io | hanbollar | @@ -0,0 +1,83 @@
+import { MRSystem } from 'mrjs/core/MRSystem';
+import { MRPanel } from '../entities/MRPanel';
+
+
+/**
+ * @class PanelManagementSystem
+ * @classdesc A system that manages the screen relative position of UI panels
+ * @augments MRSystem
+ */
+export class PanelManagementSystem extends MRSystem { | `PanelManagementSystem` titling is misleading since we also have object managers as well as systems - renaming to something like `MultiPanelSystem` or `PanelSystem` makes more sense |
mrjs | github_2023 | javascript | 369 | Volumetrics-io | hanbollar | @@ -0,0 +1,83 @@
+import { MRSystem } from 'mrjs/core/MRSystem';
+import { MRPanel } from '../entities/MRPanel'; | make sure your imports start from `mrjs/core/...` so `mrjs/core/entities/MRPanel` |
mrjs | github_2023 | javascript | 369 | Volumetrics-io | hanbollar | @@ -23,6 +23,7 @@ import { SkyBoxSystem } from 'mrjs/core/componentSystems/SkyBoxSystem';
import { StyleSystem } from 'mrjs/core/componentSystems/StyleSystem';
import { TextSystem } from 'mrjs/core/componentSystems/TextSystem';
import { AudioSystem } from './componentSystems/AudioSystem';
+import { PanelManagementSystem } from './componentSystems/PanelManagementSystem'; | make sure your imports start from `mrjs/core/...` |
mrjs | github_2023 | javascript | 369 | Volumetrics-io | hanbollar | @@ -13,28 +13,29 @@ import { mrjsUtils } from 'mrjs';
* @augments MRDivEntity
*/
export class MRPanel extends MRDivEntity {
- /**
- * @function
- * @description Calculates the height of the Entity. If in Mixed Reality, adjusts the value appropriately.
- * @returns {number} - the resolved height
- */
- get height() {
- if (mrjsUtils.xr.isPresenting) {
- return mrjsUtils.app.scale;
- }
- return global.viewPortHeight;
- }
+ // /**
+ // * @function
+ // * @description Calculates the height of the Entity. If in Mixed Reality, adjusts the value appropriately.
+ // * @returns {number} - the resolved height
+ // */
+ // get height() {
+ // if (mrjsUtils.xr.isPresenting) {
+ // return mrjsUtils.app.scale;
+ // }
+ // return global.viewPortHeight;
+ // } | if this commented code isnt needed anymore - make sure to remove |
mrjs | github_2023 | javascript | 356 | Volumetrics-io | michaelthatsit | @@ -147,7 +147,21 @@ export class MREntity extends MRElement {
* @function
* @description
*/
- updateStyle() {}
+ updateStyle() {
+ this.setVisibility();
+ }
+
+ setVisibility() { | On principle and scalability I'd prefer this be done in a system. if we start putting more logic into MREntity it'll balloon pretty quickly.
Can we try doing it in the StyleSystem? you could even take a crack at breaking StyleSystem in 2, with anything Geometry related in one and everything else (position, color, visibility, etc) in the other. |
mrjs | github_2023 | javascript | 337 | Volumetrics-io | michaelthatsit | @@ -0,0 +1,49 @@
+import { MRSystem } from 'mrjs/core/MRSystem';
+import { MRSkyBox } from 'mrjs/core/entities/MRSkyBox';
+
+/**
+ * @class SkyBoxSystem
+ * @classdesc Handles skybox interactions and updates for all items.
+ * @augments MRSystem
+ */
+export class SkyBoxSystem extends MRSystem {
+ /**
+ * @class
+ * @description StyleSystem's default constructor with a starting framerate of 1/30.
+ */
+ constructor() {
+ super(false);
+
+ // used as a helper because we cant grab the most recently added
+ // item from registry since it's a set.
+ this._lastItem = null;
+ }
+
+ /**
+ * @function
+ * @description The generic system update call.
+ * @param {number} deltaTime - given timestep to be used for any feature changes
+ * @param {object} frame - given frame information to be used for any feature changes
+ */
+ update(deltaTime, frame) {
+ // leave for when needed.
+ }
+
+ /**
+ * @function
+ * @description Called when a new entity is added to the scene. Adds said new entity to the style's system registry.
+ * @param {MREntity} entity - the entity being added.
+ */
+ onNewEntity(entity) {
+ if (entity instanceof MRSkyBox) {
+ if (entity.compStyle.scale == 'none') {
+ // has no css scale attribute then use as default otherwise use as the user-defined version.
+ const SCALING_OFFSET = 0.01;
+ console.log(this.registry);
+ entity.style.scale = (this.registry.size == 0) ? 1 : this._lastItem.style.scale + SCALING_OFFSET; | You're mixing up style.scale with object3D.scale here. it's causing some of the skyboxes to not show up in headset.
this should do it:
`entity.object3D.scale.setScalar((this.registry.size == 0) ? 1 : this._lastItem.object3D.scale.z + SCALING_OFFSET);`
also you can reduce your scaling offset even more. |
mrjs | github_2023 | javascript | 348 | Volumetrics-io | hanbollar | @@ -30,6 +30,13 @@ const mrjsUtils = {
Physics,
StringUtils,
xr,
+
+ get appScale() { | this should be a function within mr-app even if it is not object dependent - there should be a way to do a `static` function of the class in javascript for it |
mrjs | github_2023 | javascript | 311 | Volumetrics-io | michaelthatsit | @@ -81,7 +75,11 @@ export class TextSystem extends MRSystem {
* Relies on the parent's implementation. (see [MRSystem.needsSystemUpdate](https://docs.mrjs.io/javascript-api/#mrsystem.needssystemupdate) for default).
*/
set needsSystemUpdate(bool) {
- super.needsSystemUpdate = bool;
+ console.log('Updating a value that does not need updating. TextSystem`s `needsSystemUpdate` solely depends on registry size \
+ instead of a boolean. This is required s.t. we can monitor and properly update the system when the text content has changed \ | is this log necessary? |
mrjs | github_2023 | javascript | 309 | Volumetrics-io | hanbollar | @@ -65,6 +65,8 @@ export class MREntity extends MRElement {
this.touch = false;
this.grabbed = false;
this.focus = false;
+
+ this.ignoreStencil = true | question - this should make all entities ignored by masking, even div entities - meaning we're not masking at all anymore - is this needed in this pr?
if so - make sure to add `this.ignoreStencil = false` to all mrdiventity items (or at a basis, mrdiventity) |
mrjs | github_2023 | javascript | 236 | Volumetrics-io | michaelthatsit | @@ -14,13 +14,34 @@ export class StyleSystem extends MRSystem {
*/
constructor() {
super(false);
- this.cssUpdateNeeded = true;
+
+ // want this system to run based on the true/false trigger
+ this.needsSystemUpdate = true;
document.addEventListener('panel-mutated', () => {
- this.cssUpdateNeeded = true;
+ this.needsSystemUpdate = true;
});
}
+ /**
+ * @function
+ * @description Getter to checks if we need to run this system's update call. Overridden implementation returns true if there are any items in this
+ * systems registry that need to be run AND the default systemUpdateCheck is true
+ * (see [MRSystem.needsSystemUpdate](https://docs.mrjs.io/javascript-api/#mrsystem.needssystemupdate) for default).
+ * @returns {boolean} true if the system is in a state where this system is needed to update, false otherwise
+ */
+ get needsSystemUpdate() {
+ return this.registry.size > 0 && super.needsSystemUpdate; | this needs to be always true and we need to stick with checking `entity.needsStyleUpdate` due to some asynchronous loading of text and event driven styles such as hover and click. `needsSystemUpdate` blocks these. |
mrjs | github_2023 | javascript | 236 | Volumetrics-io | michaelthatsit | @@ -71,10 +93,13 @@ export class MRSystem {
* @param {number} deltaTime - given timestep to be used for any feature changes
* @param {object} frame - given frame information to be used for any feature changes
*/
- __update(deltaTime, frame) {
- if (!this.needsUpdate(deltaTime, frame)) {
+ _update(deltaTime, frame) {
+ console.log('inside MRSystem update function'); | remove log |
mrjs | github_2023 | javascript | 236 | Volumetrics-io | michaelthatsit | @@ -71,10 +93,13 @@ export class MRSystem {
* @param {number} deltaTime - given timestep to be used for any feature changes
* @param {object} frame - given frame information to be used for any feature changes
*/
- __update(deltaTime, frame) {
- if (!this.needsUpdate(deltaTime, frame)) {
+ _update(deltaTime, frame) {
+ console.log('inside MRSystem update function');
+ if (!this.needsSystemUpdate) {
+ console.log('not updating'); | remove log |
mrjs | github_2023 | javascript | 259 | Volumetrics-io | hanbollar | @@ -4,6 +4,7 @@ import { MRSystem } from 'mrjs/core/MRSystem';
import { MRDivEntity } from 'mrjs/core/MRDivEntity';
import { MREntity } from 'mrjs/core/MREntity';
import { MRPanel } from 'mrjs/core/entities/MRPanel';
+import { MRTextEntity } from '../MRTextEntity'; | change this to `import { MRTextEntity } from 'mrjs/core/MRTextEntity';` |
mrjs | github_2023 | javascript | 259 | Volumetrics-io | hanbollar | @@ -89,6 +89,7 @@ export class ClippingSystem extends MRSystem {
* @param {MREntity} entity - the entity to which we're adding the clipping planes information
*/
addClippingPlanes(entity) {
+ console.log(entity); | if this is for just-this-pr debugging dont forget to remove |
mrjs | github_2023 | javascript | 235 | Volumetrics-io | hanbollar | @@ -87,6 +88,11 @@ export class TextSystem extends MRSystem {
}
this.updateStyle(entity);
+ if (entity instanceof Button) { | just checking - is button the only current divEntity that needs a special case? or is it all div entities that can be within text |
mrjs | github_2023 | javascript | 235 | Volumetrics-io | hanbollar | @@ -0,0 +1,122 @@
+import { mrjsUtils } from 'mrjs';
+import { MRPlane } from '../../datatypes/MRPlane';
+
+/**
+ * @class MRPlaneManager
+ * @classdesc creates and manages the mr.js representation of XR planes.
+ * The resulting planes have RAPIER rigid bodies and THREE.js meshes that occlude virtual content by default
+ */
+export class MRPlaneManager {
+ /**
+ *
+ * @param scene
+ * @param physicsWorld
+ */
+ constructor(scene, physicsWorld) {
+ // TODO: add app level controls for:
+ // - planes
+ // - mesh
+
+ this.scene = scene;
+ this.physicsWorld = physicsWorld;
+
+ this.matrix = new THREE.Matrix4();
+
+ this.currentPlanes = new Map();
+
+ this.tempPosition = new THREE.Vector3();
+ this.tempQuaternion = new THREE.Quaternion();
+ this.tempScale = new THREE.Vector3();
+
+ this.tempDimensions = new THREE.Vector3();
+
+ document.addEventListener('exitXR', () => {
+ for (const [plane, mrplane] of this.currentPlanes) {
+ mrplane.mesh.geometry.dispose();
+ mrplane.mesh.material.dispose();
+ this.scene.remove(mrplane.mesh);
+
+ this.physicsWorld.removeRigidBody(mrplane.body);
+
+ this.currentPlanes.delete(plane);
+ }
+ });
+
+ mrjsUtils.xr.addEventListener('planesdetected', (event) => {
+ const planes = event.data;
+
+ mrjsUtils.xr.session.requestAnimationFrame((t, frame) => {
+ for (const plane of planes) {
+ if (this.currentPlanes.has(plane) === false) {
+ const pose = frame.getPose(plane.planeSpace, mrjsUtils.xr.referenceSpace);
+ this.matrix.fromArray(pose.transform.matrix);
+ this.matrix.decompose(this.tempPosition, this.tempQuaternion, this.tempScale);
+
+ const polygon = plane.polygon;
+
+ let minX = Number.MAX_SAFE_INTEGER;
+ let maxX = Number.MIN_SAFE_INTEGER;
+ let minZ = Number.MAX_SAFE_INTEGER;
+ let maxZ = Number.MIN_SAFE_INTEGER;
+
+ for (const point of polygon) {
+ minX = Math.min(minX, point.x);
+ maxX = Math.max(maxX, point.x);
+ minZ = Math.min(minZ, point.z);
+ maxZ = Math.max(maxZ, point.z);
+ }
+
+ const width = maxX - minX;
+ const height = maxZ - minZ;
+
+ let mrPlane = new MRPlane();
+
+ mrPlane.label = plane.semanticLabel;
+ mrPlane.orientation = plane.orientation;
+ mrPlane.dimensions.setX(width);
+ mrPlane.dimensions.setY(0.001);
+ mrPlane.dimensions.setX(height);
+
+ const geometry = new THREE.BoxGeometry(width, 0.01, height);
+ const material = new THREE.MeshBasicMaterial({ color: 0xffffff });
+
+ mrPlane.mesh = new THREE.Mesh(geometry, material);
+ mrPlane.mesh.position.setFromMatrixPosition(this.matrix);
+ mrPlane.mesh.quaternion.setFromRotationMatrix(this.matrix);
+ mrPlane.mesh.material.colorWrite = false;
+ mrPlane.mesh.renderOrder = 2;
+ this.scene.add(mrPlane.mesh);
+
+ this.tempDimensions.setX(width / 2);
+ this.tempDimensions.setY(0.01);
+ this.tempDimensions.setZ(height / 2);
+
+ mrPlane.body = this.initPhysicsBody(plane);
+
+ this.currentPlanes.set(plane, mrPlane);
+ }
+ }
+ });
+ });
+ }
+
+ /**
+ * @function
+ * @description initializes the physics body of an MR Plane
+ * @param plane
+ */
+ initPhysicsBody(plane) {
+ const rigidBodyDesc = mrjsUtils.Physics.RAPIER.RigidBodyDesc.kinematicPositionBased().setTranslation(...this.tempPosition);
+ let colliderDesc = mrjsUtils.Physics.RAPIER.ColliderDesc.cuboid(...this.tempDimensions);
+ console.log(mrjsUtils.Physics.CollisionGroups.PLANES); | is this console.log still needed? |
mrjs | github_2023 | javascript | 235 | Volumetrics-io | hanbollar | @@ -0,0 +1,8 @@
+/**
+ * @namespace xr
+ * @description Useful namespace for helping with xr utility functions.
+ * this is set within the MRApp to access various WebXR API features
+ */
+let xr = {}; | Can we use `XR` instead of `xr` ? |
mrjs | github_2023 | javascript | 235 | Volumetrics-io | hanbollar | @@ -60,7 +61,7 @@ export class SkyBox extends MREntity {
textureNames.map((name) => (path ? path + name : name)),
this.onTextureLoaded.bind(this) // Ensuring the correct context
);
- const geometry = new THREE.SphereGeometry(1000, 32, 16);
+ const geometry = new THREE.SphereGeometry(900, 32, 16); | just curious on the change to 900, was it a render issue? |
mrjs | github_2023 | javascript | 235 | Volumetrics-io | hanbollar | @@ -0,0 +1,122 @@
+import { mrjsUtils } from 'mrjs';
+import { MRPlane } from '../../datatypes/MRPlane';
+
+/**
+ * @class MRPlaneManager
+ * @classdesc creates and manages the mr.js representation of XR planes.
+ * The resulting planes have RAPIER rigid bodies and THREE.js meshes that occlude virtual content by default
+ */
+export class MRPlaneManager { | if this is a manager and not a system we need to figure somewhere else for this to go
i'd prefer we default it back to keeping inline with the ECS setup we're going for: just change this into a System and just have an empty update function (like how the `MaskingSystem` is setup) |
mrjs | github_2023 | javascript | 144 | Volumetrics-io | michaelthatsit | @@ -0,0 +1,116 @@
+/**
+ *
+ */
+class InstancingSystem extends System {
+ // System that allows for instancing of meshes based on a given
+ // entity where the instances can be modified separately.
+
+ /**
+ *
+ */
+ constructor() {
+ super();
+
+ this.instanceCount = 5;
+ this.transformations = [];
+ this.instancedMesh = null;
+ }
+
+ /**
+ *
+ * @param deltaTime
+ * @param frame
+ */
+ update(deltaTime, frame) {
+ for (const entity of this.registry) {
+ switch (entity.components.get('instancing')?.type) {
+ case 'random':
+ this.random(entity);
+ break;
+
+ default:
+ break;
+ }
+ }
+ }
+
+ /**
+ *
+ * @param entity
+ */
+ attachedComponent(entity) {
+ // ----- setup for instanced geometry -----
+
+ let originalMesh = entity.object3D;
+ let combinedGeometry = new THREE.BufferGeometry();
+
+ // grab usable mesh
+ if (originalMesh instanceof THREE.Mesh) {
+ combinedGeometry = originalMesh.geometry.clone();
+ } else if (originalMesh instanceof THREE.Group) {
+ originalMesh.traverse((child) => {
+ if (child instanceof THREE.Mesh) {
+ const geometry = child.geometry.clone();
+ geometry.applyMatrix4(child.matrixWorld); // Apply the child's world matrix
+ combinedGeometry.merge(geometry); | Is there a difference between `.merge` and [mergeGeometries](https://threejs.org/docs/#examples/en/utils/BufferGeometryUtils.mergeGeometries)? |
mrjs | github_2023 | javascript | 153 | Volumetrics-io | michaelthatsit | @@ -0,0 +1,32 @@
+class SkyBox extends Entity {
+ constructor() {
+ super();
+ }
+
+ /**
+ *
+ */
+ connected() {
+ // you can have texturesList be all individual textures
+ // or you can store them in a specified path and just
+ // load them up solely by filename in that path.
+
+ this.texturesList = this.getAttribute('textures'); | @hanbollar what do we thing about using `src` instead of textures? We could also use the 'background' css property which would be sick. |
mrjs | github_2023 | javascript | 153 | Volumetrics-io | michaelthatsit | @@ -11,20 +11,21 @@ class SkyBox extends Entity {
// or you can store them in a specified path and just
// load them up solely by filename in that path.
- this.texturesList = this.getAttribute('textures');
+ this.texturesList = this.getAttribute('src');
if (!this.texturesList) {
return;
}
const textureLoader = THREE.CubeTextureLoader();
const textureNames = texturesList.split(',');
- let texture = null;
let path = this.getAttribute('pathToTextures');
const texture = !path ? textureLoader.load(textureNames) : textureLoader.load(textureNames.map((name) => path + name));
// scene.background
this.object3D.background = texture;
+ // css background
+ this.compStyle.background = texture; | ah so you wouldn't set compStyle.background really ever. that's done with css. Rather I'd expect you'd use `this.compStyle.background` as an alternative to `src`.
something like:
```
this.texturesList = this.compStyle.backgroundImages
...
const textureNames = texturesList.split([some regex to parse list of paths]);
```
the difference between `src` and `background-image` would be the list of paths. each path in background-image is wrapped with `url("...")` so you'd need to do some regex.
`background-image: url("img_tree.gif"), url("paper.gif");` |
mrjs | github_2023 | javascript | 177 | Volumetrics-io | hanbollar | @@ -59,6 +59,35 @@ export class MRUIEntity extends Entity {
this.windowHorizontalScale = 1;
}
+ /**
+ *
+ * @param entity
+ */
+ add(entity) {
+ let container = this.closest('mr-panel');
+
+ if (container && entity instanceof MRUIEntity) {
+ container.add(entity);
+ } else {
+ this.object3D.add(entity.object3D);
+ }
+
+ entity.object3D.position.z += 0.0001; | needs comment above this line for why this bump is necessary |
mrjs | github_2023 | javascript | 177 | Volumetrics-io | hanbollar | @@ -36,6 +36,8 @@ export class MRImage extends MRUIEntity {
}
});
this.object3D.material.map = this.texture;
+
+ this.object3D.position.z += 0.00001; | needs comment above this line for why this bump is necessary |
mrjs | github_2023 | javascript | 177 | Volumetrics-io | hanbollar | @@ -63,15 +63,18 @@ export class TextSystem extends System {
entity.blur();
}
} else {
- text = entity.textContent.replace(/(\n)\s+/g, '$1').trim();
+ text = entity.textContent
+ .replace(/(\n)\s+/g, '$1')
+ .replace(/(\r\n|\n|\r)/gm, '')
+ .trim(); | need comment above this explaining why this swap is needed and safe |
mrjs | github_2023 | javascript | 177 | Volumetrics-io | hanbollar | @@ -49,8 +50,9 @@ export default class Entity extends MRElement {
*
*/
get height() {
- const styleHeight = this.compStyle.height.split('px')[0] > 0 ? this.compStyle.height.split('px')[0] : window.innerHeight;
- return (styleHeight / window.innerHeight) * global.viewPortHeight;
+ const rect = this.getBoundingClientRect();
+ // const styleHeight = this.compStyle.height.split('px')[0] > 0 ? this.compStyle.height.split('px')[0] : window.innerHeight; | can this line be deleted? |
mrjs | github_2023 | javascript | 177 | Volumetrics-io | hanbollar | @@ -15,9 +15,9 @@ export class Model extends Entity {
/**
*
*/
- get height() {
- return this.contentHeight;
- }
+ // get height() {
+ // return this.contentHeight;
+ // } | can the above be deleted? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.