Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add XR Tool for Galacean Editor #291

Merged
merged 2 commits into from
Jul 23, 2024

Conversation

cptbtptpbcptdtptp
Copy link
Contributor

@cptbtptpbcptdtptp cptbtptpbcptdtptp commented Jul 23, 2024

Please check if the PR fulfills these requirements

  • The commit message follows our guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)

What kind of change does this PR introduce? (Bug fix, feature, docs update, ...)

What is the current behavior? (You can also link to an open issue here)

What is the new behavior (if this is a feature change)?

Does this PR introduce a breaking change? (What changes might users need to make in their application due to this PR?)

Other information:

Summary by CodeRabbit

  • New Features

    • Introduced a comprehensive README.md for the XR package, detailing installation, usage examples, and package purpose.
    • Added @galacean/engine-toolkit-xr package with essential metadata for integration within the Galacean engine ecosystem.
    • Implemented TrackedComponent, XROrigin, XRAnchorManager, XRImageManager, and XRPlaneManager classes for managing tracked objects and XR functionalities.
    • Created an entry point index.ts for exporting core XR components and managers.
  • Bug Fixes

    • Enhanced error handling and logging for unsupported XR features in the new managers.
  • Documentation

    • Included detailed documentation and usage examples in the new README.md file for users.
  • Chores

    • Set up TypeScript configuration for improved build processes and type-checking.
    • Updated Rollup configuration to support additional dependencies related to the XR package.

Copy link

coderabbitai bot commented Jul 23, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The recent updates to the @galacean/engine-toolkit-xr package enhance the Extended Reality (XR) capabilities of the Galacean engine with new classes and components. Key additions include TrackedComponent, XROrigin, and managers for anchors, images, and planes, which streamline the management of XR objects. Supporting documentation and configurations have also been established, improving the developer experience and facilitating integration within XR applications.

Changes

