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

new three js #1153

Merged
merged 207 commits into from
Aug 6, 2024
Merged

new three js #1153

merged 207 commits into from
Aug 6, 2024

Conversation

aymericdelab
Copy link
Collaborator

@aymericdelab aymericdelab commented Aug 6, 2024

PR Type

Enhancement, Tests, Bug fix


Description

  • Introduced WorldmapScene and HexceptionScene classes extending HexagonScene for managing world map and hexception scenes.
  • Added ArmyMovementManager and ArmyManager classes for managing army movements and interactions.
  • Refactored useUIStore to include new slices for three.js state management.
  • Added GameRenderer class for managing three.js rendering and scene transitions.
  • Added TileManager class for managing tile and building data.
  • Updated ActionInfo component to use new state management for army actions.
  • Refactored useExplore hook to remove unused functions and simplify logic.
  • Added InteractiveHexManager class for managing interactive hexagons.
  • Added Biome class for biome calculations and management.
  • Updated RightNavigationModule to use new modal store.

Changes walkthrough 📝

Relevant files
Enhancement
13 files
Worldmap.ts
Introduce `WorldmapScene` class with army and hexagon management.

client/src/three/scenes/Worldmap.ts

  • Added new WorldmapScene class extending HexagonScene.
  • Implemented methods for handling army movements and hexagon
    interactions.
  • Integrated biome and structure management.
  • +392/-0 
    ArmyMovementManager.ts
    Add `ArmyMovementManager` for army movements and pathfinding.

    client/src/dojo/modelManager/ArmyMovementManager.ts

  • Added ArmyMovementManager class for managing army movements.
  • Implemented pathfinding and stamina management.
  • Added methods for exploring and traveling hexes.
  • +397/-0 
    Hexception.ts
    Introduce HexceptionScene class with building and hexagon management.

    client/src/three/scenes/Hexception.ts

  • Added new HexceptionScene class extending HexagonScene.
  • Implemented methods for building placement and hexagon interactions.
  • Integrated biome and structure management.
  • +329/-0 
    HexagonScene.ts
    Add abstract `HexagonScene` class for common functionality.

    client/src/three/scenes/HexagonScene.ts

  • Added abstract HexagonScene class for common hexagon scene
    functionality.
  • Implemented methods for camera movement and light management.
  • Integrated biome model loading.
  • +334/-0 
    useUIStore.tsx
    Refactor `useUIStore` with new slices and methods.             

    client/src/hooks/store/useUIStore.tsx

  • Refactored useUIStore to include new slices for three.js state
    management.
  • Added methods for camera movement and UI state updates.
  • +140/-134
    GameRenderer.ts
    Add `GameRenderer` class for rendering and scene management.

    client/src/three/GameRenderer.ts

  • Added GameRenderer class for managing three.js rendering and scene
    transitions.
  • Implemented methods for initializing scenes and handling window
    resize.
  • +241/-0 
    ArmyManager.ts
    Add `ArmyManager` for managing army instances and movements.

    client/src/three/components/ArmyManager.ts

  • Added ArmyManager class for managing army instances and movements.
  • Implemented methods for handling mouse interactions and army updates.
  • +211/-0 
    TileManager.ts
    Add `TileManager` for managing tile and building data.     

    client/src/dojo/modelManager/TileManager.ts

  • Added TileManager class for managing tile and building data.
  • Implemented methods for placing and destroying buildings.
  • +226/-0 
    ActionInfo.tsx
    Update `ActionInfo` component with new state management. 

    client/src/ui/components/worldmap/hexagon/ActionInfo.tsx

  • Updated ActionInfo component to use new state management for army
    actions.
  • Refactored tooltip rendering logic.
  • +45/-51 
    useExplore.tsx
    Refactor `useExplore` hook for simplification.                     

    client/src/hooks/helpers/useExplore.tsx

  • Refactored useExplore hook to remove unused functions and simplify
    logic.
  • +2/-113 
    InteractiveHexManager.ts
    Add `InteractiveHexManager` for interactive hexagon management.

    client/src/three/components/InteractiveHexManager.ts

  • Added InteractiveHexManager class for managing interactive hexagons.
  • Implemented methods for handling mouse interactions and rendering
    hexes.
  • +132/-0 
    Biome.ts
    Add `Biome` class for biome calculations and management. 

    client/src/three/components/Biome.ts

  • Added Biome class for biome calculations and management.
  • Implemented methods for determining biome types based on elevation and
    moisture.
  • +97/-0   
    RightNavigationModule.tsx
    Update `RightNavigationModule` to use new modal store.     

    client/src/ui/modules/navigation/RightNavigationModule.tsx

    • Updated RightNavigationModule to use new modal store.
    +2/-2     
    Additional files (token-limit)
    46 files
    InstancedModel.tsx
    ...                                                                                                           

    client/src/three/components/InstancedModel.tsx

    ...

    +116/-0 
    BaseThreeTooltip.tsx
    ...                                                                                                           

    client/src/ui/elements/BaseThreeTooltip.tsx

    ...

    +51/-18 
    BuildingPreview.ts
    ...                                                                                                           

    client/src/three/components/BuildingPreview.ts

    ...

    +104/-0 
    StructureManager.ts
    ...                                                                                                           

    client/src/three/components/StructureManager.ts

    ...

    +90/-0   
    SystemManager.ts
    ...                                                                                                           

    client/src/three/systems/SystemManager.ts

    ...

    +86/-0   
    useHexPosition.tsx
    ...                                                                                                           

    client/src/hooks/helpers/useHexPosition.tsx

    ...

    +7/-38   
    EntityDetails.tsx
    ...                                                                                                           

    client/src/ui/modules/entity-details/EntityDetails.tsx

    ...

    +11/-11 
    InputManager.ts
    ...                                                                                                           

    client/src/three/components/InputManager.ts

    ...

    +76/-0   
    World.tsx
    ...                                                                                                           

    client/src/ui/layouts/World.tsx

    ...

    +10/-17 
    _threeStore.tsx
    ...                                                                                                           

    client/src/hooks/store/_threeStore.tsx

    ...

    +43/-0   
    InstancedBuilding.tsx
    ...                                                                                                           

    client/src/three/components/InstancedBuilding.tsx

    ...

    +84/-0   
    utils.tsx
    ...                                                                                                           

    client/src/ui/utils/utils.tsx

    ...

    +45/-1   
    BattleView.tsx
    ...                                                                                                           

    client/src/ui/modules/military/battle-view/BattleView.tsx

    ...

    +8/-13   
    ArmyInfoLabel.tsx
    ...                                                                                                           

    client/src/ui/components/worldmap/armies/ArmyInfoLabel.tsx

    ...

    +17/-14 
    HighlightHexManager.ts
    ...                                                                                                           

    client/src/three/components/HighlightHexManager.ts

    ...

    +47/-0   
    _popupsStore.tsx
    ...                                                                                                           

    client/src/hooks/store/_popupsStore.tsx

    ...

    +29/-1   
    LabelManager.ts
    ...                                                                                                           

    client/src/three/components/LabelManager.ts

    ...

    +43/-0   
    FogManager.ts
    ...                                                                                                           

    client/src/three/components/FogManager.ts

    ...

    +29/-0   
    TransitionManager.tsx
    ...                                                                                                           

    client/src/three/components/TransitionManager.tsx

    ...

    +48/-0   
    TopMiddleNavigation.tsx
    ...                                                                                                           

    client/src/ui/modules/navigation/TopMiddleNavigation.tsx

    ...

    +7/-1     
    SceneManager.ts
    ...                                                                                                           

    client/src/three/SceneManager.ts

    ...

    +37/-0   
    Steps.tsx
    ...                                                                                                           

    client/src/ui/modules/onboarding/Steps.tsx

    ...

    +7/-1     
    LocationManager.ts
    ...                                                                                                           

    client/src/three/helpers/LocationManager.ts

    ...

    +33/-0   
    HooksComponent.tsx
    ...                                                                                                           

    client/src/ui/components/HooksComponent.tsx

    ...

    +2/-16   
    highlightHexMaterial.ts
    ...                                                                                                           

    client/src/three/shaders/highlightHexMaterial.ts

    ...

    +3/-3     
    MarketModal.tsx
    ...                                                                                                           

    client/src/ui/components/trading/MarketModal.tsx

    ...

    +2/-2     
    BattleActions.tsx
    ...                                                                                                           

    client/src/ui/modules/military/battle-view/BattleActions.tsx

    ...

    +2/-2     
    TopLeftNavigation.tsx
    ...                                                                                                           

    client/src/ui/modules/navigation/TopLeftNavigation.tsx

    ...

    +2/-2     
    HintModalButton.tsx
    ...                                                                                                           

    client/src/ui/elements/HintModalButton.tsx

    ...

    +2/-2     
    main.tsx
    ...                                                                                                           

    client/src/main.tsx

    ...

    +6/-0     
    types.ts
    ...                                                                                                           

    client/src/three/systems/types.ts

    ...

    +19/-0   
    BaseContainer.tsx
    ...                                                                                                           

    client/src/ui/containers/BaseContainer.tsx

    ...

    +1/-1     
    ModalContainer.tsx
    ...                                                                                                           

    client/src/ui/components/ModalContainer.tsx

    ...

    +2/-2     
    ticks.ts
    ...                                                                                                           

    client/src/three/helpers/ticks.ts

    ...

    +11/-0   
    Onboarding.tsx
    ...                                                                                                           

    client/src/ui/layouts/Onboarding.tsx

    ...

    +1/-1     
    DojoHtml.tsx
    ...                                                                                                           

    client/src/ui/elements/DojoHtml.tsx

    ...

    +1/-0     
    useModalStore.tsx
    ...                                                                                                           

    client/src/hooks/store/useModalStore.tsx

    ...

    +1/-1     
    global.ts
    ...                                                                                                           

    sdk/packages/eternum/src/constants/global.ts

    ...

    +3/-1     
    borderHexMaterial.ts
    ...                                                                                                           

    client/src/three/shaders/borderHexMaterial.ts

    ...

    +9/-0     
    transparentHexMaterial.ts
    ...                                                                                                           

    client/src/three/shaders/transparentHexMaterial.ts

    ...

    +9/-0     
    createClientComponents.ts
    ...                                                                                                           

    client/src/dojo/createClientComponents.ts

    ...

    +1/-0     
    App.tsx
    ...                                                                                                           

    client/src/App.tsx

    ...

    +2/-2     
    createSystemCalls.ts
    ...                                                                                                           

    client/src/dojo/createSystemCalls.ts

    ...

    +1/-0     
    GUIManager.ts
    ...                                                                                                           

    client/src/three/helpers/GUIManager.ts

    ...

    +3/-0     
    pnpm-lock.yaml
    ...                                                                                                           

    pnpm-lock.yaml

    ...

    +659/-629
    package.json
    ...                                                                                                           

    client/package.json

    ...

    +4/-1     

    💡 PR-Agent usage:
    Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    Copy link

    vercel bot commented Aug 6, 2024

    The latest updates on your projects. Learn more about Vercel for Git ↗︎

    Name Status Preview Comments Updated (UTC)
    eternum ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 6, 2024 7:07pm

    Copy link

    github-actions bot commented Aug 6, 2024

    PR Reviewer Guide 🔍

    ⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Key issues to review

    Performance Concern
    The WorldmapScene class is very large and complex, which could lead to maintenance challenges and performance issues. Consider refactoring into smaller components or using more efficient data structures and algorithms.

    Code Complexity
    The GameRenderer class handles multiple responsibilities such as scene management, event handling, and rendering logic. This could be refactored to separate concerns more clearly, improving readability and maintainability.

    Possible Bug
    The ArmyManager class uses a complex system of managing armies that might be prone to errors, especially in the methods handling movement and updates. Ensure thorough testing and consider simplifying the logic.

    Code Smell
    The TileManager class has methods with deeply nested logic and multiple responsibilities, which could be simplified or broken down into smaller methods to improve readability and testability.

    Copy link

    github-actions bot commented Aug 6, 2024

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Best practice
    Improve type safety by specifying more accurate types for parameters

    Consider using a more descriptive type than any for the set and get parameters in
    the store slice functions to improve type safety and code readability.

    client/src/hooks/store/_threeStore.tsx [24]

    -export const createThreeStoreSlice = (set: any, get: any) => ({
    +export const createThreeStoreSlice = (set: SetState<ThreeStore>, get: GetState<ThreeStore>) => ({
     
    Suggestion importance[1-10]: 10

    Why: This suggestion significantly improves type safety and code readability by specifying more accurate types for the set and get parameters. This is a best practice in TypeScript to avoid the pitfalls of using any.

    10
    Use optional chaining to safely access deeply nested properties

    Consider using optional chaining (?.) when accessing deeply nested properties to
    avoid potential runtime errors if any part of the chain is undefined. This is
    particularly useful in complex destructuring assignments where the structure of the
    object might not be guaranteed.

    client/src/hooks/helpers/useExplore.tsx [6-13]

    -const {
    -  setup: {
    -    updates: {
    -      eventUpdates: { createExploreEntityMapEvents: exploreEntityMapEvents },
    -    },
    -  },
    -} = useDojo();
    +const exploreEntityMapEvents = useDojo()?.setup?.updates?.eventUpdates?.createExploreEntityMapEvents;
     
    Suggestion importance[1-10]: 8

    Why: This suggestion improves code safety by preventing potential runtime errors when accessing deeply nested properties. It is particularly useful in complex destructuring assignments where the structure of the object might not be guaranteed.

    8
    Improve type safety by specifying a more accurate type than any

    Consider using a more specific type than any for the stats property to enhance type
    safety and code clarity.

    client/src/three/GameRenderer.ts [40]

    -private stats!: any;
    +private stats!: Stats;
     
    Suggestion importance[1-10]: 8

    Why: Specifying a more accurate type than any enhances type safety and code clarity, which is a good practice in TypeScript.

    8
    Integrate DOM updates with React lifecycle using React portals

    Replace the direct manipulation of document.body with a more React-friendly
    approach, such as using React portals or state management, to integrate DOM updates
    within the React lifecycle.

    client/src/three/GameRenderer.ts [122-129]

    -document.body.appendChild(this.stats.dom);
    -document.body.appendChild(this.renderer.domElement);
    +// Use React portals or state to manage these elements
    +ReactDOM.createPortal(this.stats.dom, document.body);
    +ReactDOM.createPortal(this.renderer.domElement, document.body);
     
    Suggestion importance[1-10]: 7

    Why: Using React portals for DOM manipulation aligns with React best practices, but the current implementation might not be straightforward to convert without additional context.

    7
    Use explicit React fragment tags for clarity

    Replace the fragment shorthand <> with <React.Fragment> for better readability and consistency.

    client/src/App.tsx [8-11]

    -<>
    -</>
    +<React.Fragment>
    +</React.Fragment>
     
    Suggestion importance[1-10]: 6

    Why: While using <React.Fragment> instead of <> can improve readability and consistency, it is a minor improvement and does not significantly impact functionality or performance.

    6
    Security
    Remove debug logging to enhance security and cleanliness of production logs

    Remove the console.log statement to avoid exposing potentially sensitive information
    in production logs.

    client/src/dojo/createSystemCalls.ts [132]

    -console.log({ props });
    +// console.log({ props });
     
    Suggestion importance[1-10]: 9

    Why: Removing console.log statements in production code is a good practice to avoid exposing potentially sensitive information and to keep logs clean. This suggestion directly addresses a security concern.

    9
    Enhancement
    Ensure uniqueness in the openedPopups list by using a Set

    Refactor the openAllPopups method to avoid potential duplicates in the openedPopups
    array by using a Set to ensure uniqueness before converting it back to an array.

    client/src/hooks/store/_popupsStore.tsx [26]

     openAllPopups: (names: string[]) => {
    -  set({ openedPopups: [...get().openedPopups, ...names] });
    +  const uniquePopups = new Set([...get().openedPopups, ...names]);
    +  set({ openedPopups: Array.from(uniquePopups) });
     },
     
    Suggestion importance[1-10]: 9

    Why: This suggestion effectively prevents duplicates in the openedPopups array, enhancing the robustness of the code. Using a Set to ensure uniqueness is a simple yet powerful improvement.

    9
    Improve robustness of localStorage data retrieval and parsing

    Consider using a more robust type checking for localStorage operations to handle
    cases where the item does not exist or is not a valid number. This will prevent
    potential runtime errors or incorrect values being used in the state.

    client/src/hooks/store/useUIStore.tsx [80-97]

    -isSoundOn: localStorage.getItem("soundEnabled") ? localStorage.getItem("soundEnabled") === "true" : true,
    -musicLevel: localStorage.getItem("musicLevel") ? parseInt(localStorage.getItem("musicLevel") as string) : 50,
    -effectsLevel: localStorage.getItem("effectsLevel") ? parseInt(localStorage.getItem("effectsLevel") as string) : 50,
    +isSoundOn: localStorage.getItem("soundEnabled") === "true",
    +musicLevel: parseInt(localStorage.getItem("musicLevel") ?? "50"),
    +effectsLevel: parseInt(localStorage.getItem("effectsLevel") ?? "50"),
     
    Suggestion importance[1-10]: 9

    Why: This suggestion improves the robustness of the code by handling cases where localStorage items might not exist or be invalid, preventing potential runtime errors and ensuring default values are used correctly.

    9
    Maintainability
    Add comprehensive error handling for system calls

    Implement error handling for the asynchronous explore and travel_hex system calls to
    manage exceptions and maintain application stability.

    client/src/dojo/modelManager/ArmyMovementManager.ts [336-346]

     this.dojo.systemCalls
       .explore({
         unit_id: this.entityId,
         direction,
         signer: this.dojo.network.burnerManager.account!,
       })
       .catch((e) => {
    -    // removeHex(path[1].x - FELT_CENTER, path[1].y - FELT_CENTER);
    -    this.positionModel.removeOverride(overrideId);
    -    this.staminaModel.removeOverride(overrideId);
    +    console.error("Failed to explore:", e);
    +    // Handle the error appropriately
       });
     
    Suggestion importance[1-10]: 8

    Why: Adding comprehensive error handling improves maintainability and stability of the application. This suggestion enhances the robustness of the code by ensuring errors are logged and managed appropriately.

    8
    Reduce code duplication by refactoring repeated camera update logic into a function

    Refactor the repeated logic for setting camera position and target into a separate
    function to reduce code duplication and improve maintainability.

    client/src/hooks/store/useUIStore.tsx [126-139]

    -set({ cameraPosition: speed ? { ...cameraPos, transitionDuration: speed } : cameraPos });
    -set({ cameraTarget: speed ? { ...targetPos, transitionDuration: speed } : targetPos });
    +function updateCamera(speed, cameraPos, targetPos) {
    +  set({ cameraPosition: speed ? { ...cameraPos, transitionDuration: speed } : cameraPos });
    +  set({ cameraTarget: speed ? { ...targetPos, transitionDuration: speed } : targetPos });
    +}
    +updateCamera(speed, cameraPos, targetPos);
     
    Suggestion importance[1-10]: 8

    Why: Refactoring the repeated logic into a function improves maintainability and readability by reducing code duplication.

    8
    Use a function to dynamically calculate position offsets

    Replace the hardcoded addition of FELT_CENTER with a dynamic calculation based on
    the hex position to ensure the position calculation remains accurate even if the
    configuration changes.

    client/src/hooks/helpers/useHexPosition.tsx [41]

    -HasValue(Position, { x: hexPosition.col + FELT_CENTER, y: hexPosition.row + FELT_CENTER }),
    +HasValue(Position, { x: hexPosition.col + getFeltCenterOffset(), y: hexPosition.row + getFeltCenterOffset() }),
     
    Suggestion importance[1-10]: 7

    Why: This suggestion enhances maintainability by making the position calculation more flexible and adaptable to configuration changes. However, it introduces a minor complexity by requiring the definition of the getFeltCenterOffset function.

    7
    Performance
    Optimize pathfinding with a proper priority queue

    Replace the manual sort operation with a priority queue implementation for better
    performance in pathfinding.

    client/src/dojo/modelManager/ArmyMovementManager.ts [224]

    -priorityQueue.sort((a, b) => a.distance - b.distance); // This makes the queue work as a priority queue
    +// Implement a proper priority queue for better performance
    +// Example placeholder for priority queue usage
     
    Suggestion importance[1-10]: 7

    Why: Replacing the manual sort operation with a proper priority queue can improve performance, especially in pathfinding algorithms. However, the suggestion lacks a concrete implementation, making it less actionable.

    7

    client/src/dojo/createSystemCalls.ts Outdated Show resolved Hide resolved
    client/src/dojo/modelManager/ArmyMovementManager.ts Outdated Show resolved Hide resolved
    client/src/dojo/modelManager/ArmyMovementManager.ts Outdated Show resolved Hide resolved
    client/src/dojo/modelManager/ArmyMovementManager.ts Outdated Show resolved Hide resolved
    client/src/dojo/modelManager/ArmyMovementManager.ts Outdated Show resolved Hide resolved
    client/src/hooks/helpers/useHexPosition.tsx Outdated Show resolved Hide resolved
    client/src/three/components/ArmyManager.ts Outdated Show resolved Hide resolved
    client/src/three/components/InstancedModel.tsx Outdated Show resolved Hide resolved
    client/src/three/scenes/Hexception.ts Show resolved Hide resolved
    sdk/packages/eternum/src/constants/global.ts Outdated Show resolved Hide resolved
    Copy link
    Collaborator

    @bob0005 bob0005 left a comment

    Choose a reason for hiding this comment

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

    Good job ! Looks amazing

    @aymericdelab aymericdelab merged commit 67caeda into main Aug 6, 2024
    21 checks passed
    @aymericdelab aymericdelab deleted the merge-main branch August 6, 2024 19:18
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    5 participants