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

Added a new 3D view page #927

Merged
merged 1 commit into from
Dec 31, 2024
Merged

Added a new 3D view page #927

merged 1 commit into from
Dec 31, 2024

Conversation

DTTerastar
Copy link
Collaborator

@DTTerastar DTTerastar commented Dec 29, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Added a new 3D view page to the application.
    • Introduced navigation to the 3D view route.
  • Dependencies

    • Added Three.js library for 3D graphics rendering.
    • Added TypeScript type definitions for Three.js.
  • Improvements

    • Updated Svelte version configuration.
    • Enhanced application with 3D visualization capabilities.

@DTTerastar DTTerastar temporarily deployed to CI - release environment December 29, 2024 22:03 — with GitHub Actions Inactive
Copy link

coderabbitai bot commented Dec 29, 2024

Warning

Rate limit exceeded

@DTTerastar has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 6 minutes and 7 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between f438e21 and 2bb9224.

⛔ Files ignored due to path filters (2)
  • src/ui/package-lock.json is excluded by !**/package-lock.json
  • src/ui/src/lib/images/cube.svg is excluded by !**/*.svg
📒 Files selected for processing (4)
  • .clinerules (1 hunks)
  • src/ui/package.json (2 hunks)
  • src/ui/src/routes/+layout.svelte (2 hunks)
  • src/ui/src/routes/3d/+page.svelte (1 hunks)
📝 Walkthrough

Walkthrough

The pull request introduces a new 3D view feature to the application, involving updates to the project configuration and routing. The changes include updating the Svelte version in the .clinerules file, adding Three.js dependencies to the package.json, modifying the layout to include a new 3D route, and creating a new +page.svelte component for rendering a 3D scene with interactive elements like room, node, and device management.

Changes

File Change Summary
.clinerules Updated Svelte version from 5 to 4
src/ui/package.json Added @types/three and three as dev dependencies (version ^0.171.0)
src/ui/src/routes/+layout.svelte Added new route for 3D view with /3d path and 3D icon
src/ui/src/routes/3d/+page.svelte New Svelte component implementing a Three.js 3D scene with rendering, controls, and dynamic scene management

Sequence Diagram

sequenceDiagram
    participant User
    participant Layout
    participant 3DPage
    participant ThreeJS
    
    User->>Layout: Navigate to 3D View
    Layout->>3DPage: Load 3D Component
    3DPage->>ThreeJS: Initialize Scene
    3DPage->>ThreeJS: Setup Renderers
    3DPage->>ThreeJS: Configure Camera
    3DPage->>ThreeJS: Setup OrbitControls
    3DPage->>ThreeJS: Animate Scene
    ThreeJS-->>3DPage: Render 3D Content
Loading

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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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 using 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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.

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: 0

🧹 Nitpick comments (6)
src/ui/src/lib/3d/Devices.svelte (2)

47-49: Consider throttling or debouncing store updates for large device sets
Repeatedly calling updateDevices($devices) on every store change might be expensive if the $devices array is very large or changes very frequently. Consider throttling or debouncing updates to prevent potential performance bottlenecks.


127-136: Pulse animation overhead
The pulsing effect recalculates scale on every animation frame. For many devices, this may cause overhead. If performance becomes critical at scale, consider a shader-based approach or a single global time uniform, so that you only adjust transformations once, rather than individually per sphere.

src/ui/src/routes/3d/+page.svelte (2)

26-35: GUI refreshNodes usage
The refreshNodes function hides and immediately shows nodes to force data refresh. While effective, it might cause brief flicker. Consider an in-place data refresh sequence for a smoother user experience if the underlying store supports it.


107-120: Commented-out GUI control
The commented-out lines for showNodes in the GUI might be intentional. If you plan to provide a toggle in the future, leaving the code commented-out is understandable. Otherwise, removing or refactoring it for clarity would clean up the code.

src/ui/src/lib/3d/Rooms.svelte (1)

44-87: Possibility of large floor data
If $config.floors or room.points grow significantly, consider more efficient geometry representations or simplified line rendering to maintain performance.

src/ui/src/lib/3d/Nodes.svelte (1)

78-115: Label creation
The code creates a CSS2DObject for each node. If you anticipate a high volume of nodes, evaluate the performance of generating many labels. Potentially, you can group or batch labels to reduce overhead.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7497073 and d7cc99c.

⛔ Files ignored due to path filters (2)
  • src/ui/package-lock.json is excluded by !**/package-lock.json
  • src/ui/src/lib/images/3d.svg is excluded by !**/*.svg
📒 Files selected for processing (7)
  • .clinerules (1 hunks)
  • src/ui/package.json (2 hunks)
  • src/ui/src/lib/3d/Devices.svelte (1 hunks)
  • src/ui/src/lib/3d/Nodes.svelte (1 hunks)
  • src/ui/src/lib/3d/Rooms.svelte (1 hunks)
  • src/ui/src/routes/+layout.svelte (2 hunks)
  • src/ui/src/routes/3d/+page.svelte (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .clinerules
🔇 Additional comments (11)
src/ui/src/lib/3d/Devices.svelte (3)

51-74: Good resource cleanup approach
The cleanupDeviceGroup() function correctly disposes geometries and materials, and removes CSS2D labels from the DOM. This is essential for preventing memory leaks or keeping unused DOM nodes around.


79-125: Validate device filtering logic
By checking if (confidence <= 1) return;, devices with confidence <= 1 are skipped. Ensure this is desired if you have devices that might report exactly 1 or less in certain edge cases. Otherwise, you risk missing devices that may need simple placeholders in the 3D scene.


138-143: Exported update function is flexible but watch for potential side effects
Calling update() externally is a convenient way to animate device pulses. In future expansions, ensure that additional side effects (like store writes or large computations) are carefully handled to avoid blocking the render loop.

src/ui/src/routes/3d/+page.svelte (1)

125-148: Proper resource disposal on unmount
Setting isAnimating = false, removing resize listeners, and disposing the WebGL context help avoid memory/resource leaks. Great job ensuring the 3D renderer is properly tidied up when this component is destroyed.

src/ui/src/routes/+layout.svelte (2)

15-15: 3D icon import
Importing threeD under $lib/images/3d.svg is consistent with existing icon imports. No issues found.


29-29: Navigation improvement
Adding a route for /3d introduces an easy way to navigate to the 3D scene. Confirm that you have appropriate SEO, if relevant, or meta tags for the new route.

src/ui/src/lib/3d/Rooms.svelte (1)

29-42: Good cleanup logic
Similar to other components, cleanupRooms() ensures geometries and materials are disposed of properly. This is a recommended approach in Three.js setups as it helps prevent memory leaks.

src/ui/src/lib/3d/Nodes.svelte (2)

35-37: Reactivity and conditional checks
$: if ($nodes && groupPivot && enabled) { ... } triggers updates whenever $nodes, groupPivot, or enabled changes. Ensure these changes won’t cause unnecessary group rebuilds if the node data is only changing partially.


43-64: Nodes disposal
The cleanupNodeGroup() function comprehensively frees geometry, materials, and CSS2DObjects, which is a best practice to maintain GPU and DOM hygiene.

src/ui/package.json (2)

27-27: LGTM! Three.js dependencies are properly configured.

The Three.js library and its TypeScript types are correctly added as devDependencies with matching versions. This setup is appropriate for a Vite + SvelteKit project.

Also applies to: 45-45


27-27: Verify Three.js version security status

Let's check for any known vulnerabilities in Three.js v0.171.0.

Also applies to: 45-45

✅ Verification successful

Three.js version 0.171.0 is secure with no known vulnerabilities

The version check reveals that Three.js v0.171.0 is actually the latest available version, and there are no known security vulnerabilities affecting this version. The two previously reported vulnerabilities were:

  • A high-severity DoS vulnerability affecting versions < 0.125.0 (patched in March 2021)
  • A high-severity XSS vulnerability affecting versions < 0.137.0 (patched in January 2022)

Both vulnerabilities were patched in much earlier versions, making v0.171.0 safe to use.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for security advisories for Three.js

# Check npm for latest versions and any security advisories
curl -s "https://registry.npmjs.org/three" | jq '.versions | keys_unsorted[-5:]'

# Check for GitHub security advisories
gh api graphql -f query='
{
  securityVulnerabilities(first: 5, ecosystem: NPM, package: "three") {
    nodes {
      advisory {
        summary
        severity
        publishedAt
      }
      vulnerableVersionRange
      firstPatchedVersion {
        identifier
      }
    }
  }
}'

Length of output: 878

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: 2

🧹 Nitpick comments (8)
src/ui/src/routes/3d/+page.svelte (8)

1-10: Consider lazy-loading Three.js.
Imports from three/examples/jsm can significantly increase bundle size. You might consider dynamically importing them or using a code-splitting strategy to optimize performance when the 3D feature is not immediately required.


54-69: Validate room visuals for large floor plans.
If users configure large or complex floor plans, the approach of drawing many lines and shapes might become expensive. Consider instancing or merging geometry for performance gains.


70-89: Use visible = false instead of removing node groups.
Currently, toggling showNodes triggers destroying and re-creating node objects. You may reduce overhead by simply toggling nodeGroup.visible, preserving state and preventing repeated geometry allocations.


331-361: Synchronize node states in real-time.
When a node goes from offline to online, or its location changes, you may want dynamic updates, rather than recreating the entire group. Tracking changes at the node level could improve performance and user experience.


389-437: Cycle device materials with caution.
Using modulo on trackerMaterials works for color cycling, but confirm this is your intended design when the number of tracked devices is large. You could create more diverse materials or unify color logic with device states.


449-473: Pause animation when tab is inactive.
Continuous requestAnimationFrame() calls can be CPU-intensive. Consider using the Page Visibility API or a Svelte-friendly approach to halt rendering loops when the page is in the background.


475-483: Hide or remove the debug GUI in production.
The GUI is helpful for debugging but may not be desired in a release build. Provide a way to conditionally compile or remove it for end users.


485-521: Dispose of label renderer if supported.
CSS2DRenderer may not have a .dispose() method, but if it does in future versions or if memory usage becomes an issue, consider removing any references to the label renderer to avoid potential leaks.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d7cc99c and 5497ede.

⛔ Files ignored due to path filters (2)
  • src/ui/package-lock.json is excluded by !**/package-lock.json
  • src/ui/src/lib/images/3d.svg is excluded by !**/*.svg
📒 Files selected for processing (4)
  • .clinerules (1 hunks)
  • src/ui/package.json (2 hunks)
  • src/ui/src/routes/+layout.svelte (2 hunks)
  • src/ui/src/routes/3d/+page.svelte (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • .clinerules
  • src/ui/package.json
  • src/ui/src/routes/+layout.svelte
🔇 Additional comments (4)
src/ui/src/routes/3d/+page.svelte (4)

11-20: Check initial startTime type usage.
startTime is declared as number, but it can remain undefined until set. You might want to initialize it to 0 or use a union type like number | undefined for clarity.


30-53: Ensure tracker materials are properly disposed.
Although you invoke cleanupDeviceGroup(), confirm that no references to these materials persist elsewhere, to avoid memory leaks.


177-183: Guard against empty rooms array.
calculateRoomCenter() divides by points.length. If points is empty, an error or NaN might occur. Consider validating or returning early if the array is empty.


254-262: Confirm store reactivity handles unsubscribes.
Reactivity with $: is convenient, but ensure there are no lingering subscriptions to $nodes or $config once the component unmounts. Typically, Svelte handles these automatically, but a thorough check is still warranted.

src/ui/src/routes/3d/+page.svelte Show resolved Hide resolved
src/ui/src/routes/3d/+page.svelte Show resolved Hide resolved
@DTTerastar DTTerastar temporarily deployed to CI - release environment December 30, 2024 23:55 — with GitHub Actions Inactive
@DTTerastar DTTerastar changed the title WIP Added a new 3D view page Dec 30, 2024
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: 2

♻️ Duplicate comments (2)
src/ui/src/routes/3d/+page.svelte (2)

107-172: 🛠️ Refactor suggestion

Break down scene initialization for better maintainability.

Additionally, add WebGL context loss handling for better reliability.

+function handleContextLost(event: WebGLContextEvent) {
+    event.preventDefault();
+    isAnimating = false;
+    // Notify user about context loss
+    console.warn('WebGL context lost. Try refreshing the page.');
+}
+
+function handleContextRestored() {
+    // Reinitialize scene
+    initScene();
+    isAnimating = true;
+    requestAnimationFrame(animate);
+}
+
 function initScene() {
     // ... existing code ...
+    
+    renderer.domElement.addEventListener('webglcontextlost', handleContextLost, false);
+    renderer.domElement.addEventListener('webglcontextrestored', handleContextRestored, false);
 }

199-249: 🛠️ Refactor suggestion

Add error boundaries and validation.

Additionally, implement error boundaries to prevent crashes from geometry creation failures.

 function setupRooms() {
     $: if ($config?.floors && groupPivot) {
         cleanupRooms();
+        try {
             const newRoomGroup = new THREE.Group();
             // ... existing code ...
+        } catch (error) {
+            console.error('Failed to setup rooms:', error);
+            // Fallback to empty room group
+            const fallbackGroup = new THREE.Group();
+            fallbackGroup.name = 'RoomGroup';
+            groupPivot.add(fallbackGroup);
+            roomGroup = fallbackGroup;
+        }
     }
 }
🧹 Nitpick comments (4)
src/ui/src/routes/3d/+page.svelte (4)

30-49: Consider lazy initialization of materials.

The materials are initialized at module level, which consumes memory even if the component is not mounted. Consider moving the material initialization to initScene() or creating a dedicated materials manager.

-const trackerMaterials = [
-    new THREE.MeshStandardMaterial({
-        emissive: 0xff0000,
-        emissiveIntensity: 2,
-        transparent: true,
-        opacity: 0.8
-    }),
-    // ... other materials
-];
+let trackerMaterials: THREE.Material[] = [];
+
+function initMaterials() {
+    trackerMaterials = [
+        new THREE.MeshStandardMaterial({
+            emissive: 0xff0000,
+            emissiveIntensity: 2,
+            transparent: true,
+            opacity: 0.8
+        }),
+        // ... other materials
+    ];
+}

21-24: Document the purpose of constants.

Add JSDoc comments to explain the purpose and units of measurement for position adjustments and pulse animation constants.

+/** Adjustment factor for x-axis positioning (in meters) */
 const X_POS_ADJ = 1.5;