Files Change Summary
packages/xr/README.md Introduced a README.md detailing package purpose, installation, usage, and links to documentation.
packages/xr/package.json New package.json for @galacean/engine-toolkit-xr, including metadata, scripts, and peer dependencies.
packages/xr/src/component/* Introduced TrackedComponent and XROrigin classes for tracking objects and managing XR origins and camera settings.
packages/xr/src/index.ts New entry point consolidating exports of XR-related components and managers.
packages/xr/src/trackable/* Added XRAnchorManager, XRImageManager, and XRPlaneManager for managing XR anchors, images, and planes.
packages/xr/src/trackable/XRTrackedObjectManager.ts New class managing the lifecycle of tracked objects in XR.
packages/xr/tsconfig.json Introduced tsconfig.json for TypeScript configuration enhancing build and type-checking processes.
rollup.config.mjs Updated global mappings to include @galacean/engine-xr for Rollup configurations.
rollup.miniprogram.plugin.mjs Expanded registration capability to include @galacean/engine-xr in the plugin.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant XRManager
    participant TrackedObjectManager
    participant XRAnchorManager
    participant XRImageManager
    participant XRPlaneManager

    User->>XRManager: Initialize XR session
    XRManager->>TrackedObjectManager: Manage tracked objects
    TrackedObjectManager->>XRAnchorManager: Track anchors
    TrackedObjectManager->>XRImageManager: Track images
    TrackedObjectManager->>XRPlaneManager: Track planes
    XRManager->>User: XR session ready
Loading

🐇 In a world of XR delight,
New classes hop into sight!
Anchors, images, planes take flight,
With every change, our dreams ignite.
So let’s explore, let’s not delay,
In Galacean’s realm, let’s play! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@cptbtptpbcptdtptp cptbtptpbcptdtptp added the feature New feature label Jul 23, 2024
@@ -71,7 +71,8 @@ function makeRollupConfig(pkg) {
Object.assign({}, pkg.pkgJson.dependencies, pkg.pkgJson.peerDependencies, pkg.pkgJson.devDependencies)
);
let globals = {
"@galacean/engine": "Galacean"
"@galacean/engine": "Galacean",
"@galacean/engine-xr": "GalaceanXR"
Copy link
Collaborator

@gz65555 gz65555 Jul 23, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Galacean.XR,按照 PhysX 这类方式命名 Global name

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 11

Outside diff range, codebase verification and nitpick comments (2)
packages/xr/src/trackable/XRImageManager.ts (1)

10-10: Consider renaming the property for clarity.

The property trackingImages could be renamed to trackedImages for better clarity and consistency with the class name.

-  trackingImages: XRReferenceImage[] = [];
+  trackedImages: XRReferenceImage[] = [];
packages/xr/README.md (1)

11-13: Show command output.

According to Markdownlint, dollar signs should be used to show command output.

- $ npm install @galacean/engine-toolkit-xr
+ $ npm install @galacean/engine-toolkit-xr
+ # Output: ...
Tools
Markdownlint

12-12: null
Dollar signs used before commands without showing output

(MD014, commands-show-output)

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 38bcc92 and a9b0f22.

Files selected for processing (12)
  • packages/xr/README.md (1 hunks)
  • packages/xr/package.json (1 hunks)
  • packages/xr/src/component/TrackedComponent.ts (1 hunks)
  • packages/xr/src/component/XROrigin.ts (1 hunks)
  • packages/xr/src/index.ts (1 hunks)
  • packages/xr/src/trackable/XRAnchorManager.ts (1 hunks)
  • packages/xr/src/trackable/XRImageManager.ts (1 hunks)
  • packages/xr/src/trackable/XRPlaneManager.ts (1 hunks)
  • packages/xr/src/trackable/XRTrackedObjectManager.ts (1 hunks)
  • packages/xr/tsconfig.json (1 hunks)
  • rollup.config.mjs (1 hunks)
  • rollup.miniprogram.plugin.mjs (1 hunks)
Files skipped from review due to trivial changes (2)
  • packages/xr/src/index.ts
  • packages/xr/tsconfig.json
Additional context used
Markdownlint
packages/xr/README.md

12-12: null
Dollar signs used before commands without showing output

(MD014, commands-show-output)

Biome
packages/xr/src/component/XROrigin.ts

[error] 25-25: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 34-34: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 40-40: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

packages/xr/src/trackable/XRTrackedObjectManager.ts

[error] 59-59: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

Additional comments not posted (32)
packages/xr/src/trackable/XRImageManager.ts (2)

12-14: Constructor looks good.

The constructor correctly initializes the base class with the entity and XRImageTracking.


16-21: Ensure error handling covers all edge cases.

The _initXRFeature method correctly tries to add the XRImageTracking feature and logs an error if it fails. Ensure that all potential edge cases are covered in the error handling.

packages/xr/src/trackable/XRPlaneManager.ts (2)

12-14: Constructor looks good.

The constructor correctly initializes the base class with the entity and XRPlaneTracking.


16-21: Ensure error handling covers all edge cases.

The _initXRFeature method correctly tries to add the XRPlaneTracking feature and logs an error if it fails. Ensure that all potential edge cases are covered in the error handling.

Verification successful

Error handling in _initXRFeature methods is adequate.

The _initXRFeature methods in XRPlaneManager.ts, XRAnchorManager.ts, and XRImageManager.ts all use try-catch blocks to handle errors, ensuring that any exceptions thrown during the addition of features are logged appropriately. This approach covers potential edge cases effectively.

  • packages/xr/src/trackable/XRPlaneManager.ts
  • packages/xr/src/trackable/XRAnchorManager.ts
  • packages/xr/src/trackable/XRImageManager.ts
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all potential edge cases are covered in the error handling.

# Test: Search for the usage of `_initXRFeature` method. Expect: Proper error handling in all cases.
rg --type python -A 5 $'_initXRFeature'

Length of output: 69


Script:

#!/bin/bash
# Description: Verify that all potential edge cases are covered in the error handling.

# Test: Search for the usage of `_initXRFeature` method. Expect: Proper error handling in all cases.
rg --type ts -A 5 '_initXRFeature'

Length of output: 2584


Script:

#!/bin/bash
# Description: Verify that all potential edge cases are covered in the error handling.

# Test: Search for all instances of error handling within the _initXRFeature methods.
rg --type ts 'try {' -A 5

Length of output: 101


Script:

#!/bin/bash
# Description: Verify that all potential edge cases are covered in the error handling.

# Test: Search for all instances of error handling within the _initXRFeature methods.
rg --type ts 'try \{' -A 5

Length of output: 1429

packages/xr/src/component/TrackedComponent.ts (3)

19-21: Setter method looks good.

The setter method for _data correctly assigns the value.


30-32: Setter method looks good.

The setter method for _destroyedOnRemoval correctly assigns the value.


10-10: Consider providing a default value for _destroyedOnRemoval.

The _destroyedOnRemoval property is set to true by default. Consider providing a default value in the declaration itself.

-  private _destroyedOnRemoval = true;
+  private _destroyedOnRemoval: boolean = true;

Likely invalid or redundant comment.

packages/xr/package.json (6)

1-3: Ensure the package versioning strategy aligns with semantic versioning.

The version "1.3.0-beta.0" indicates a beta release. Ensure that this versioning strategy aligns with your overall release plan and semantic versioning.


4-7: Verify the publish configuration.

The publishConfig specifies public access and the npm registry. Ensure this is intended and aligns with your publishing strategy.


8-14: Review the repository and issue tracking URLs.

Ensure that the homepage, repository, and bugs URLs are correct and accessible.


15-18: Review the scripts for building and linting.

The b:types and lint:fix scripts are defined. Ensure these scripts are correct and sufficient for your build and linting processes.


19-26: Validate the entry points and included files.

The types, main, module, and files fields specify the entry points and included files. Ensure these paths are correct and align with your project structure.


27-30: Check peer dependencies compatibility.

The peerDependencies specify versions for @galacean/engine and @galacean/engine-xr. Ensure these versions are compatible with your project and other dependencies.

packages/xr/src/trackable/XRAnchorManager.ts (4)

1-3: Ensure all imported modules are necessary.

The imports include Entity, Logger, Quaternion, Vector3, XRAnchor, XRAnchorTracking, and XRTrackedObjectManager. Ensure all these imports are necessary for the functionality of the XRAnchorManager class.


8-10: Ensure proper initialization of class properties.

The anchors property is initialized as an empty array. Ensure this initialization aligns with the intended functionality.


12-14: Constructor looks good.

The constructor initializes the class with the entity and XRAnchorTracking. Ensure this initialization aligns with the intended functionality.


16-28: Ensure proper error handling in _initXRFeature method.

The _initXRFeature method sets up the XR feature and handles errors. Ensure the error handling is sufficient and consider logging additional context if necessary.

rollup.miniprogram.plugin.mjs (1)

45-45: Modification looks good.

The regStr constant is modified to include '@galacean/engine-xr'. Ensure this modification aligns with the intended functionality and does not introduce any unintended side effects.

packages/xr/README.md (4)

3-5: LGTM!

The feature description is clear and concise.


23-34: LGTM!

The usage example is clear and provides a good overview of how to use the tool.


36-40: LGTM!

The links are relevant and useful.


42-44: LGTM!

The license information is clear and provides a link to the MIT license.

packages/xr/src/component/XROrigin.ts (5)

8-9: LGTM!

The property mode is correctly defined and initialized.


10-11: LGTM!

The property origin is correctly defined.


12-13: LGTM!

The property camera is correctly defined.


14-15: LGTM!

The property leftCamera is correctly defined.


16-17: LGTM!

The property rightCamera is correctly defined.

rollup.config.mjs (3)

74-75: LGTM!

The addition of the @galacean/engine-xr package to the globals object is correct and aligns with the intention to support the package.


Line range hint 66-73:
LGTM!

The function makeRollupConfig is well-structured and correctly defines the configuration.

Also applies to: 76-103


Line range hint 105-105:
LGTM!

The default export is correctly defined.

packages/xr/src/trackable/XRTrackedObjectManager.ts (2)

42-47: Ensure xrManager is defined before accessing its properties.

The method onDisable assumes xrManager is defined. Add a check to avoid potential runtime errors.

-    const { xrManager } = this.engine;
-    if (!xrManager) return;
+    const { xrManager } = this.engine;
+    if (xrManager) {
+      xrManager.getFeature(this._feature)?.removeChangedListener(this._onTrackedChanged);
+      xrManager.sessionManager.removeStateChangedListener(this._onSessionChanged);
+    }

Likely invalid or redundant comment.


33-36: Ensure proper handling of undefined index.

The method getTrackedComponentByTrackId returns undefined if the index is not found. Ensure that the calling code handles this case properly.

Verification successful

Proper handling of undefined index verified.

The method getTrackedComponentByTrackId properly handles the undefined case by checking if trackedComponent is falsy (if (!trackedComponent)).

  • packages/xr/src/trackable/XRTrackedObjectManager.ts
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `getTrackedComponentByTrackId` handle the `undefined` case.

# Test: Search for the function usage. Expect: Proper handling of `undefined` return value.
rg --type typescript -A 5 $'getTrackedComponentByTrackId'

Length of output: 91


Script:

#!/bin/bash
# Description: Verify all function calls to `getTrackedComponentByTrackId` handle the `undefined` case.

# Test: Search for the function usage. Expect: Proper handling of `undefined` return value.
rg --type ts -A 5 $'getTrackedComponentByTrackId'

Length of output: 1315

*/
export class XRPlaneManager extends XRTrackedObjectManager<XRTrackedPlane> {
/** The plane detection mode. */
detectionMode: XRPlaneMode = XRPlaneMode.EveryThing;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider making the detection mode configurable.

The property detectionMode is set to XRPlaneMode.EveryThing by default. Consider making this configurable through the constructor or a setter method.

-  detectionMode: XRPlaneMode = XRPlaneMode.EveryThing;
+  detectionMode: XRPlaneMode;

+  constructor(entity: Entity, detectionMode: XRPlaneMode = XRPlaneMode.EveryThing) {
+    super(entity, XRPlaneTracking);
+    this.detectionMode = detectionMode;
+  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
detectionMode: XRPlaneMode = XRPlaneMode.EveryThing;
detectionMode: XRPlaneMode;
constructor(entity: Entity, detectionMode: XRPlaneMode = XRPlaneMode.EveryThing) {
super(entity, XRPlaneTracking);
this.detectionMode = detectionMode;
}

Comment on lines +21 to +26
constructor(entity: Entity, feature: any) {
super(entity);
this._feature = feature;
this._onTrackedChanged = this._onTrackedChanged.bind(this);
this._onSessionChanged = this._onSessionChanged.bind(this);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoid using any type for the feature parameter.

Using any defeats the purpose of TypeScript. Consider defining a specific type or a more generic type.

-  constructor(entity: Entity, feature: any) {
+  constructor(entity: Entity, feature: TFeatureConstructor<XRTrackableFeature>) {

Committable suggestion was skipped due to low confidence.

Comment on lines 49 to 51
protected _initXRFeature(): void {
throw new Error("You need to override this method.");
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider making _initXRFeature an abstract method.

The method _initXRFeature is meant to be overridden. Consider making it abstract to enforce this.

-  protected _initXRFeature(): void {
-    throw new Error("You need to override this method.");
+  protected abstract _initXRFeature(): void;
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
protected _initXRFeature(): void {
throw new Error("You need to override this method.");
}
protected abstract _initXRFeature(): void;

* If you set an Entity, the entity.Clone() will be used.
* otherwise, a new empty Entity will be used instead
*/
prefab: GLTFResource | PrefabResource | Entity;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure proper initialization of prefab.

The prefab property is not initialized in the constructor. Consider initializing it to a default value to avoid potential undefined issues.

-  prefab: GLTFResource | PrefabResource | Entity;
+  prefab: GLTFResource | PrefabResource | Entity = null;
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
prefab: GLTFResource | PrefabResource | Entity;
prefab: GLTFResource | PrefabResource | Entity = null;

Comment on lines +38 to +40
override onEnable(): void {
this.engine.xrManager?.sessionManager.addStateChangedListener(this._onSessionChanged);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure xrManager is defined.

The method onEnable assumes xrManager is defined. Add a check to avoid potential runtime errors.

-    this.engine.xrManager?.sessionManager.addStateChangedListener(this._onSessionChanged);
+    const { xrManager } = this.engine;
+    if (xrManager) {
+      xrManager.sessionManager.addStateChangedListener(this._onSessionChanged);
+    }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
override onEnable(): void {
this.engine.xrManager?.sessionManager.addStateChangedListener(this._onSessionChanged);
}
override onEnable(): void {
const { xrManager } = this.engine;
if (xrManager) {
xrManager.sessionManager.addStateChangedListener(this._onSessionChanged);
}
}

Comment on lines +117 to +137
private _createTrackedComponents(sessionRelativeData: T): TrackedComponent<T> {
const { origin } = this._engine.xrManager;
const { prefab } = this;
let entity: Entity;
if (!prefab) {
entity = origin.createChild("TrackedImage" + sessionRelativeData.id);
} else {
if (prefab instanceof GLTFResource) {
entity = prefab.instantiateSceneRoot();
} else if (prefab instanceof PrefabResource) {
entity = prefab.instantiate();
} else {
entity = prefab.clone();
}
entity.name = "TrackedImage" + sessionRelativeData.id;
origin.addChild(entity);
}

const trackedComponent = entity.addComponent(TrackedComponent<T>);
return trackedComponent;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optimize entity creation in _createTrackedComponents.

The method _createTrackedComponents can be optimized by reducing redundant code.

-    if (!prefab) {
-      entity = origin.createChild("TrackedImage" + sessionRelativeData.id);
-    } else {
-      if (prefab instanceof GLTFResource) {
-        entity = prefab.instantiateSceneRoot();
-      } else if (prefab instanceof PrefabResource) {
-        entity = prefab.instantiate();
-      } else {
-        entity = prefab.clone();
-      }
-      entity.name = "TrackedImage" + sessionRelativeData.id;
-      origin.addChild(entity);
-    }
+    entity = prefab ? 
+      (prefab instanceof GLTFResource ? prefab.instantiateSceneRoot() : 
+      (prefab instanceof PrefabResource ? prefab.instantiate() : prefab.clone())) : 
+      origin.createChild("TrackedImage" + sessionRelativeData.id);
+    entity.name = "TrackedImage" + sessionRelativeData.id;
+    origin.addChild(entity);
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private _createTrackedComponents(sessionRelativeData: T): TrackedComponent<T> {
const { origin } = this._engine.xrManager;
const { prefab } = this;
let entity: Entity;
if (!prefab) {
entity = origin.createChild("TrackedImage" + sessionRelativeData.id);
} else {
if (prefab instanceof GLTFResource) {
entity = prefab.instantiateSceneRoot();
} else if (prefab instanceof PrefabResource) {
entity = prefab.instantiate();
} else {
entity = prefab.clone();
}
entity.name = "TrackedImage" + sessionRelativeData.id;
origin.addChild(entity);
}
const trackedComponent = entity.addComponent(TrackedComponent<T>);
return trackedComponent;
}
private _createTrackedComponents(sessionRelativeData: T): TrackedComponent<T> {
const { origin } = this._engine.xrManager;
const { prefab } = this;
let entity: Entity;
entity = prefab ?
(prefab instanceof GLTFResource ? prefab.instantiateSceneRoot() :
(prefab instanceof PrefabResource ? prefab.instantiate() : prefab.clone())) :
origin.createChild("TrackedImage" + sessionRelativeData.id);
entity.name = "TrackedImage" + sessionRelativeData.id;
origin.addChild(entity);
const trackedComponent = entity.addComponent(TrackedComponent<T>);
return trackedComponent;
}

Comment on lines 53 to 69
private _onSessionChanged(state: XRSessionState): void {
switch (state) {
case XRSessionState.Initializing:
this._initXRFeature();
break;
case XRSessionState.Initialized:
const feature = this._engine.xrManager.getFeature(this._feature);
if (feature) {
feature.addChangedListener(this._onTrackedChanged);
} else {
Logger.error("XRTrackedObjectManager: Feature ", this._feature.name, " not found");
}
break;
default:
break;
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix scope of feature declaration in _onSessionChanged.

The feature variable is declared inside a switch case, which can lead to scope issues. Move the declaration outside the switch statement.

-    switch (state) {
+    let feature;
+    switch (state) {
-      case XRSessionState.Initialized:
-        const feature = this._engine.xrManager.getFeature(this._feature);
+      case XRSessionState.Initialized:
+        feature = this._engine.xrManager.getFeature(this._feature);
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private _onSessionChanged(state: XRSessionState): void {
switch (state) {
case XRSessionState.Initializing:
this._initXRFeature();
break;
case XRSessionState.Initialized:
const feature = this._engine.xrManager.getFeature(this._feature);
if (feature) {
feature.addChangedListener(this._onTrackedChanged);
} else {
Logger.error("XRTrackedObjectManager: Feature ", this._feature.name, " not found");
}
break;
default:
break;
}
}
private _onSessionChanged(state: XRSessionState): void {
let feature;
switch (state) {
case XRSessionState.Initializing:
this._initXRFeature();
break;
case XRSessionState.Initialized:
feature = this._engine.xrManager.getFeature(this._feature);
if (feature) {
feature.addChangedListener(this._onTrackedChanged);
} else {
Logger.error("XRTrackedObjectManager: Feature ", this._feature.name, " not found");
}
break;
default:
break;
}
}
Tools
Biome

[error] 59-59: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

Comment on lines +101 to +115
private _createOrUpdateTrackedComponents(sessionRelativeData: T): TrackedComponent<T> {
let trackedComponent = this.getTrackedComponentByTrackId(sessionRelativeData.id);
if (!trackedComponent) {
const { _trackIdToIndex: trackIdToIndex, _trackedComponents: trackedComponents } = this;
trackedComponent = this._createTrackedComponents(sessionRelativeData);
trackIdToIndex[sessionRelativeData.id] = trackedComponents.length;
trackedComponents.push(trackedComponent);
}
trackedComponent.data = sessionRelativeData;
const { transform } = trackedComponent.entity;
const { pose } = sessionRelativeData;
transform.position = pose.position;
transform.rotationQuaternion = pose.rotation;
return trackedComponent;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure sessionRelativeData has valid pose property.

The method _createOrUpdateTrackedComponents assumes sessionRelativeData has a valid pose property. Add checks to avoid potential runtime errors.

-    const { pose } = sessionRelativeData;
-    transform.position = pose.position;
-    transform.rotationQuaternion = pose.rotation;
+    if (sessionRelativeData.pose) {
+      const { pose } = sessionRelativeData;
+      transform.position = pose.position;
+      transform.rotationQuaternion = pose.rotation;
+    }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private _createOrUpdateTrackedComponents(sessionRelativeData: T): TrackedComponent<T> {
let trackedComponent = this.getTrackedComponentByTrackId(sessionRelativeData.id);
if (!trackedComponent) {
const { _trackIdToIndex: trackIdToIndex, _trackedComponents: trackedComponents } = this;
trackedComponent = this._createTrackedComponents(sessionRelativeData);
trackIdToIndex[sessionRelativeData.id] = trackedComponents.length;
trackedComponents.push(trackedComponent);
}
trackedComponent.data = sessionRelativeData;
const { transform } = trackedComponent.entity;
const { pose } = sessionRelativeData;
transform.position = pose.position;
transform.rotationQuaternion = pose.rotation;
return trackedComponent;
}
private _createOrUpdateTrackedComponents(sessionRelativeData: T): TrackedComponent<T> {
let trackedComponent = this.getTrackedComponentByTrackId(sessionRelativeData.id);
if (!trackedComponent) {
const { _trackIdToIndex: trackIdToIndex, _trackedComponents: trackedComponents } = this;
trackedComponent = this._createTrackedComponents(sessionRelativeData);
trackIdToIndex[sessionRelativeData.id] = trackedComponents.length;
trackedComponents.push(trackedComponent);
}
trackedComponent.data = sessionRelativeData;
const { transform } = trackedComponent.entity;
if (sessionRelativeData.pose) {
const { pose } = sessionRelativeData;
transform.position = pose.position;
transform.rotationQuaternion = pose.rotation;
}
return trackedComponent;
}

Comment on lines +9 to +21
private _data: T;
private _destroyedOnRemoval = true;

/**
* Tracking data of the TrackedObject.
*/
get data(): T {
return this._data;
}

set data(value: T) {
this._data = value;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider making _data property private.

The _data property is currently private but exposed through getter and setter methods. Consider making it truly private by using TypeScript's private modifier.

-  private _data: T;
+  #_data: T;
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private _data: T;
private _destroyedOnRemoval = true;
/**
* Tracking data of the TrackedObject.
*/
get data(): T {
return this._data;
}
set data(value: T) {
this._data = value;
}
#_data: T;
private _destroyedOnRemoval = true;
/**
* Tracking data of the TrackedObject.
*/
get data(): T {
return this.#_data;
}
set data(value: T) {
this.#_data = value;
}

Comment on lines +19 to +49
override onEnable(): void {
const { xrManager } = this.engine;
if (!xrManager) return;
switch (this.mode) {
case XRSessionMode.AR:
xrManager.origin = this.origin;
const camera = this.camera?.getComponent(Camera);
if (camera) {
xrManager.cameraManager.attachCamera(XRTrackedInputDevice.Camera, camera);
} else {
throw new Error("XROrigin: The Camera is not included on the Camera Entity");
}
break;
case XRSessionMode.VR:
xrManager.origin = this.origin;
const leftCamera = this.leftCamera?.getComponent(Camera);
if (leftCamera) {
xrManager.cameraManager.attachCamera(XRTrackedInputDevice.LeftCamera, leftCamera);
} else {
throw new Error("XROrigin: The Camera is not included on the Left Camera Entity");
}
const rightCamera = this.rightCamera?.getComponent(Camera);
if (rightCamera) {
xrManager.cameraManager.attachCamera(XRTrackedInputDevice.RightCamera, rightCamera);
} else {
throw new Error("XROrigin: The Camera is not included on the Right Camera Entity");
}
break;
default:
break;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wrap declarations in blocks to restrict access.

Static analysis tools suggest wrapping declarations in blocks to restrict access to the switch clauses.

-    switch (this.mode) {
-      case XRSessionMode.AR:
-        xrManager.origin = this.origin;
-        const camera = this.camera?.getComponent(Camera);
-        if (camera) {
-          xrManager.cameraManager.attachCamera(XRTrackedInputDevice.Camera, camera);
-        } else {
-          throw new Error("XROrigin: The Camera is not included on the Camera Entity");
-        }
-        break;
-      case XRSessionMode.VR:
-        xrManager.origin = this.origin;
-        const leftCamera = this.leftCamera?.getComponent(Camera);
-        if (leftCamera) {
-          xrManager.cameraManager.attachCamera(XRTrackedInputDevice.LeftCamera, leftCamera);
-        } else {
-          throw new Error("XROrigin: The Camera is not included on the Left Camera Entity");
-        }
-        const rightCamera = this.rightCamera?.getComponent(Camera);
-        if (rightCamera) {
-          xrManager.cameraManager.attachCamera(XRTrackedInputDevice.RightCamera, rightCamera);
-        } else {
-          throw new Error("XROrigin: The Camera is not included on the Right Camera Entity");
-        }
-        break;
-      default:
-        break;
-    }
+    switch (this.mode) {
+      case XRSessionMode.AR: {
+        xrManager.origin = this.origin;
+        const camera = this.camera?.getComponent(Camera);
+        if (camera) {
+          xrManager.cameraManager.attachCamera(XRTrackedInputDevice.Camera, camera);
+        } else {
+          throw new Error("XROrigin: The Camera is not included on the Camera Entity");
+        }
+        break;
+      }
+      case XRSessionMode.VR: {
+        xrManager.origin = this.origin;
+        const leftCamera = this.leftCamera?.getComponent(Camera);
+        if (leftCamera) {
+          xrManager.cameraManager.attachCamera(XRTrackedInputDevice.LeftCamera, leftCamera);
+        } else {
+          throw new Error("XROrigin: The Camera is not included on the Left Camera Entity");
+        }
+        const rightCamera = this.rightCamera?.getComponent(Camera);
+        if (rightCamera) {
+          xrManager.cameraManager.attachCamera(XRTrackedInputDevice.RightCamera, rightCamera);
+        } else {
+          throw new Error("XROrigin: The Camera is not included on the Right Camera Entity");
+        }
+        break;
+      }
+      default:
+        break;
+    }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
override onEnable(): void {
const { xrManager } = this.engine;
if (!xrManager) return;
switch (this.mode) {
case XRSessionMode.AR:
xrManager.origin = this.origin;
const camera = this.camera?.getComponent(Camera);
if (camera) {
xrManager.cameraManager.attachCamera(XRTrackedInputDevice.Camera, camera);
} else {
throw new Error("XROrigin: The Camera is not included on the Camera Entity");
}
break;
case XRSessionMode.VR:
xrManager.origin = this.origin;
const leftCamera = this.leftCamera?.getComponent(Camera);
if (leftCamera) {
xrManager.cameraManager.attachCamera(XRTrackedInputDevice.LeftCamera, leftCamera);
} else {
throw new Error("XROrigin: The Camera is not included on the Left Camera Entity");
}
const rightCamera = this.rightCamera?.getComponent(Camera);
if (rightCamera) {
xrManager.cameraManager.attachCamera(XRTrackedInputDevice.RightCamera, rightCamera);
} else {
throw new Error("XROrigin: The Camera is not included on the Right Camera Entity");
}
break;
default:
break;
}
override onEnable(): void {
const { xrManager } = this.engine;
if (!xrManager) return;
switch (this.mode) {
case XRSessionMode.AR: {
xrManager.origin = this.origin;
const camera = this.camera?.getComponent(Camera);
if (camera) {
xrManager.cameraManager.attachCamera(XRTrackedInputDevice.Camera, camera);
} else {
throw new Error("XROrigin: The Camera is not included on the Camera Entity");
}
break;
}
case XRSessionMode.VR: {
xrManager.origin = this.origin;
const leftCamera = this.leftCamera?.getComponent(Camera);
if (leftCamera) {
xrManager.cameraManager.attachCamera(XRTrackedInputDevice.LeftCamera, leftCamera);
} else {
throw new Error("XROrigin: The Camera is not included on the Left Camera Entity");
}
const rightCamera = this.rightCamera?.getComponent(Camera);
if (rightCamera) {
xrManager.cameraManager.attachCamera(XRTrackedInputDevice.RightCamera, rightCamera);
} else {
throw new Error("XROrigin: The Camera is not included on the Right Camera Entity");
}
break;
}
default:
break;
}
Tools
Biome

[error] 25-25: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 34-34: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 40-40: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

if (feature) {
feature.addChangedListener(this._onTrackedChanged);
} else {
Logger.error("XRTrackedObjectManager: Feature ", this._feature.name, " not found");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里直接把 异常 console 出来,用 console.warn 应该会好一点

@gz65555 gz65555 merged commit 3682198 into galacean:dev/1.3 Jul 23, 2024
1 check failed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature New feature
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

2 participants