+/** Adjustment factor for y-axis positioning (in meters) */
 const Y_POS_ADJ = 5;

+/** Speed of the pulse animation (cycles per second) */
 const PULSE_SPEED = 2;
+/** Minimum scale factor for pulse animation */
 const PULSE_MIN = 0.8;
+/** Maximum scale factor for pulse animation */
 const PULSE_MAX = 1.2;

Also applies to: 26-28


446-470: Add performance monitoring and frame timing optimization.

The animation loop could benefit from performance monitoring and frame timing optimization.

+let frameCount = 0;
+const FPS_INTERVAL = 60; // Check FPS every 60 frames
+let lastFpsTime = performance.now();

 function animate(currentTime: number) {
     if (!isAnimating) return;

+    // Monitor performance
+    frameCount++;
+    if (frameCount % FPS_INTERVAL === 0) {
+        const currentFps = Math.round(1000 * FPS_INTERVAL / (currentTime - lastFpsTime));
+        if (currentFps < 30) {
+            console.warn(`Low FPS detected: ${currentFps}`);
+        }
+        lastFpsTime = currentTime;
+    }

     // ... rest of the code ...

+    // Use optimal timing for next frame
+    if (document.hidden) {
+        setTimeout(() => requestAnimationFrame(animate), 1000 / 30);
+    } else {
         requestAnimationFrame(animate);
+    }
 }

472-482: Enhance GUI controls for better user experience.

Consider adding more controls for user customization and scene management.

 function doGuiSetup() {
     const gui = new GUI({ title: 'Settings' });

+    // Animation folder
+    const animationFolder = gui.addFolder('Animation');
     gui.add(effectController, 'zRotationSpeed', 0, 1, 0.01)
         .onChange((value: number) => {
             zRotationSpeed = value;
         });
+    
+    // Visibility folder
+    const visibilityFolder = gui.addFolder('Visibility');
+    visibilityFolder.add(effectController, 'showNodes')
+        .name('Show Nodes')
+        .onChange((value: boolean) => {
+            showNodes = value;
+        });
+    
+    // Camera folder
+    const cameraFolder = gui.addFolder('Camera');
+    cameraFolder.add(controls, 'autoRotate');
+    cameraFolder.add(controls, 'autoRotateSpeed', 0, 5, 0.1);

     gui.close();
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5497ede and f438e21.

⛔ Files ignored due to path filters (1)
  • src/ui/src/lib/images/cube.svg is excluded by !**/*.svg
📒 Files selected for processing (2)
  • src/ui/src/routes/+layout.svelte (2 hunks)
  • src/ui/src/routes/3d/+page.svelte (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/ui/src/routes/+layout.svelte

src/ui/src/routes/3d/+page.svelte Show resolved Hide resolved
src/ui/src/routes/3d/+page.svelte Show resolved Hide resolved
@DTTerastar DTTerastar temporarily deployed to CI - release environment December 30, 2024 23:59 — with GitHub Actions Inactive
@DTTerastar DTTerastar enabled auto-merge (squash) December 31, 2024 00:00
@DTTerastar DTTerastar merged commit ed4ff3b into main Dec 31, 2024
4 checks passed
@DTTerastar DTTerastar deleted the 3d branch December 31, 2024 00:01
DTTerastar added a commit that referenced this pull request Dec 31, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant