diff --git a/knip.jsonc b/knip.jsonc index 55f0de093..b4bebf1f4 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -65,28 +65,6 @@ "src/components/application-starter/TemplatePicker.tsx", "src/components/application-starter/index.ts", "src/components/game/engine/entities/index.ts", - "src/components/game/hooks/useAIOpponents.ts", - "src/components/game/hooks/useBoatControls.ts", - "src/components/game/scene/AIShips.tsx", - "src/components/game/scene/BeachChair.tsx", - "src/components/game/scene/Boat.tsx", - "src/components/game/scene/BoundaryWalls.tsx", - "src/components/game/scene/Cannonballs.tsx", - "src/components/game/scene/Coin.tsx", - "src/components/game/scene/Dinghy.tsx", - "src/components/game/scene/Flag.tsx", - "src/components/game/scene/GameScene.tsx", - "src/components/game/scene/Island.tsx", - "src/components/game/scene/IslandInfo3D.tsx", - "src/components/game/scene/IslandLobe.tsx", - "src/components/game/scene/Ocean.tsx", - "src/components/game/scene/OceanRocks.tsx", - "src/components/game/scene/PalmTree.tsx", - "src/components/game/scene/Ship.tsx", - "src/components/game/scene/Sky.tsx", - "src/components/game/scene/TikiShack.tsx", - "src/components/game/scene/VirtualizedCoins.tsx", - "src/components/game/scene/VirtualizedIslands.tsx", "src/components/game/ui/DiscoveryProgress.tsx", "src/components/icons/BaseballCapIcon.tsx", "src/components/icons/YinYangIcon.tsx", @@ -128,7 +106,6 @@ "src/utils/showcase.client.ts", ], "ignoreDependencies": [ - "@react-three/drei", "@tanstack/react-start-client", "@types/hast", "@types/linkify-it", diff --git a/package.json b/package.json index 1d27c6df4..2567b5188 100644 --- a/package.json +++ b/package.json @@ -89,8 +89,6 @@ "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-tooltip": "^1.2.8", - "@react-three/drei": "^10.7.7", - "@react-three/fiber": "^9.5.0", "@sentry/browser": "^10.47.0", "@sentry/node": "^10.47.0", "@sentry/tanstackstart-react": "^10.47.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6d321fd84..68996f0bd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -102,12 +102,6 @@ importers: '@radix-ui/react-tooltip': specifier: ^1.2.8 version: 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3) - '@react-three/drei': - specifier: ^10.7.7 - version: 10.7.7(@react-three/fiber@9.5.0(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(three@0.183.2))(@types/react@19.2.14)(@types/three@0.183.1)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(three@0.183.2) - '@react-three/fiber': - specifier: ^9.5.0 - version: 9.5.0(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(three@0.183.2) '@sentry/browser': specifier: ^10.47.0 version: 10.47.0 @@ -2062,9 +2056,6 @@ packages: '@marijn/find-cluster-break@1.0.3': resolution: {integrity: sha512-FY+MKLBoTsLNJF/eLWaOsXGdz6uh3Iu1axjPf6TUq92IYumcTcXWHoS747JARLkcdlJ/Waiaxc5wQfFO8jC6NA==} - '@mediapipe/tasks-vision@0.10.17': - resolution: {integrity: sha512-CZWV/q6TTe8ta61cZXjfnnHsfWIdFhms03M9T7Cnd5y2mdpylJM0rF1qRq+wsQVRMLz1OYPVEBU9ph2Bx8cxrg==} - '@mermaid-js/parser@1.1.0': resolution: {integrity: sha512-gxK9ZX2+Fex5zu8LhRQoMeMPEHbc73UKZ0FQ54YrQtUxE1VVhMwzeNtKRPAu5aXks4FasbMe4xB4bWrmq6Jlxw==} @@ -3428,42 +3419,6 @@ packages: '@radix-ui/rect@1.1.1': resolution: {integrity: sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw==} - '@react-three/drei@10.7.7': - resolution: {integrity: sha512-ff+J5iloR0k4tC++QtD/j9u3w5fzfgFAWDtAGQah9pF2B1YgOq/5JxqY0/aVoQG5r3xSZz0cv5tk2YuBob4xEQ==} - peerDependencies: - '@react-three/fiber': ^9.0.0 - react: ^19 - react-dom: ^19 - three: '>=0.159' - peerDependenciesMeta: - react-dom: - optional: true - - '@react-three/fiber@9.5.0': - resolution: {integrity: sha512-FiUzfYW4wB1+PpmsE47UM+mCads7j2+giRBltfwH7SNhah95rqJs3ltEs9V3pP8rYdS0QlNne+9Aj8dS/SiaIA==} - peerDependencies: - expo: '>=43.0' - expo-asset: '>=8.4' - expo-file-system: '>=11.0' - expo-gl: '>=11.0' - react: '>=19 <19.3' - react-dom: '>=19 <19.3' - react-native: '>=0.78' - three: '>=0.156' - peerDependenciesMeta: - expo: - optional: true - expo-asset: - optional: true - expo-file-system: - optional: true - expo-gl: - optional: true - react-dom: - optional: true - react-native: - optional: true - '@rolldown/binding-android-arm64@1.0.3': resolution: {integrity: sha512-454rs7jHngixp/NMxd5srYD57OnzSlZ/eFTETjORQHLwJG1lRtmNOJcBerZlfu4GjKqeq8aCCIQrMdHyhI51Hw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -4737,9 +4692,6 @@ packages: '@types/dom-speech-recognition@0.0.1': resolution: {integrity: sha512-udCxb8DvjcDKfk1WTBzDsxFbLgYxmQGKrE/ricoMqHRNjSlSUCcamVTA5lIQqzY10mY5qCY0QDwBfFEwhfoDPw==} - '@types/draco3d@1.4.10': - resolution: {integrity: sha512-AX22jp8Y7wwaBgAixaSvkoG4M/+PlAcm3Qs4OW8yT9DM4xUpWKeFhLueTAyZF39pviAdcDdeJoACapiAceqNcw==} - '@types/estree-jsx@1.0.5': resolution: {integrity: sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==} @@ -4782,9 +4734,6 @@ packages: '@types/node@25.5.0': resolution: {integrity: sha512-jp2P3tQMSxWugkCUKLRPVUpGaL5MVFwF8RDuSRztfwgN1wmqJeMSbKlnEtQqU8UrhTmzEmZdu2I6v2dpp7XIxw==} - '@types/offscreencanvas@2019.7.3': - resolution: {integrity: sha512-ieXiYmgSRXUDeOntE1InxjWyvEelZGP63M+cGuquuRLuIKKT1osnkXjxev9B7d1nXSug5vpunx+gNlbVxMlC9A==} - '@types/pg-pool@2.0.7': resolution: {integrity: sha512-U4CwmGVQcbEuqpyju8/ptOKg6gEC+Tqsvj2xS9o1g71bUh8twxnC6ZL5rZKCsGN0iyH0CwgUyc9VR5owNQF9Ng==} @@ -4802,11 +4751,6 @@ packages: peerDependencies: '@types/react': ^19.2.0 - '@types/react-reconciler@0.28.9': - resolution: {integrity: sha512-HHM3nxyUZ3zAylX8ZEyrDNd2XZOnQ0D5XfunJF5FLQnZbHHYq4UWvW1QfelQNXv1ICNkwYhfxjwfnqivYB6bFg==} - peerDependencies: - '@types/react': '*' - '@types/react@19.2.14': resolution: {integrity: sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==} @@ -4859,14 +4803,6 @@ packages: '@upsetjs/venn.js@2.0.0': resolution: {integrity: sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==} - '@use-gesture/core@10.3.1': - resolution: {integrity: sha512-WcINiDt8WjqBdUXye25anHiNxPc0VOrlT8F6LLkU6cycrOGUDyY/yyFmsg3k8i5OLvv25llc0QC45GhR/C8llw==} - - '@use-gesture/react@10.3.1': - resolution: {integrity: sha512-Yy19y6O2GJq8f7CHf7L0nxL8bf4PZCPaVOCgJrusOeFHY1LvHgYXnmnXg6N5iwAnbgbZCDjo60SiM6IPJi9C5g==} - peerDependencies: - react: '>= 16.8.0' - '@vitejs/plugin-react@6.0.1': resolution: {integrity: sha512-l9X/E3cDb+xY3SWzlG1MOGt2usfEHGMNIaegaUGFsLkb3RCn/k8/TOXBcab+OndDI4TBtktT8/9BwwW8Vi9KUQ==} engines: {node: ^20.19.0 || >=22.12.0} @@ -5183,9 +5119,6 @@ packages: buffer-from@1.1.2: resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} - buffer@6.0.3: - resolution: {integrity: sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==} - builder-util-runtime@9.7.0: resolution: {integrity: sha512-g/kR520giAFYkSXTzcmF3kqQq7wi8F6N6SzeDgZrqTBN+VHdmgWOyTdD1yD7AATDId/yXLvuP34CxW46/BwCdw==} engines: {node: '>=12.0.0'} @@ -5226,12 +5159,6 @@ packages: resolution: {integrity: sha512-8WB3Jcas3swSvjIeA2yvCJ+Miyz5l1ZmB6HFb9R1317dt9LCQoswg/BGrmAmkWVEszSrrg4RwmO46qIm2OEnSA==} engines: {node: '>=16'} - camera-controls@3.1.2: - resolution: {integrity: sha512-xkxfpG2ECZ6Ww5/9+kf4mfg1VEYAoe9aDSY+IwF0UEs7qEzwy0aVRfs2grImIECs/PoBtWFrh7RXsQkwG922JA==} - engines: {node: '>=22.0.0', npm: '>=10.5.1'} - peerDependencies: - three: '>=0.126.1' - caniuse-lite@1.0.30001784: resolution: {integrity: sha512-WU346nBTklUV9YfUl60fqRbU5ZqyXlqvo1SgigE1OAXK5bFL8LL9q1K7aap3N739l4BvNqnkm3YrGHiY9sfUQw==} @@ -5406,11 +5333,6 @@ packages: cross-dirname@0.1.0: resolution: {integrity: sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==} - cross-env@7.0.3: - resolution: {integrity: sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==} - engines: {node: '>=10.14', npm: '>=6', yarn: '>=1'} - hasBin: true - cross-spawn@7.0.6: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'} @@ -5644,9 +5566,6 @@ packages: resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==} engines: {node: '>= 0.8'} - detect-gpu@5.0.70: - resolution: {integrity: sha512-bqerEP1Ese6nt3rFkwPnGbsUF9a4q+gMmpTVVOEzoCyeCc+y7/RvJnQZJx1JwhgQI5Ntg0Kgat8Uu7XpBqnz1w==} - detect-libc@2.1.2: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} @@ -5710,9 +5629,6 @@ packages: resolution: {integrity: sha512-IO8C/dzEb6O3F9/twg6ZLXz164a2fhTnEWb95H23Dm4OuN+92NmEAlTrupP9VW6Jm3sO26tQlqyvyi4CsnY9GA==} engines: {node: '>=12'} - draco3d@1.5.7: - resolution: {integrity: sha512-m6WCKt/erDXcw+70IJXnG7M3awwQPAsZvJGX5zY7beBqpELw6RDGkYVU0W43AFxye4pDZ5i2Lbyc/NNGqwjUVQ==} - drizzle-kit@0.31.10: resolution: {integrity: sha512-7OZcmQUrdGI+DUNNsKBn1aW8qSoKuTH7d0mYgSP8bAzdFzKoovxEFnoGQp2dVs82EOJeYycqRtciopszwUf8bw==} hasBin: true @@ -6078,9 +5994,6 @@ packages: fetchdts@0.1.7: resolution: {integrity: sha512-YoZjBdafyLIop9lSxXVI33oLD5kN31q4Td+CasofLLYeLXRFeOsuOw0Uo+XNRi9PZlbfdlN2GmRtm4tCEQ9/KA==} - fflate@0.6.10: - resolution: {integrity: sha512-IQrh3lEPM93wVCEczc9SaAOvkmcoQn/G8Bo1e8ZPlY3X3bnAxWaBdvTdvM1hP62iZp0BXWDy4vTAy4fF0+Dlpg==} - fflate@0.8.2: resolution: {integrity: sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==} @@ -6260,9 +6173,6 @@ packages: resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==} engines: {node: '>= 0.4'} - glsl-noise@0.0.0: - resolution: {integrity: sha512-b/ZCF6amfAUb7dJM/MxRs7AetQEahYzJ8PtgfrmEdtw6uyGOr+ZSGtgjFm6mfsBkxJ4d2W7kg+Nlqzqvn3Bc0w==} - goober@2.1.18: resolution: {integrity: sha512-2vFqsaDVIT9Gz7N6kAL++pLpp41l3PfDuusHcjnGLfR6+huZkl6ziX+zgVC3ZxpqWhzH6pyDdGrCeDhMIvwaxw==} peerDependencies: @@ -6347,9 +6257,6 @@ packages: resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==} engines: {node: '>= 0.4'} - hls.js@1.6.15: - resolution: {integrity: sha512-E3a5VwgXimGHwpRGV+WxRTKeSp2DW5DI5MWv34ulL3t5UNmyJWCQ1KmLEHbYzcfThfXG8amBL+fCYPneGHC4VA==} - hogan.js@3.0.2: resolution: {integrity: sha512-RqGs4wavGYJWE07t35JQccByczmNUXQT0E12ZYV1VKYu5UiAU9lsos/yBAcf840+zrUQQxgVduCR5/B8nNtibg==} hasBin: true @@ -6411,9 +6318,6 @@ packages: resolution: {integrity: sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==} engines: {node: '>=0.10.0'} - ieee754@1.2.1: - resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==} - ignore@7.0.7: resolution: {integrity: sha512-dML0wP6oak21rsNYCJpJB6O1BJIEwNpGrTw0URPfAk4hm0e3pRfCtzkfB6olBcXcVlU2rouCyz7lCyRB0OMVCA==} engines: {node: '>= 4'} @@ -6616,11 +6520,6 @@ packages: resolution: {integrity: sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw==} engines: {node: '>=20'} - its-fine@2.0.0: - resolution: {integrity: sha512-KLViCmWx94zOvpLwSlsx6yOCeMhZYaxrJV87Po5k/FoZzcPSahvK5qJ7fYhS61sZi5ikmh2S3Hz55A2l3U69ng==} - peerDependencies: - react: ^19.0.0 - jake@10.9.4: resolution: {integrity: sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==} engines: {node: '>=10'} @@ -6940,12 +6839,6 @@ packages: resolution: {integrity: sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==} engines: {node: '>=10'} - maath@0.10.8: - resolution: {integrity: sha512-tRvbDF0Pgqz+9XUa4jjfgAQ8/aPKmQdWXilFu2tMy4GWj4NOsx99HlULO4IeREfbO3a0sA145DZYyvXPkybm0g==} - peerDependencies: - '@types/three': '>=0.134.0' - three: '>=0.134.0' - magic-string@0.30.21: resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} @@ -6989,11 +6882,6 @@ packages: mermaid@11.14.0: resolution: {integrity: sha512-GSGloRsBs+JINmmhl0JDwjpuezCsHB4WGI4NASHxL3fHo3o/BRXTxhDLKnln8/Q0lRFRyDdEjmk1/d5Sn1Xz8g==} - meshline@3.3.1: - resolution: {integrity: sha512-/TQj+JdZkeSUOl5Mk2J7eLcYTLiQm2IDzmlSvYm7ov15anEcDJ92GHqqazxTSreeNgfnYu24kiEvvv0WlbCdFQ==} - peerDependencies: - three: '>=0.137' - meshoptimizer@1.0.1: resolution: {integrity: sha512-Vix+QlA1YYT3FwmBBZ+49cE5y/b+pRrcXKqGpS5ouh33d3lSp2PoTpCw19E0cKDFWalembrHnIaZetf27a+W2g==} @@ -7514,9 +7402,6 @@ packages: engines: {node: '>=14.0.0'} hasBin: true - potpack@1.0.2: - resolution: {integrity: sha512-choctRBIV9EMT9WGAZHn3V7t0Z2pMQyl0EZE6pFc/6ml3ssw7Dlf/oAOvFwjm1HVsqfQN8GfeFyJ+d8tRzqueQ==} - preact@10.29.0: resolution: {integrity: sha512-wSAGyk2bYR1c7t3SZ3jHcM6xy0lcBcDel6lODcs9ME6Th++Dx2KU+6D3HD8wMMKGA8Wpw7OMd3/4RGzYRpzwRg==} @@ -7650,15 +7535,6 @@ packages: '@types/react': optional: true - react-use-measure@2.1.7: - resolution: {integrity: sha512-KrvcAo13I/60HpwGO5jpW7E9DfusKyLPLvuHlUyP5zqnmAPhNc6qTRjUQrdTADl0lpPpDVU2/Gg51UlOGHXbdg==} - peerDependencies: - react: '>=16.13' - react-dom: '>=16.13' - peerDependenciesMeta: - react-dom: - optional: true - react@19.2.3: resolution: {integrity: sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==} engines: {node: '>=0.10.0'} @@ -8022,15 +7898,6 @@ packages: resolution: {integrity: sha512-jH9EhtKIjuXZ2cWxmXS8ZP80XyC3iasQxMDV8jzhNJpfDb7VbQLVW4Wvsxz9QZvzV+G4YoSfBUVKDOyxLzi/sg==} engines: {node: '>= 6'} - stats-gl@2.4.2: - resolution: {integrity: sha512-g5O9B0hm9CvnM36+v7SFl39T7hmAlv541tU81ME8YeSb3i1CIP5/QdDeSB3A0la0bKNHpxpwxOVRo2wFTYEosQ==} - peerDependencies: - '@types/three': '*' - three: '*' - - stats.js@0.17.0: - resolution: {integrity: sha512-hNKz8phvYLPEcRkeG1rsGmV5ChMjKDAWU7/OJJdDErPBNChQXxCo3WZurGpnWc6gZhAzEPFad1aVgyOANH1sMw==} - statuses@2.0.2: resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==} engines: {node: '>= 0.8'} @@ -8114,11 +7981,6 @@ packages: resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} engines: {node: '>= 0.4'} - suspend-react@0.1.3: - resolution: {integrity: sha512-aqldKgX9aZqpoDp3e8/BZ8Dm7x1pJl+qI3ZKxDN0i/IQTWUwBx/ManmlVJ3wowqbno6c2bmiIfs+Um6LbsjJyQ==} - peerDependencies: - react: '>=17.0' - svix@1.88.0: resolution: {integrity: sha512-vm/JrrUd3bVyBE+3L33TIyVSs8gS5fYx7lrISvKlDJXTYX1ACH4REX8P1tHxsSKoZi/rvifM1t0XRc5Vc45THw==} @@ -8159,16 +8021,6 @@ packages: text-decoder@1.2.7: resolution: {integrity: sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==} - three-mesh-bvh@0.8.3: - resolution: {integrity: sha512-4G5lBaF+g2auKX3P0yqx+MJC6oVt6sB5k+CchS6Ob0qvH0YIhuUk1eYr7ktsIpY+albCqE80/FVQGV190PmiAg==} - peerDependencies: - three: '>= 0.159.0' - - three-stdlib@2.36.1: - resolution: {integrity: sha512-XyGQrFmNQ5O/IoKm556ftwKsBg11TIb301MB5dWNicziQBEs2g3gtOYIf7pFiLa0zI2gUwhtCjv9fmjnxKZ1Cg==} - peerDependencies: - three: '>=0.128.0' - three@0.183.2: resolution: {integrity: sha512-di3BsL2FEQ1PA7Hcvn4fyJOlxRRgFYBpMTcyOgkwJIaDOdJMebEFPA+t98EvjuljDx4hNulAGwF6KIjtwI5jgQ==} @@ -8246,9 +8098,6 @@ packages: engines: {node: '>=18.0.0'} hasBin: true - tunnel-rat@0.1.2: - resolution: {integrity: sha512-lR5VHmkPhzdhrM092lI2nACsLO4QubF0/yoOhzX7c+wIpbN1GjHNzCc91QlpxBi+cnx8vVJ+Ur6vL5cEoQPFpQ==} - tw-fade@0.8.0: resolution: {integrity: sha512-9ewfWqOiMaUKrsiN4+jsu1IyFnqzr9coZrVRzGlB0G1HuEPcvpCG2sRo8F1rEoRXxFVmrL6WxT8CRIlmYPV0Qw==} peerDependencies: @@ -8458,10 +8307,6 @@ packages: util-deprecate@1.0.2: resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} - utility-types@3.11.0: - resolution: {integrity: sha512-6Z7Ma2aVEWisaL6TvBCy7P8rm2LQoPv6dJ7ecIaIixHcwfbJ0x7mWdbcwlIM5IGQxPZSFYeqRCqlOOeKoJYMkw==} - engines: {node: '>= 4'} - uuid@10.0.0: resolution: {integrity: sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==} hasBin: true @@ -8615,9 +8460,6 @@ packages: webcrypto-core@1.9.2: resolution: {integrity: sha512-gsXecm82UQNlTBURJGuqOWy1Ww08S3kZUcr3aOJS02Pk0xLtkfeUAVC0u0xhgdonFme80edSJUIJyuvL/7250Q==} - webgl-constants@1.1.1: - resolution: {integrity: sha512-LkBXKjU5r9vAW7Gcu3T5u+5cvSvh5WwINdr0C+9jpzVB41cjQAP5ePArDtk/WHYdVj0GefCgM73BA7FlIiNtdg==} - webgl-sdf-generator@1.1.1: resolution: {integrity: sha512-9Z0JcMTFxeE+b2x1LJTdnaT8rT8aEp7MVxkNwoycNmJWwPdzoXzMh0BjJSh/AEFP+KPYZUli814h8bJZFIZ2jA==} @@ -10202,8 +10044,6 @@ snapshots: '@marijn/find-cluster-break@1.0.3': {} - '@mediapipe/tasks-vision@0.10.17': {} - '@mermaid-js/parser@1.1.0': dependencies: langium: 4.2.1 @@ -11306,59 +11146,6 @@ snapshots: '@radix-ui/rect@1.1.1': {} - '@react-three/drei@10.7.7(@react-three/fiber@9.5.0(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(three@0.183.2))(@types/react@19.2.14)(@types/three@0.183.1)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(three@0.183.2)': - dependencies: - '@babel/runtime': 7.29.2 - '@mediapipe/tasks-vision': 0.10.17 - '@monogrid/gainmap-js': 3.4.0(three@0.183.2) - '@react-three/fiber': 9.5.0(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(three@0.183.2) - '@use-gesture/react': 10.3.1(react@19.2.3) - camera-controls: 3.1.2(three@0.183.2) - cross-env: 7.0.3 - detect-gpu: 5.0.70 - glsl-noise: 0.0.0 - hls.js: 1.6.15 - maath: 0.10.8(@types/three@0.183.1)(three@0.183.2) - meshline: 3.3.1(three@0.183.2) - react: 19.2.3 - stats-gl: 2.4.2(@types/three@0.183.1)(three@0.183.2) - stats.js: 0.17.0 - suspend-react: 0.1.3(react@19.2.3) - three: 0.183.2 - three-mesh-bvh: 0.8.3(three@0.183.2) - three-stdlib: 2.36.1(three@0.183.2) - troika-three-text: 0.52.4(three@0.183.2) - tunnel-rat: 0.1.2(@types/react@19.2.14)(react@19.2.3)(use-sync-external-store@1.6.0(react@19.2.3)) - use-sync-external-store: 1.6.0(react@19.2.3) - utility-types: 3.11.0 - zustand: 5.0.12(@types/react@19.2.14)(react@19.2.3)(use-sync-external-store@1.6.0(react@19.2.3)) - optionalDependencies: - react-dom: 19.2.3(react@19.2.3) - transitivePeerDependencies: - - '@types/react' - - '@types/three' - - immer - - '@react-three/fiber@9.5.0(@types/react@19.2.14)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(three@0.183.2)': - dependencies: - '@babel/runtime': 7.29.2 - '@types/webxr': 0.5.24 - base64-js: 1.5.1 - buffer: 6.0.3 - its-fine: 2.0.0(@types/react@19.2.14)(react@19.2.3) - react: 19.2.3 - react-use-measure: 2.1.7(react-dom@19.2.3(react@19.2.3))(react@19.2.3) - scheduler: 0.27.0 - suspend-react: 0.1.3(react@19.2.3) - three: 0.183.2 - use-sync-external-store: 1.6.0(react@19.2.3) - zustand: 5.0.12(@types/react@19.2.14)(react@19.2.3)(use-sync-external-store@1.6.0(react@19.2.3)) - optionalDependencies: - react-dom: 19.2.3(react@19.2.3) - transitivePeerDependencies: - - '@types/react' - - immer - '@rolldown/binding-android-arm64@1.0.3': optional: true @@ -12755,8 +12542,6 @@ snapshots: '@types/dom-speech-recognition@0.0.1': {} - '@types/draco3d@1.4.10': {} - '@types/estree-jsx@1.0.5': dependencies: '@types/estree': 1.0.8 @@ -12799,8 +12584,6 @@ snapshots: dependencies: undici-types: 7.18.2 - '@types/offscreencanvas@2019.7.3': {} - '@types/pg-pool@2.0.7': dependencies: '@types/pg': 8.20.0 @@ -12823,10 +12606,6 @@ snapshots: dependencies: '@types/react': 19.2.14 - '@types/react-reconciler@0.28.9(@types/react@19.2.14)': - dependencies: - '@types/react': 19.2.14 - '@types/react@19.2.14': dependencies: csstype: 3.2.3 @@ -12887,13 +12666,6 @@ snapshots: d3-selection: 3.0.0 d3-transition: 3.0.1(d3-selection@3.0.0) - '@use-gesture/core@10.3.1': {} - - '@use-gesture/react@10.3.1(react@19.2.3)': - dependencies: - '@use-gesture/core': 10.3.1 - react: 19.2.3 - '@vitejs/plugin-react@6.0.1(vite@8.0.16(@types/node@25.5.0)(esbuild@0.27.4)(jiti@2.7.0)(tsx@4.21.0)(yaml@2.9.0))': dependencies: '@rolldown/pluginutils': 1.0.0-rc.7 @@ -13242,11 +13014,6 @@ snapshots: buffer-from@1.1.2: {} - buffer@6.0.3: - dependencies: - base64-js: 1.5.1 - ieee754: 1.2.1 - builder-util-runtime@9.7.0: dependencies: debug: 4.4.3 @@ -13308,10 +13075,6 @@ snapshots: camelcase@8.0.0: {} - camera-controls@3.1.2(three@0.183.2): - dependencies: - three: 0.183.2 - caniuse-lite@1.0.30001784: {} chai@6.3.0: {} @@ -13491,10 +13254,6 @@ snapshots: cross-dirname@0.1.0: optional: true - cross-env@7.0.3: - dependencies: - cross-spawn: 7.0.6 - cross-spawn@7.0.6: dependencies: path-key: 3.1.1 @@ -13753,10 +13512,6 @@ snapshots: depd@2.0.0: {} - detect-gpu@5.0.70: - dependencies: - webgl-constants: 1.1.1 - detect-libc@2.1.2: {} detect-node-es@1.1.0: {} @@ -13826,8 +13581,6 @@ snapshots: dotenv@17.3.1: {} - draco3d@1.5.7: {} - drizzle-kit@0.31.10: dependencies: '@drizzle-team/brocli': 0.10.2 @@ -14310,8 +14063,6 @@ snapshots: fetchdts@0.1.7: {} - fflate@0.6.10: {} - fflate@0.8.2: {} fflate@0.8.3: {} @@ -14526,8 +14277,6 @@ snapshots: define-properties: 1.2.1 gopd: 1.2.0 - glsl-noise@0.0.0: {} - goober@2.1.18(csstype@3.2.3): dependencies: csstype: 3.2.3 @@ -14611,8 +14360,6 @@ snapshots: dependencies: function-bind: 1.1.2 - hls.js@1.6.15: {} - hogan.js@3.0.2: dependencies: mkdirp: 0.3.0 @@ -14683,8 +14430,6 @@ snapshots: dependencies: safer-buffer: 2.1.2 - ieee754@1.2.1: {} - ignore@7.0.7: {} immediate@3.0.6: {} @@ -14890,13 +14635,6 @@ snapshots: isexe@4.0.0: {} - its-fine@2.0.0(@types/react@19.2.14)(react@19.2.3): - dependencies: - '@types/react-reconciler': 0.28.9(@types/react@19.2.14) - react: 19.2.3 - transitivePeerDependencies: - - '@types/react' - jake@10.9.4: dependencies: async: 3.2.6 @@ -15178,11 +14916,6 @@ snapshots: dependencies: yallist: 4.0.0 - maath@0.10.8(@types/three@0.183.1)(three@0.183.2): - dependencies: - '@types/three': 0.183.1 - three: 0.183.2 - magic-string@0.30.21: dependencies: '@jridgewell/sourcemap-codec': 1.5.5 @@ -15235,10 +14968,6 @@ snapshots: ts-dedent: 2.2.0 uuid: 11.1.0 - meshline@3.3.1(three@0.183.2): - dependencies: - three: 0.183.2 - meshoptimizer@1.0.1: {} mime-db@1.52.0: {} @@ -15826,8 +15555,6 @@ snapshots: commander: 9.5.0 optional: true - potpack@1.0.2: {} - preact@10.29.0: {} prettier@3.9.6: {} @@ -15972,12 +15699,6 @@ snapshots: optionalDependencies: '@types/react': 19.2.14 - react-use-measure@2.1.7(react-dom@19.2.3(react@19.2.3))(react@19.2.3): - dependencies: - react: 19.2.3 - optionalDependencies: - react-dom: 19.2.3(react@19.2.3) - react@19.2.3: {} read-binary-file-arch@1.0.6: @@ -16460,13 +16181,6 @@ snapshots: stat-mode@1.0.0: {} - stats-gl@2.4.2(@types/three@0.183.1)(three@0.183.2): - dependencies: - '@types/three': 0.183.1 - three: 0.183.2 - - stats.js@0.17.0: {} - statuses@2.0.2: {} std-env@4.3.0: {} @@ -16559,10 +16273,6 @@ snapshots: supports-preserve-symlinks-flag@1.0.0: {} - suspend-react@0.1.3(react@19.2.3): - dependencies: - react: 19.2.3 - svix@1.88.0: dependencies: standardwebhooks: 1.0.0 @@ -16628,20 +16338,6 @@ snapshots: transitivePeerDependencies: - react-native-b4a - three-mesh-bvh@0.8.3(three@0.183.2): - dependencies: - three: 0.183.2 - - three-stdlib@2.36.1(three@0.183.2): - dependencies: - '@types/draco3d': 1.4.10 - '@types/offscreencanvas': 2019.7.3 - '@types/webxr': 0.5.24 - draco3d: 1.5.7 - fflate: 0.6.10 - potpack: 1.0.2 - three: 0.183.2 - three@0.183.2: {} tiny-async-pool@1.3.0: @@ -16709,15 +16405,6 @@ snapshots: optionalDependencies: fsevents: 2.3.3 - tunnel-rat@0.1.2(@types/react@19.2.14)(react@19.2.3)(use-sync-external-store@1.6.0(react@19.2.3)): - dependencies: - zustand: 5.0.12(@types/react@19.2.14)(react@19.2.3)(use-sync-external-store@1.6.0(react@19.2.3)) - transitivePeerDependencies: - - '@types/react' - - immer - - react - - use-sync-external-store - tw-fade@0.8.0(tailwindcss@4.2.2): optionalDependencies: tailwindcss: 4.2.2 @@ -16877,8 +16564,6 @@ snapshots: util-deprecate@1.0.2: {} - utility-types@3.11.0: {} - uuid@10.0.0: {} uuid@11.1.0: {} @@ -16974,8 +16659,6 @@ snapshots: asn1js: 3.0.10 tslib: 2.8.1 - webgl-constants@1.1.1: {} - webgl-sdf-generator@1.1.1: {} webidl-conversions@3.0.1: {} diff --git a/src/components/game/engine/entities/AIShips.ts b/src/components/game/engine/entities/AIShips.ts index 0e24c33a4..bd8297e2f 100644 --- a/src/components/game/engine/entities/AIShips.ts +++ b/src/components/game/engine/entities/AIShips.ts @@ -1,7 +1,6 @@ import * as THREE from 'three' import { modelLoader } from '../loaders/ModelLoader' import { getWaveHeight } from './Ocean' -import { CULL_DISTANCES } from '../../hooks/useDistanceCulling' import { useGameStore, type OtherPlayer } from '../../hooks/useGameStore' interface AIShipData { @@ -108,7 +107,7 @@ export class AIShips { } this.group.visible = true - const maxDistSq = CULL_DISTANCES.ship * CULL_DISTANCES.ship + const maxDistSq = 100 ** 2 for (const player of otherPlayers) { if (!player.isAI) continue diff --git a/src/components/game/engine/entities/OceanRocks.ts b/src/components/game/engine/entities/OceanRocks.ts index cad3ad765..31dc5cba0 100644 --- a/src/components/game/engine/entities/OceanRocks.ts +++ b/src/components/game/engine/entities/OceanRocks.ts @@ -1,6 +1,5 @@ import * as THREE from 'three' import type { IslandData } from '../../utils/islandGenerator' -import { CULL_DISTANCES } from '../../hooks/useDistanceCulling' interface RockData { localPosition: THREE.Vector3 @@ -177,7 +176,7 @@ export class OceanRocks { } update(time: number, boatPosition: [number, number, number]): void { - const maxDistSq = CULL_DISTANCES.rock * CULL_DISTANCES.rock + const maxDistSq = 60 ** 2 for (let gi = 0; gi < this.rockGroups.length; gi++) { const rockGroup = this.rockGroups[gi] diff --git a/src/components/game/hooks/useAIOpponents.ts b/src/components/game/hooks/useAIOpponents.ts deleted file mode 100644 index 4cd37a5f6..000000000 --- a/src/components/game/hooks/useAIOpponents.ts +++ /dev/null @@ -1,318 +0,0 @@ -import { useEffect, useRef } from 'react' -import { useFrame } from '@react-three/fiber' -import { useGameStore, type OtherPlayer, type Cannonball } from './useGameStore' - -const AI_SHIP_COLORS = [ - '#e74c3c', // Red - '#9b59b6', // Purple - '#3498db', // Blue - '#1abc9c', // Teal - '#f39c12', // Orange - '#2ecc71', // Green -] - -// AI behavior constants -const AI_SPEED = 4 -const AI_TURN_SPEED = 1.5 -const AI_WANDER_CHANGE_TIME = 5 // Seconds before picking new direction -const AI_AVOID_DISTANCE = 15 // Distance to start avoiding obstacles -const AI_AGGRO_DISTANCE = 50 // Distance to start chasing player -const AI_ATTACK_DISTANCE = 20 // Distance to start firing -const AI_FIRE_COOLDOWN = 2000 // ms between shots - -interface AIState { - targetAngle: number - wanderTimer: number - isAvoiding: boolean - isAggro: boolean - lastFireTime: number -} - -// Generate initial AI opponents -function generateAIOpponents( - count: number, - _worldBoundary: number, -): OtherPlayer[] { - const opponents: OtherPlayer[] = [] - - for (let i = 0; i < count; i++) { - // Spawn in expanded zone (outer ring) - const angle = (i / count) * Math.PI * 2 + Math.random() * 0.5 - const radius = 100 + Math.random() * 60 // 100-160 units from center - - opponents.push({ - id: `ai-${i}`, - isAI: true, - position: [Math.cos(angle) * radius, 0, Math.sin(angle) * radius], - rotation: Math.random() * Math.PI * 2, - velocity: AI_SPEED * 0.5, - boatType: 'ship', - color: AI_SHIP_COLORS[i % AI_SHIP_COLORS.length], - health: 100, - }) - } - - return opponents -} - -// Create AI cannonball -function createAICannonball( - aiPosition: [number, number, number], - aiRotation: number, - aiId: string, - side: 'left' | 'right', -): Cannonball { - const sideMultiplier = side === 'right' ? 1 : -1 - const cannonOffset = 0.5 - const baseSpeed = 15 - - // Position: offset perpendicular to ship heading - const perpX = Math.cos(aiRotation) * sideMultiplier - const perpZ = -Math.sin(aiRotation) * sideMultiplier - const fireX = aiPosition[0] + perpX * cannonOffset - const fireZ = aiPosition[2] + perpZ * cannonOffset - - // Velocity: fire perpendicular to ship - const velX = Math.cos(aiRotation) * baseSpeed * sideMultiplier - const velZ = -Math.sin(aiRotation) * baseSpeed * sideMultiplier - - return { - id: Date.now() + Math.random() * 1000, - position: [fireX, 0.5, fireZ], - velocity: [velX, 2, velZ], - ownerId: aiId, - createdAt: Date.now(), - } -} - -export function useAIOpponents() { - const { setOtherPlayers } = useGameStore.getState() - - // Store AI state (not in global store to avoid re-renders) - const aiStates = useRef>(new Map()) - const initialized = useRef(false) - - // Initialize AI opponents when entering battle stage - useEffect(() => { - // Check stage inside effect, subscribe via interval to avoid re-render loop - const checkAndInit = () => { - const { stage, otherPlayers, worldBoundary } = useGameStore.getState() - - // Reset initialized flag if we're in battle but have no AI ships (restart scenario) - if ( - stage === 'battle' && - initialized.current && - otherPlayers.length === 0 - ) { - initialized.current = false - aiStates.current.clear() - } - - if (stage === 'battle' && !initialized.current) { - const aiOpponents = generateAIOpponents(4, worldBoundary) - setOtherPlayers(aiOpponents) - initialized.current = true - - // Initialize AI states - aiOpponents.forEach((ai) => { - aiStates.current.set(ai.id, { - targetAngle: ai.rotation, - wanderTimer: Math.random() * AI_WANDER_CHANGE_TIME, - isAvoiding: false, - isAggro: false, - lastFireTime: 0, - }) - }) - } - } - - checkAndInit() - const interval = setInterval(checkAndInit, 500) - return () => clearInterval(interval) - }, [setOtherPlayers]) - - // Update AI behavior each frame - useFrame((_, delta) => { - const { - phase, - stage, - otherPlayers, - boatPosition, - islands, - worldBoundary, - cannonballs, - } = useGameStore.getState() - if (phase !== 'playing' || stage !== 'battle') return - const dt = Math.min(delta, 0.1) - - const newCannonballs: Cannonball[] = [] - - const updatedPlayers = otherPlayers.map((player) => { - if (!player.isAI) return player - - let state = aiStates.current.get(player.id) - if (!state) { - state = { - targetAngle: player.rotation, - wanderTimer: 0, - isAvoiding: false, - isAggro: false, - lastFireTime: 0, - } - aiStates.current.set(player.id, state) - } - - const [px, py, pz] = player.position - - // Check distance to player - const dxToPlayer = boatPosition[0] - px - const dzToPlayer = boatPosition[2] - pz - const distToPlayer = Math.sqrt( - dxToPlayer * dxToPlayer + dzToPlayer * dzToPlayer, - ) - - // Aggro check - state.isAggro = distToPlayer < AI_AGGRO_DISTANCE - - // Update wander timer (only when not aggro) - if (!state.isAggro) { - state.wanderTimer -= dt - if (state.wanderTimer <= 0) { - state.targetAngle = Math.random() * Math.PI * 2 - state.wanderTimer = AI_WANDER_CHANGE_TIME + Math.random() * 3 - } - } - - // Check for obstacles (world boundary, islands) - let avoidAngle = state.targetAngle - state.isAvoiding = false - - // Avoid world boundary - const boundaryMargin = 20 - if (px < -worldBoundary + boundaryMargin) { - avoidAngle = 0 - state.isAvoiding = true - } else if (px > worldBoundary - boundaryMargin) { - avoidAngle = Math.PI - state.isAvoiding = true - } else if (pz < -worldBoundary + boundaryMargin) { - avoidAngle = Math.PI / 2 - state.isAvoiding = true - } else if (pz > worldBoundary - boundaryMargin) { - avoidAngle = -Math.PI / 2 - state.isAvoiding = true - } - - // Avoid islands - if (!state.isAvoiding) { - for (const island of islands) { - const dx = px - island.position[0] - const dz = pz - island.position[2] - const dist = Math.sqrt(dx * dx + dz * dz) - const avoidRadius = island.scale * 4 + AI_AVOID_DISTANCE - - if (dist < avoidRadius) { - avoidAngle = Math.atan2(dx, dz) - state.isAvoiding = true - break - } - } - } - - // Determine target angle - let targetAngle: number - if (state.isAvoiding) { - targetAngle = avoidAngle - } else if (state.isAggro) { - // Chase player - but offset to get broadside angle for firing - const angleToPlayer = Math.atan2(dxToPlayer, dzToPlayer) - // Try to position perpendicular to player for broadside attack - if (distToPlayer < AI_ATTACK_DISTANCE) { - // Circle around player - targetAngle = angleToPlayer + Math.PI / 2 - } else { - // Chase directly - targetAngle = angleToPlayer - } - } else { - targetAngle = state.targetAngle - } - - // Calculate new rotation (turn toward target) - let newRotation = player.rotation - let angleDiff = targetAngle - newRotation - - // Normalize angle difference - while (angleDiff > Math.PI) angleDiff -= Math.PI * 2 - while (angleDiff < -Math.PI) angleDiff += Math.PI * 2 - - // Turn toward target - const turnAmount = AI_TURN_SPEED * dt - if (Math.abs(angleDiff) > 0.05) { - if (angleDiff > 0) { - newRotation += Math.min(turnAmount, angleDiff) - } else { - newRotation -= Math.min(turnAmount, -angleDiff) - } - } - - // Move forward - const speed = state.isAvoiding - ? AI_SPEED * 0.7 - : state.isAggro - ? AI_SPEED * 1.2 - : AI_SPEED - const moveX = Math.sin(newRotation) * speed * dt - const moveZ = Math.cos(newRotation) * speed * dt - - let newX = px + moveX - let newZ = pz + moveZ - - // Hard clamp to world boundary - newX = Math.max(-worldBoundary + 5, Math.min(worldBoundary - 5, newX)) - newZ = Math.max(-worldBoundary + 5, Math.min(worldBoundary - 5, newZ)) - - // Attack logic - fire cannons when in range - const now = Date.now() - if ( - state.isAggro && - distToPlayer < AI_ATTACK_DISTANCE && - now - state.lastFireTime > AI_FIRE_COOLDOWN - ) { - // Check if player is roughly to our side (broadside angle) - const angleToPlayerFromShip = Math.atan2(dxToPlayer, dzToPlayer) - let relativeAngle = angleToPlayerFromShip - newRotation - while (relativeAngle > Math.PI) relativeAngle -= Math.PI * 2 - while (relativeAngle < -Math.PI) relativeAngle += Math.PI * 2 - - // Fire if player is roughly to our side (within 90 degrees of perpendicular) - const absRelAngle = Math.abs(relativeAngle) - if (absRelAngle > Math.PI / 4 && absRelAngle < (3 * Math.PI) / 4) { - // Determine which side to fire - const side = relativeAngle > 0 ? 'left' : 'right' - newCannonballs.push( - createAICannonball([newX, py, newZ], newRotation, player.id, side), - ) - state.lastFireTime = now - } - } - - return { - ...player, - position: [newX, py, newZ] as [number, number, number], - rotation: newRotation, - velocity: speed, - } - }) - - // Update store with new positions and any new cannonballs - if (newCannonballs.length > 0) { - useGameStore.setState({ - otherPlayers: updatedPlayers, - cannonballs: [...cannonballs, ...newCannonballs], - }) - } else { - useGameStore.setState({ otherPlayers: updatedPlayers }) - } - }) -} diff --git a/src/components/game/hooks/useBoatControls.ts b/src/components/game/hooks/useBoatControls.ts deleted file mode 100644 index b9b393fe1..000000000 --- a/src/components/game/hooks/useBoatControls.ts +++ /dev/null @@ -1,403 +0,0 @@ -import { useEffect, useRef } from 'react' -import { useFrame } from '@react-three/fiber' -import { useGameStore } from './useGameStore' -import { findNearestIsland } from '../utils/islandGenerator' -import { checkIslandCollision, checkRockCollision } from '../utils/collision' -import { getPointerState } from '../ui/TouchControls' - -// Speed scales from MIN to MAX based on coins collected (0-100) -const MIN_BOAT_SPEED = 3 -const MAX_BOAT_SPEED = 10 -const MIN_REVERSE_SPEED = 1.5 -const MAX_REVERSE_SPEED = 5 -const TURN_SPEED = 2.2 -const DRAG = 0.96 -const ACCELERATION = 0.12 -const BOAT_RADIUS = 0.8 -const COIN_COLLECT_RADIUS = 1.5 -const MAX_COINS = 50 - -// Calculate current max speed based on coins collected and active boosts -function getMaxSpeed( - coinsCollected: number, - isReverse: boolean, - hasSpeedBoost: boolean, -): number { - const ratio = Math.min(coinsCollected / MAX_COINS, 1) - let speed: number - if (isReverse) { - speed = MIN_REVERSE_SPEED + ratio * (MAX_REVERSE_SPEED - MIN_REVERSE_SPEED) - } else { - speed = MIN_BOAT_SPEED + ratio * (MAX_BOAT_SPEED - MIN_BOAT_SPEED) - } - // Double speed if boost is active - return hasSpeedBoost ? speed * 2 : speed -} - -// Calculate target angle from pointer position -function getTargetAngleFromPointer(pointerX: number, pointerY: number): number { - const centerX = window.innerWidth / 2 - const centerY = window.innerHeight / 2 - - const dx = pointerX - centerX - const dy = pointerY - centerY - - // Screen angle: 0 = up, positive = clockwise - // Negate dx to fix left/right inversion - const screenAngle = Math.atan2(-dx, -dy) - - // Camera offset: camera is at +X, +Z looking toward origin - const cameraOffset = -Math.PI * 0.75 - const targetAngle = screenAngle + cameraOffset - - // Normalize to -PI to PI - return Math.atan2(Math.sin(targetAngle), Math.cos(targetAngle)) -} - -// Calculate shortest angle difference, normalized to -PI to PI -function angleDifference(target: number, current: number): number { - let diff = target - current - while (diff > Math.PI) diff -= Math.PI * 2 - while (diff < -Math.PI) diff += Math.PI * 2 - return diff -} - -export function useBoatControls() { - // Get setters once via getState to avoid any subscriptions - const { - setBoatPosition, - setBoatRotation, - setBoatVelocity, - setMovingForward, - setMovingBackward, - setTurningLeft, - setTurningRight, - setNearbyIsland, - discoverIsland, - } = useGameStore.getState() - - // Track if space is held for gatling - const spaceHeldRef = useRef(false) - - // Keyboard controls - always attach, check phase inside handlers - useEffect(() => { - const handleKeyDown = (e: KeyboardEvent) => { - if (e.code === 'ArrowUp' || e.code === 'KeyW') { - e.preventDefault() - setMovingForward(true) - } - if (e.code === 'ArrowDown' || e.code === 'KeyS') { - e.preventDefault() - setMovingBackward(true) - } - if (e.code === 'ArrowLeft' || e.code === 'KeyA') { - e.preventDefault() - setTurningLeft(true) - } - if (e.code === 'ArrowRight' || e.code === 'KeyD') { - e.preventDefault() - setTurningRight(true) - } - // Fire cannon with spacebar (only works in battle stage) - // e.repeat is true when key is held down and auto-repeating - if (e.code === 'Space' && !e.repeat) { - e.preventDefault() - const { shipStats, fireCannon } = useGameStore.getState() - // Only set held ref if gatling is unlocked (for continuous fire) - if (shipStats.gatlingGuns) { - spaceHeldRef.current = true - } - // Fire side cannons on initial press only - fireCannon() - } - } - - const handleKeyUp = (e: KeyboardEvent) => { - if (e.code === 'ArrowUp' || e.code === 'KeyW') { - setMovingForward(false) - } - if (e.code === 'ArrowDown' || e.code === 'KeyS') { - setMovingBackward(false) - } - if (e.code === 'ArrowLeft' || e.code === 'KeyA') { - setTurningLeft(false) - } - if (e.code === 'ArrowRight' || e.code === 'KeyD') { - setTurningRight(false) - } - if (e.code === 'Space') { - spaceHeldRef.current = false - } - } - - window.addEventListener('keydown', handleKeyDown) - window.addEventListener('keyup', handleKeyUp) - - return () => { - window.removeEventListener('keydown', handleKeyDown) - window.removeEventListener('keyup', handleKeyUp) - spaceHeldRef.current = false - } - }, [setMovingForward, setMovingBackward, setTurningLeft, setTurningRight]) - - // Physics update - useFrame((_, delta) => { - // Read all volatile state directly from store to avoid re-renders - const { - phase, - boatPosition, - boatRotation, - boatVelocity, - isMovingForward, - isMovingBackward, - isTurningLeft, - isTurningRight, - islands, - expandedIslands, - stage, - rockColliders, - coins, - coinsCollected, - collectCoin, - shipStats, - fireGatling, - speedBoostEndTime, - } = useGameStore.getState() - - if (phase !== 'playing') return - - // Combine islands for collision in battle stage (includes partner islands) - const allIslands = - stage === 'battle' ? [...islands, ...expandedIslands] : islands - - // Fire gatling while space is held (if unlocked) - if (spaceHeldRef.current && shipStats.gatlingGuns) { - fireGatling() - } - - const dt = Math.min(delta, 0.1) - - // Calculate max speeds based on coins collected - const hasSpeedBoost = !!( - speedBoostEndTime && Date.now() < speedBoostEndTime - ) - const maxForwardSpeed = getMaxSpeed(coinsCollected, false, hasSpeedBoost) - const maxReverseSpeed = getMaxSpeed(coinsCollected, true, hasSpeedBoost) - - // Check for pointer-based controls - const pointer = getPointerState() - - let newRotation = boatRotation - let newVelocity = boatVelocity - - if (pointer.active) { - // Pointer is down - always accelerate forward - newVelocity = Math.min(newVelocity + ACCELERATION, maxForwardSpeed) - - // Calculate target angle and turn toward it - const targetAngle = getTargetAngleFromPointer(pointer.x, pointer.y) - const angleDiff = angleDifference(targetAngle, boatRotation) - const angleDiffDeg = Math.abs(angleDiff) * (180 / Math.PI) - - // Thresholds - const stopThreshold = 1 // degrees - stop turning - const slowThreshold = 10 // degrees - start slowing turn - - if (angleDiffDeg > stopThreshold) { - // Calculate turn rate - full speed far away, slower when close - let turnMultiplier = 1 - if (angleDiffDeg < slowThreshold) { - // Lerp from 0.2 to 1 based on angle - turnMultiplier = 0.2 + 0.8 * (angleDiffDeg / slowThreshold) - } - - // Turn toward target - const turnAmount = TURN_SPEED * turnMultiplier * dt - if (angleDiff > 0) { - newRotation += Math.min(turnAmount, angleDiff) - } else { - newRotation -= Math.min(turnAmount, -angleDiff) - } - } - } else { - // Keyboard controls - if (isTurningLeft) { - newRotation += TURN_SPEED * dt - } - if (isTurningRight) { - newRotation -= TURN_SPEED * dt - } - - // Acceleration / deceleration - if (isMovingForward) { - newVelocity = Math.min(newVelocity + ACCELERATION, maxForwardSpeed) - } else if (isMovingBackward) { - newVelocity = Math.max(newVelocity - ACCELERATION, -maxReverseSpeed) - } else { - // Apply drag - newVelocity *= DRAG - if (Math.abs(newVelocity) < 0.01) newVelocity = 0 - } - } - - // Check for coin collection - for (const coin of coins) { - if (coin.collected) continue - const dx = boatPosition[0] - coin.position[0] - const dz = boatPosition[2] - coin.position[2] - const dist = Math.sqrt(dx * dx + dz * dz) - if (dist < COIN_COLLECT_RADIUS) { - collectCoin(coin.id) - } - } - - // Movement - const moveX = Math.sin(newRotation) * newVelocity * dt - const moveZ = Math.cos(newRotation) * newVelocity * dt - - let newX = boatPosition[0] + moveX - let newZ = boatPosition[2] + moveZ - - // Check island collision - apply gentle repulsion (includes partner islands) - const islandCollision = checkIslandCollision( - newX, - newZ, - allIslands, - BOAT_RADIUS, - ) - if (islandCollision.collides) { - newX += islandCollision.pushX - newZ += islandCollision.pushZ - // Gradually slow down when colliding - newVelocity *= 0.92 - } - - // Check rock collision - apply gentle repulsion - const rockCollision = checkRockCollision( - newX, - newZ, - rockColliders, - BOAT_RADIUS, - ) - if (rockCollision.collides) { - newX += rockCollision.pushX - newZ += rockCollision.pushZ - // Gradually slow down when colliding - newVelocity *= 0.88 - } - - // Second pass - check again after push to prevent getting stuck - const islandCollision2 = checkIslandCollision( - newX, - newZ, - allIslands, - BOAT_RADIUS, - ) - if (islandCollision2.collides) { - newX += islandCollision2.pushX * 0.5 - newZ += islandCollision2.pushZ * 0.5 - } - - const rockCollision2 = checkRockCollision( - newX, - newZ, - rockColliders, - BOAT_RADIUS, - ) - if (rockCollision2.collides) { - newX += rockCollision2.pushX * 0.5 - newZ += rockCollision2.pushZ * 0.5 - } - - // Get dynamic world boundary from store - const { worldBoundary, boundaryEdges, setBoundaryEdges } = - useGameStore.getState() - - // Clamp to world boundary and detect which edges are hit - const BOUNDARY_THRESHOLD = 2 // How close to boundary to show wall - const atWest = newX <= -worldBoundary + BOUNDARY_THRESHOLD - const atEast = newX >= worldBoundary - BOUNDARY_THRESHOLD - const atSouth = newZ <= -worldBoundary + BOUNDARY_THRESHOLD - const atNorth = newZ >= worldBoundary - BOUNDARY_THRESHOLD - - // Update boundary edges if changed - if ( - boundaryEdges.north !== atNorth || - boundaryEdges.south !== atSouth || - boundaryEdges.east !== atEast || - boundaryEdges.west !== atWest - ) { - setBoundaryEdges({ - north: atNorth, - south: atSouth, - east: atEast, - west: atWest, - }) - } - - newX = Math.max(-worldBoundary, Math.min(worldBoundary, newX)) - newZ = Math.max(-worldBoundary, Math.min(worldBoundary, newZ)) - - const newPosition: [number, number, number] = [newX, boatPosition[1], newZ] - - // Update state only if changed - if (newRotation !== boatRotation) { - setBoatRotation(newRotation) - } - if (newVelocity !== boatVelocity) { - setBoatVelocity(newVelocity) - } - if (newX !== boatPosition[0] || newZ !== boatPosition[2]) { - setBoatPosition(newPosition) - } - - // Check for nearby islands (uses allIslands which includes partner islands in battle stage) - const nearby = findNearestIsland(newPosition, allIslands, 10) - const { - nearbyIsland, - discoveryProgress, - discoveredIslands, - setDiscoveryProgress, - } = useGameStore.getState() - - if (nearby?.id !== nearbyIsland?.id) { - setNearbyIsland(nearby) - // Reset progress when changing islands - if (discoveryProgress > 0) { - setDiscoveryProgress(0) - } - } - - // Discovery progress - stay near undiscovered island to discover it - const DISCOVERY_RADIUS = 8 // Must be within this distance - const DISCOVERY_TIME = 8 // Seconds to fully discover - - if (nearby && !discoveredIslands.has(nearby.id)) { - const dist = Math.sqrt( - (newPosition[0] - nearby.position[0]) ** 2 + - (newPosition[2] - nearby.position[2]) ** 2, - ) - - if (dist < DISCOVERY_RADIUS) { - // Accumulate progress - const newProgress = Math.min(1, discoveryProgress + dt / DISCOVERY_TIME) - setDiscoveryProgress(newProgress) - - // Discover when progress reaches 100% - if (newProgress >= 1) { - discoverIsland(nearby.id) - setDiscoveryProgress(0) - } - } else { - // Decay progress when outside radius (but slower than gain) - if (discoveryProgress > 0) { - const decayedProgress = Math.max( - 0, - discoveryProgress - dt / (DISCOVERY_TIME * 2), - ) - setDiscoveryProgress(decayedProgress) - } - } - } - }) -} diff --git a/src/components/game/hooks/useDistanceCulling.ts b/src/components/game/hooks/useDistanceCulling.ts deleted file mode 100644 index f0efcd3d2..000000000 --- a/src/components/game/hooks/useDistanceCulling.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { useRef } from 'react' -import { useFrame } from '@react-three/fiber' -import { useGameStore } from './useGameStore' - -// Distance thresholds for different object types -export const CULL_DISTANCES = { - island: 80, - rock: 60, - ship: 100, - detail: 40, // palm trees, shrubs, etc within islands -} - -/** - * Hook that returns whether an object at given position should be rendered - * based on distance from the player's boat. - * - * Uses a ref to avoid re-renders - check .current in useFrame or render. - */ -export function useDistanceCulling( - position: [number, number, number], - maxDistance: number, -) { - const visibleRef = useRef(true) - - useFrame(() => { - const { boatPosition } = useGameStore.getState() - const dx = position[0] - boatPosition[0] - const dz = position[2] - boatPosition[2] - const distSq = dx * dx + dz * dz - visibleRef.current = distSq < maxDistance * maxDistance - }) - - return visibleRef -} - -/** - * Batch version - filters an array of positioned objects by distance. - * More efficient than individual hooks for many objects. - */ -export function filterByDistance< - T extends { position: [number, number, number] }, ->( - items: T[], - boatPosition: [number, number, number], - maxDistance: number, -): T[] { - const maxDistSq = maxDistance * maxDistance - return items.filter((item) => { - const dx = item.position[0] - boatPosition[0] - const dz = item.position[2] - boatPosition[2] - return dx * dx + dz * dz < maxDistSq - }) -} diff --git a/src/components/game/scene/AIShips.tsx b/src/components/game/scene/AIShips.tsx deleted file mode 100644 index fd0a7a185..000000000 --- a/src/components/game/scene/AIShips.tsx +++ /dev/null @@ -1,139 +0,0 @@ -import { useRef, useMemo, useState } from 'react' -import { useFrame } from '@react-three/fiber' -import { useGLTF } from '@react-three/drei' -import * as THREE from 'three' -import { useGameStore } from '../hooks/useGameStore' -import { CULL_DISTANCES } from '../hooks/useDistanceCulling' -import { getWaveHeight } from './Ocean' - -interface AIShipProps { - id: string - color: string -} - -function AIShip({ id, color }: AIShipProps) { - const groupRef = useRef(null) - const { scene } = useGLTF('/models/ship.glb') - - const clonedScene = useMemo(() => { - const clone = scene.clone() - const tintColor = new THREE.Color(color) - - clone.traverse((child) => { - if (child instanceof THREE.Mesh) { - child.castShadow = true - child.receiveShadow = true - - if (child.material) { - child.material = child.material.clone() - const mat = child.material as THREE.MeshStandardMaterial - mat.color.multiply(tintColor) - - if (mat.map) { - mat.map.minFilter = THREE.LinearMipmapLinearFilter - mat.map.magFilter = THREE.LinearFilter - mat.map.generateMipmaps = true - mat.map.anisotropy = 16 - mat.map.needsUpdate = true - } - } - } - }) - return clone - }, [scene, color]) - - useFrame((state) => { - const { otherPlayers } = useGameStore.getState() - const player = otherPlayers.find((p) => p.id === id) - - if (!player || !groupRef.current) return - - const time = state.clock.elapsedTime - const [px, _py, pz] = player.position - - const waveY = getWaveHeight(px, pz, time) - const bobY = Math.sin(time * 1.8 + px * 0.1) * 0.03 - const bobRoll = Math.sin(time * 1.5 + pz * 0.1) * 0.03 - const bobPitch = Math.sin(time * 2.2) * 0.02 - - const waveTiltX = getWaveHeight(px + 0.3, pz, time) - waveY - const waveTiltZ = getWaveHeight(px, pz + 0.3, time) - waveY - - groupRef.current.position.set(px, waveY + bobY + 0.2, pz) - groupRef.current.rotation.set( - bobPitch + waveTiltZ * 0.4, - player.rotation, - bobRoll + waveTiltX * 0.4, - ) - }) - - return ( - - - {/* Simple cannon on side */} - - - - - - - - - - - - ) -} - -export function AIShips() { - const { stage, otherPlayers } = useGameStore() - const [visibleIds, setVisibleIds] = useState>(() => new Set()) - - // Distance culling for AI ships - useFrame(() => { - const { boatPosition, otherPlayers } = useGameStore.getState() - const maxDistSq = CULL_DISTANCES.ship * CULL_DISTANCES.ship - - const newVisible = new Set() - for (const player of otherPlayers) { - if (!player.isAI) continue - const dx = player.position[0] - boatPosition[0] - const dz = player.position[2] - boatPosition[2] - if (dx * dx + dz * dz < maxDistSq) { - newVisible.add(player.id) - } - } - - if ( - newVisible.size !== visibleIds.size || - [...newVisible].some((id) => !visibleIds.has(id)) - ) { - setVisibleIds(newVisible) - } - }) - - // Only render in battle stage - if (stage !== 'battle') return null - - const aiPlayers = otherPlayers.filter((p) => p.isAI && visibleIds.has(p.id)) - - return ( - <> - {aiPlayers.map((player) => ( - - ))} - - ) -} diff --git a/src/components/game/scene/BeachChair.tsx b/src/components/game/scene/BeachChair.tsx deleted file mode 100644 index 647e52f09..000000000 --- a/src/components/game/scene/BeachChair.tsx +++ /dev/null @@ -1,94 +0,0 @@ -import { useMemo } from 'react' -import * as THREE from 'three' - -interface BeachChairProps { - position?: [number, number, number] - rotation?: number - color?: string -} - -export function BeachChair({ - position = [0, 0, 0], - rotation = 0, - color = '#DC143C', // Cherry red -}: BeachChairProps) { - const woodColor = '#D97706' - - const seatGeometry = useMemo(() => { - return new THREE.BoxGeometry(0.6, 0.05, 0.8) - }, []) - - const backGeometry = useMemo(() => { - return new THREE.BoxGeometry(0.6, 0.6, 0.05) - }, []) - - return ( - - {/* Frame legs - back */} - - - - - - - - - - {/* Frame legs - front */} - - - - - - - - - - {/* Seat (angled) */} - - - - - {/* Back rest (angled) */} - - - - - {/* Stripes on seat */} - {[-0.15, 0.15].map((x, i) => ( - - - - - ))} - - {/* Stripes on back */} - {[-0.15, 0.15].map((x, i) => ( - - - - - ))} - - ) -} diff --git a/src/components/game/scene/Boat.tsx b/src/components/game/scene/Boat.tsx deleted file mode 100644 index a51905435..000000000 --- a/src/components/game/scene/Boat.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { useGameStore } from '../hooks/useGameStore' -import { Dinghy } from './Dinghy' -import { Ship } from './Ship' - -interface BoatProps { - color?: string -} - -export function Boat({ color = '#FFEEDD' }: BoatProps) { - const { boatType } = useGameStore() - - if (boatType === 'dinghy') { - return - } - - return -} diff --git a/src/components/game/scene/BoundaryWalls.tsx b/src/components/game/scene/BoundaryWalls.tsx deleted file mode 100644 index 7b80f8cc6..000000000 --- a/src/components/game/scene/BoundaryWalls.tsx +++ /dev/null @@ -1,89 +0,0 @@ -import { useRef } from 'react' -import { useFrame } from '@react-three/fiber' -import * as THREE from 'three' -import { useGameStore } from '../hooks/useGameStore' - -const PLANE_SIZE = 100 // How far the boundary plane extends outward -const PLANE_OPACITY = 0.6 - -type Edge = 'north' | 'south' | 'east' | 'west' - -interface BoundaryPlaneProps { - edge: Edge -} - -function BoundaryPlane({ edge }: BoundaryPlaneProps) { - const meshRef = useRef(null) - - useFrame((_, delta) => { - if (!meshRef.current) return - const material = meshRef.current.material as THREE.MeshBasicMaterial - const { boundaryEdges, worldBoundary, phase } = useGameStore.getState() - - // Hide when not playing - if (phase !== 'playing') { - meshRef.current.visible = false - return - } - - const active = boundaryEdges[edge] - - // Fade in/out - const targetOpacity = active ? PLANE_OPACITY : 0 - material.opacity = THREE.MathUtils.lerp( - material.opacity, - targetOpacity, - delta * 6, - ) - meshRef.current.visible = material.opacity > 0.01 - - // Update position based on dynamic world boundary - const planeWidth = worldBoundary * 2 + PLANE_SIZE * 2 - const planeY = 0.5 - - if (edge === 'north') { - meshRef.current.position.set(0, planeY, worldBoundary + PLANE_SIZE / 2) - meshRef.current.scale.set(planeWidth / 100, PLANE_SIZE / 100, 1) - } else if (edge === 'south') { - meshRef.current.position.set(0, planeY, -worldBoundary - PLANE_SIZE / 2) - meshRef.current.scale.set(planeWidth / 100, PLANE_SIZE / 100, 1) - } else if (edge === 'east') { - meshRef.current.position.set(worldBoundary + PLANE_SIZE / 2, planeY, 0) - meshRef.current.scale.set(PLANE_SIZE / 100, planeWidth / 100, 1) - } else { - meshRef.current.position.set(-worldBoundary - PLANE_SIZE / 2, planeY, 0) - meshRef.current.scale.set(PLANE_SIZE / 100, planeWidth / 100, 1) - } - }) - - return ( - - - - - ) -} - -export function BoundaryWalls() { - // Read phase inside useFrame to avoid re-renders - // Component always renders, but planes check phase internally - return ( - - - - - - - ) -} diff --git a/src/components/game/scene/Cannonballs.tsx b/src/components/game/scene/Cannonballs.tsx deleted file mode 100644 index 2b567724d..000000000 --- a/src/components/game/scene/Cannonballs.tsx +++ /dev/null @@ -1,235 +0,0 @@ -import { useRef } from 'react' -import { useFrame } from '@react-three/fiber' -import * as THREE from 'three' -import { useGameStore } from '../hooks/useGameStore' - -const CANNONBALL_RADIUS = 0.15 -const GRAVITY = -15 -const MAX_LIFETIME = 3000 // 3 seconds -const HIT_RADIUS = 1.5 // Collision radius for hitting ships - -// Shared geometry and material for performance -const ballGeometry = new THREE.SphereGeometry(CANNONBALL_RADIUS, 12, 12) -const ballMaterial = new THREE.MeshStandardMaterial({ - color: '#333333', - metalness: 0.8, - roughness: 0.3, -}) - -function Cannonball({ id }: { id: number }) { - const meshRef = useRef(null) - - useFrame(() => { - const { cannonballs } = useGameStore.getState() - const ball = cannonballs.find((c) => c.id === id) - - if (!ball || !meshRef.current) return - - meshRef.current.position.set(...ball.position) - }) - - return ( - - ) -} - -// Smoke/splash effect when cannonball lands -function SplashEffect({ - position, - onComplete, -}: { - position: [number, number, number] - onComplete: () => void -}) { - const groupRef = useRef(null) - // eslint-disable-next-line react-hooks/purity - const startTime = useRef(Date.now()) - - useFrame(() => { - if (!groupRef.current) return - - const elapsed = Date.now() - startTime.current - const progress = elapsed / 500 // 500ms animation - - if (progress >= 1) { - onComplete() - return - } - - // Expand and fade - const scale = 1 + progress * 2 - groupRef.current.scale.set(scale, scale, scale) - groupRef.current.children.forEach((child) => { - if (child instanceof THREE.Mesh) { - const mat = child.material as THREE.MeshBasicMaterial - mat.opacity = 1 - progress - } - }) - }) - - return ( - - - - - - - ) -} - -export function Cannonballs() { - const { stage, cannonballs } = useGameStore() - const splashEffects = useRef< - Array<{ id: number; position: [number, number, number] }> - >([]) - - // Physics update for all cannonballs - useFrame((_, delta) => { - if (stage !== 'battle') return - - const { - cannonballs, - updateCannonballs, - removeCannonball: _removeCannonball, - otherPlayers, - setOtherPlayers, - } = useGameStore.getState() - - const now = Date.now() - const dt = Math.min(delta, 0.1) - const updatedBalls = [] - const hitsToProcess: Array<{ ballId: number; playerId: string }> = [] - - for (const ball of cannonballs) { - // Check lifetime - if (now - ball.createdAt > MAX_LIFETIME) { - continue // Remove old cannonballs - } - - // Update position - const newX = ball.position[0] + ball.velocity[0] * dt - const newY = ball.position[1] + ball.velocity[1] * dt - const newZ = ball.position[2] + ball.velocity[2] * dt - - // Apply gravity to Y velocity - const newVelY = ball.velocity[1] + GRAVITY * dt - - // Check if hit water - if (newY <= 0) { - // Create splash effect - splashEffects.current.push({ - id: ball.id, - position: [newX, 0.1, newZ], - }) - continue // Remove cannonball - } - - // Check collision with AI ships (player cannonballs) - if (ball.ownerId === 'player') { - for (const player of otherPlayers) { - const dx = newX - player.position[0] - const dz = newZ - player.position[2] - const dist = Math.sqrt(dx * dx + dz * dz) - - if (dist < HIT_RADIUS && newY < 2) { - hitsToProcess.push({ ballId: ball.id, playerId: player.id }) - splashEffects.current.push({ - id: ball.id, - position: [newX, 0.5, newZ], - }) - break - } - } - } - - // Check collision with player (AI cannonballs) - if (ball.ownerId !== 'player') { - const { boatPosition } = useGameStore.getState() - const dx = newX - boatPosition[0] - const dz = newZ - boatPosition[2] - const dist = Math.sqrt(dx * dx + dz * dz) - - if (dist < HIT_RADIUS && newY < 2) { - hitsToProcess.push({ ballId: ball.id, playerId: 'player' }) - splashEffects.current.push({ - id: ball.id, - position: [newX, 0.5, newZ], - }) - } - } - - // Check if this ball was hit - if (hitsToProcess.some((h) => h.ballId === ball.id)) { - continue - } - - updatedBalls.push({ - ...ball, - position: [newX, newY, newZ] as [number, number, number], - velocity: [ball.velocity[0], newVelY, ball.velocity[2]] as [ - number, - number, - number, - ], - }) - } - - // Process hits - damage AI ships and player - if (hitsToProcess.length > 0) { - const { boatHealth, setPhase } = useGameStore.getState() - - // Check for player hit - const playerHit = hitsToProcess.find((h) => h.playerId === 'player') - if (playerHit) { - const newHealth = Math.max(0, boatHealth - 20) - useGameStore.setState({ boatHealth: newHealth }) - - // Check for game over - if (newHealth <= 0) { - setPhase('gameover') - } - } - - // Process AI hits - const updatedPlayers = otherPlayers.map((player) => { - const hit = hitsToProcess.find((h) => h.playerId === player.id) - if (hit) { - const newHealth = player.health - 25 // 25 damage per hit - return { ...player, health: Math.max(0, newHealth) } - } - return player - }) - // Remove dead ships - setOtherPlayers(updatedPlayers.filter((p) => p.health > 0)) - } - - updateCannonballs(updatedBalls) - }) - - if (stage !== 'battle') return null - - return ( - <> - {cannonballs.map((ball) => ( - - ))} - {/* eslint-disable-next-line react-hooks/refs */} - {splashEffects.current.map((splash) => ( - { - splashEffects.current = splashEffects.current.filter( - (s) => s.id !== splash.id, - ) - }} - /> - ))} - - ) -} diff --git a/src/components/game/scene/Coin.tsx b/src/components/game/scene/Coin.tsx deleted file mode 100644 index e78a208f1..000000000 --- a/src/components/game/scene/Coin.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import { useRef } from 'react' -import { useFrame } from '@react-three/fiber' -import * as THREE from 'three' - -interface CoinProps { - position: [number, number, number] - id: number -} - -// Shared geometry and material for all coins -const coinGeometry = new THREE.CylinderGeometry(0.35, 0.35, 0.08, 12) -const coinMaterial = new THREE.MeshStandardMaterial({ - color: '#FFD700', - metalness: 0.8, - roughness: 0.3, - emissive: '#FF8C00', - emissiveIntensity: 0.4, -}) - -export function Coin({ position, id }: CoinProps) { - const meshRef = useRef(null) - - useFrame((state) => { - if (meshRef.current) { - const t = state.clock.elapsedTime - meshRef.current.rotation.y = t * 2 - meshRef.current.position.y = - position[1] + Math.sin(t * 2 + id * 0.5) * 0.15 - } - }) - - return ( - - ) -} diff --git a/src/components/game/scene/Dinghy.tsx b/src/components/game/scene/Dinghy.tsx deleted file mode 100644 index fc132b8b0..000000000 --- a/src/components/game/scene/Dinghy.tsx +++ /dev/null @@ -1,169 +0,0 @@ -import { useRef, useMemo } from 'react' -import { useFrame } from '@react-three/fiber' -import { useGLTF } from '@react-three/drei' -import * as THREE from 'three' -import { useGameStore } from '../hooks/useGameStore' -import { getWaveHeight } from './Ocean' - -interface DinghyProps { - color?: string -} - -export function Dinghy({ color = '#FFF5E6' }: DinghyProps) { - const groupRef = useRef(null) - const wakeRef = useRef(null) - - const { scene } = useGLTF('/models/rowboat.glb') - - const clonedScene = useMemo(() => { - const clone = scene.clone() - const tintColor = new THREE.Color(color) - - clone.traverse((child) => { - // Hide cannon parts - the rowboat model has a cannon we don't want for early game - const name = child.name.toLowerCase() - if (name.includes('cannon') || name.includes('gun')) { - child.visible = false - return - } - - if (child instanceof THREE.Mesh) { - child.castShadow = true - child.receiveShadow = true - - if (child.material) { - child.material = child.material.clone() - const mat = child.material as THREE.MeshStandardMaterial - mat.color.multiply(tintColor) - - if (mat.map) { - mat.map.minFilter = THREE.LinearMipmapLinearFilter - mat.map.magFilter = THREE.LinearFilter - mat.map.generateMipmaps = true - mat.map.anisotropy = 16 - mat.map.needsUpdate = true - } - } - } - }) - return clone - }, [scene, color]) - - // Wake particles - const wakeParticles = useMemo(() => { - const count = 60 - const positions = new Float32Array(count * 3) - const sizes = new Float32Array(count) - - for (let i = 0; i < count; i++) { - positions[i * 3] = 0 - positions[i * 3 + 1] = 0 - positions[i * 3 + 2] = 0 - sizes[i] = 0 - } - - const geometry = new THREE.BufferGeometry() - geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3)) - geometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1)) - - return geometry - }, []) - - // Animate dinghy with waves, wake, and paddles - useFrame((state) => { - const { boatPosition, boatRotation, boatVelocity } = useGameStore.getState() - - if (groupRef.current) { - const time = state.clock.elapsedTime - - // Wave height at boat position - const waveY = getWaveHeight(boatPosition[0], boatPosition[2], time) - - // More pronounced bobbing for small boat - const bobY = Math.sin(time * 2.2) * 0.05 - const bobRoll = Math.sin(time * 1.8) * 0.06 - const bobPitch = Math.sin(time * 2.5) * 0.04 - - // Wave-based tilting - const waveTiltX = - getWaveHeight(boatPosition[0] + 0.2, boatPosition[2], time) - waveY - const waveTiltZ = - getWaveHeight(boatPosition[0], boatPosition[2] + 0.2, time) - waveY - - groupRef.current.position.set( - boatPosition[0], - waveY + bobY + 0.15, - boatPosition[2], - ) - groupRef.current.rotation.set( - bobPitch + waveTiltZ * 0.5, - boatRotation, - bobRoll + waveTiltX * 0.5, - ) - } - - // Update wake particles - if (wakeRef.current) { - const positions = wakeRef.current.geometry.attributes - .position as THREE.BufferAttribute - const sizes = wakeRef.current.geometry.attributes - .size as THREE.BufferAttribute - - // Shift all particles back - for (let i = positions.count - 1; i > 0; i--) { - positions.setXYZ( - i, - positions.getX(i - 1), - positions.getY(i - 1) - 0.002, - positions.getZ(i - 1), - ) - const currentSize = sizes.getX(i - 1) - sizes.setX(i, currentSize > 0.01 ? currentSize * 0.99 : 0) - } - - // Add new particles when moving (every 4th frame) - if (boatVelocity > 0.05 && Math.random() < 0.25) { - const backOffset = 0.5 - const spread = (Math.random() - 0.5) * 0.3 - - const newX = - boatPosition[0] - - Math.sin(boatRotation) * backOffset + - Math.cos(boatRotation) * spread - const newZ = - boatPosition[2] - - Math.cos(boatRotation) * backOffset - - Math.sin(boatRotation) * spread - - positions.setXYZ(0, newX, -0.35, newZ) - sizes.setX(0, 0.12 + boatVelocity * 0.08) - } else { - positions.setXYZ(0, boatPosition[0], -10, boatPosition[2]) - sizes.setX(0, 0) - } - - positions.needsUpdate = true - sizes.needsUpdate = true - } - }) - - return ( - <> - - {/* Rowboat model */} - - - - {/* Wake/splash particles */} - - - - - ) -} diff --git a/src/components/game/scene/Flag.tsx b/src/components/game/scene/Flag.tsx deleted file mode 100644 index 3b583a431..000000000 --- a/src/components/game/scene/Flag.tsx +++ /dev/null @@ -1,288 +0,0 @@ -import { useRef, useState, useMemo } from 'react' -import { useFrame } from '@react-three/fiber' -import * as THREE from 'three' -import { useGameStore } from '../hooks/useGameStore' - -interface FlagProps { - position: [number, number, number] - color: string - libraryId?: string - partnerId?: string - partnerHref?: string - islandId: string -} - -interface ConfettiParticle { - position: THREE.Vector3 - velocity: THREE.Vector3 - rotation: THREE.Euler - rotationSpeed: THREE.Vector3 - scale: number - color: string - lifetime: number -} - -const POLE_HEIGHT = 2.5 -const FLAG_HEIGHT = 0.5 -const FLAG_WIDTH = 0.7 - -export function Flag({ - position, - color, - libraryId, - partnerId: _partnerId, - partnerHref, - islandId, -}: FlagProps) { - const groupRef = useRef(null) - const flagGroupRef = useRef(null) - - // Animation state - const scaleRef = useRef(0) - const scaleVelocityRef = useRef(0) - const flagPositionRef = useRef(0) // 0 = bottom, 1 = top - const completionScaleRef = useRef(1) - const wasDiscoveredRef = useRef(false) - - // Confetti - const [confetti, setConfetti] = useState([]) - const confettiSpawnedRef = useRef(false) - - const [hovered, setHovered] = useState(false) - - // Create isoceles triangle geometry for flag - // Long edge on left (touching pole), point on right (centered vertically) - const flagGeometry = useMemo(() => { - const shape = new THREE.Shape() - // Top-left corner (on pole, top of flag) - shape.moveTo(0, FLAG_HEIGHT / 2) - // Point on right (centered vertically) - shape.lineTo(FLAG_WIDTH, 0) - // Bottom-left corner (on pole, bottom of flag) - shape.lineTo(0, -FLAG_HEIGHT / 2) - // Close back to start (this draws the long edge on the pole) - shape.closePath() - - const geo = new THREE.ShapeGeometry(shape) - geo.computeVertexNormals() - return geo - }, []) - - const handleClick = () => { - if (partnerHref) { - window.open(partnerHref, '_blank') - } else if (libraryId) { - window.location.href = `/${libraryId}` - } - } - - // Generate confetti colors based on flag color - const confettiColors = useMemo(() => { - const base = new THREE.Color(color) - const hsl = { h: 0, s: 0, l: 0 } - base.getHSL(hsl) - return [ - color, - '#FFFFFF', - `#${new THREE.Color().setHSL((hsl.h + 0.1) % 1, 0.8, 0.6).getHexString()}`, - `#${new THREE.Color().setHSL((hsl.h - 0.1 + 1) % 1, 0.8, 0.6).getHexString()}`, - '#FFD700', - ] - }, [color]) - - const spawnConfetti = () => { - const particles: ConfettiParticle[] = [] - const spawnPos = new THREE.Vector3(0, POLE_HEIGHT - 0.3, 0) - - for (let i = 0; i < 30; i++) { - const angle = Math.random() * Math.PI * 2 - const speed = 2 + Math.random() * 3 - const upSpeed = 3 + Math.random() * 2 - - particles.push({ - position: spawnPos - .clone() - .add( - new THREE.Vector3( - (Math.random() - 0.5) * 0.3, - Math.random() * 0.2, - (Math.random() - 0.5) * 0.3, - ), - ), - velocity: new THREE.Vector3( - Math.cos(angle) * speed, - upSpeed, - Math.sin(angle) * speed, - ), - rotation: new THREE.Euler( - Math.random() * Math.PI * 2, - Math.random() * Math.PI * 2, - Math.random() * Math.PI * 2, - ), - rotationSpeed: new THREE.Vector3( - (Math.random() - 0.5) * 10, - (Math.random() - 0.5) * 10, - (Math.random() - 0.5) * 10, - ), - scale: 0.05 + Math.random() * 0.08, - color: - confettiColors[Math.floor(Math.random() * confettiColors.length)], - lifetime: 2 + Math.random(), - }) - } - - setConfetti(particles) - } - - useFrame((_, delta) => { - if (!groupRef.current || !flagGroupRef.current) return - - const { nearbyIsland, discoveryProgress, discoveredIslands } = - useGameStore.getState() - const isNearby = nearbyIsland?.id === islandId - const isDiscovered = discoveredIslands.has(islandId) - - const dt = Math.min(delta, 0.1) - - // Spring animation for initial scale (appears when nearby) - const targetScale = isNearby || isDiscovered ? 1 : 0 - const stiffness = 200 - const damping = 15 - - const displacement = scaleRef.current - targetScale - const springForce = -stiffness * displacement - const dampingForce = -damping * scaleVelocityRef.current - - scaleVelocityRef.current += (springForce + dampingForce) * dt - scaleRef.current += scaleVelocityRef.current * dt - scaleRef.current = Math.max(0, Math.min(1.3, scaleRef.current)) - - // Flag position (rises with discovery progress) - const targetFlagPos = isDiscovered ? 1 : isNearby ? discoveryProgress : 0 - flagPositionRef.current = THREE.MathUtils.lerp( - flagPositionRef.current, - targetFlagPos, - 0.1, - ) - - // Completion scale bump - if (isDiscovered && !wasDiscoveredRef.current) { - wasDiscoveredRef.current = true - completionScaleRef.current = 1.3 // Bump up - - // Spawn confetti - if (!confettiSpawnedRef.current) { - confettiSpawnedRef.current = true - spawnConfetti() - } - } - - // Lerp completion scale back to normal (slightly larger than 1) - const finalCompletionScale = isDiscovered ? 1.1 : 1 - completionScaleRef.current = THREE.MathUtils.lerp( - completionScaleRef.current, - finalCompletionScale, - 0.05, - ) - - // Apply transforms - const finalScale = scaleRef.current * completionScaleRef.current - groupRef.current.scale.setScalar(Math.max(0.001, finalScale)) - - // Position flag along pole (from near bottom to near top) - const flagBottomY = 0.4 // Starting position near bottom - const flagTopY = POLE_HEIGHT - FLAG_HEIGHT / 2 - 0.15 // End position near top (accounting for flag height) - const flagY = - flagBottomY + flagPositionRef.current * (flagTopY - flagBottomY) - flagGroupRef.current.position.y = flagY - - // Update confetti - if (confetti.length > 0) { - const updatedConfetti = confetti - .map((p) => ({ - ...p, - position: p.position - .clone() - .add(p.velocity.clone().multiplyScalar(dt)), - velocity: p.velocity - .clone() - .setY(p.velocity.y - 9.8 * dt) - .multiplyScalar(0.98), - rotation: new THREE.Euler( - p.rotation.x + p.rotationSpeed.x * dt, - p.rotation.y + p.rotationSpeed.y * dt, - p.rotation.z + p.rotationSpeed.z * dt, - ), - lifetime: p.lifetime - dt, - })) - .filter((p) => p.lifetime > 0 && p.position.y > -1) - - setConfetti(updatedConfetti) - } - - // Reset confetti spawned flag when leaving - if (!isNearby && !isDiscovered) { - confettiSpawnedRef.current = false - wasDiscoveredRef.current = false - } - }) - - return ( - - { - setHovered(true) - document.body.style.cursor = 'pointer' - }} - onPointerOut={() => { - setHovered(false) - document.body.style.cursor = 'auto' - }} - > - {/* White pole */} - - - - - - {/* White ball on top */} - - - - - - {/* Flag group (moves up/down) */} - - {/* Isoceles flag - left edge touches pole */} - - - - - - - {/* Confetti particles */} - {confetti.map((particle, i) => ( - - - - - ))} - - ) -} diff --git a/src/components/game/scene/GameScene.tsx b/src/components/game/scene/GameScene.tsx deleted file mode 100644 index 3fc66296b..000000000 --- a/src/components/game/scene/GameScene.tsx +++ /dev/null @@ -1,287 +0,0 @@ -/* eslint-disable react-hooks/set-state-in-effect -- game animation state sync */ -import { useEffect, useRef, useState } from 'react' -import { Canvas, useThree, useFrame } from '@react-three/fiber' -import * as THREE from 'three' -import { Sky } from './Sky' -import { Ocean } from './Ocean' -import { Island } from './Island' -import { Boat } from './Boat' -import { OceanRocks } from './OceanRocks' -import { VirtualizedCoins } from './VirtualizedCoins' -import { BoundaryWalls } from './BoundaryWalls' -import { AIShips } from './AIShips' -import { Cannonballs } from './Cannonballs' -import { useGameStore } from '../hooks/useGameStore' -import { useBoatControls } from '../hooks/useBoatControls' -import { useAIOpponents } from '../hooks/useAIOpponents' -import { IslandInfo3D } from './IslandInfo3D' -import { - generateIslands, - generateExpandedIslands, - type IslandData, -} from '../utils/islandGenerator' -import { generateRockColliders } from '../utils/collision' -import { generateCoins } from '../utils/coinGenerator' -import { publicLibraries } from '~/libraries' -import { partners } from '~/utils/partners' - -// Filter to only active partners and convert to slim format for the game -const ACTIVE_PARTNERS = partners - .filter((p) => p.status === 'active') - .map((p) => ({ - id: p.id, - name: p.name, - href: p.href, - brandColor: p.brandColor, - })) - -// Floating info sign for nearby island with exit animation -function NearbyIslandInfo() { - const nearbyIsland = useGameStore((s) => s.nearbyIsland) - const discoveredIslands = useGameStore((s) => s.discoveredIslands) - const [displayedIsland, setDisplayedIsland] = useState( - null, - ) - const [isExiting, setIsExiting] = useState(false) - const [wasDiscovered, setWasDiscovered] = useState(false) - - // Track if current island is discovered - const isDiscovered = nearbyIsland - ? discoveredIslands.has(nearbyIsland.id) - : false - - useEffect(() => { - if (nearbyIsland) { - // New island - show it - setIsExiting(false) - setDisplayedIsland(nearbyIsland) - setWasDiscovered(discoveredIslands.has(nearbyIsland.id)) - } else if (displayedIsland) { - // Island gone - start exit animation - setIsExiting(true) - const timer = setTimeout(() => { - setDisplayedIsland(null) - setIsExiting(false) - }, 300) - return () => clearTimeout(timer) - } - }, [nearbyIsland?.id]) // eslint-disable-line react-hooks/exhaustive-deps - - // Detect when island gets discovered while we're near it - useEffect(() => { - if (displayedIsland && !wasDiscovered && isDiscovered) { - // Just got discovered - bounce it by remounting - setWasDiscovered(true) - setIsExiting(true) - const timer = setTimeout(() => { - setIsExiting(false) - }, 50) - return () => clearTimeout(timer) - } - }, [isDiscovered, wasDiscovered, displayedIsland]) - - if (!displayedIsland) return null - - // Key includes discovered state to force remount on discovery - const key = `${displayedIsland.id}-${wasDiscovered}` - - return -} - -// Isometric camera that follows the boat -const BASE_FOV = 20 // Narrow FOV for more orthographic feel - -function IsometricCamera() { - const { camera } = useThree() - - // Camera offset - slight asymmetry for less sterile feel - const offset = useRef(new THREE.Vector3(22, 20, 20)) - const targetPosition = useRef(new THREE.Vector3()) - const currentPosition = useRef(new THREE.Vector3(22, 15, 22)) - const currentFov = useRef(BASE_FOV) - - useEffect(() => { - // Set up orthographic-like perspective - if (camera instanceof THREE.PerspectiveCamera) { - // eslint-disable-next-line react-hooks/immutability - camera.fov = BASE_FOV - camera.updateProjectionMatrix() - } - }, [camera]) - - useFrame(() => { - // Read directly from store to avoid component re-renders - const { boatPosition, phase, shipStats } = useGameStore.getState() - if (phase !== 'playing') return - - // Update FOV based on fieldOfView upgrade (higher multiplier = wider FOV = zoomed out) - if (camera instanceof THREE.PerspectiveCamera) { - const targetFov = BASE_FOV * shipStats.fieldOfView - if (Math.abs(currentFov.current - targetFov) > 0.01) { - currentFov.current = THREE.MathUtils.lerp( - currentFov.current, - targetFov, - 0.1, - ) - // eslint-disable-next-line react-hooks/immutability - camera.fov = currentFov.current - camera.updateProjectionMatrix() - } - } - - // Target position follows boat - targetPosition.current.set( - boatPosition[0] + offset.current.x, - offset.current.y, - boatPosition[2] + offset.current.z, - ) - - // Smooth camera follow - currentPosition.current.lerp(targetPosition.current, 0.05) - camera.position.copy(currentPosition.current) - - // Look at boat position - camera.lookAt(boatPosition[0], 0, boatPosition[2]) - }) - - return null -} - -// Scene content (rendered inside Canvas) -function SceneContent() { - // Use local state for islands to trigger single re-render when loaded - const [islands, setLocalIslands] = useState([]) - const [expandedIslands, setLocalExpandedIslands] = useState([]) - - // Initialize game data and get islands - useEffect(() => { - const state = useGameStore.getState() - if (state.islands.length > 0) { - setLocalIslands(state.islands) - return - } - - // Generate islands - const generatedIslands = generateIslands(publicLibraries) - state.setIslands(generatedIslands) - const rockColliders = generateRockColliders(generatedIslands, 30, 140) - state.setRockColliders(rockColliders) - const generatedCoins = generateCoins(generatedIslands) - state.setCoins(generatedCoins) - setLocalIslands(generatedIslands) - }, []) - - // Check for battle stage expansion via interval - useEffect(() => { - const checkBattleStage = () => { - const { stage, expandedIslands, setExpandedIslands } = - useGameStore.getState() - if (stage === 'battle' && expandedIslands.length === 0) { - const partnerIslands = generateExpandedIslands(ACTIVE_PARTNERS) - setExpandedIslands(partnerIslands) - setLocalExpandedIslands(partnerIslands) - } else if (stage === 'battle' && expandedIslands.length > 0) { - // Sync local state with store - setLocalExpandedIslands(expandedIslands) - } - } - - const interval = setInterval(checkBattleStage, 500) - return () => clearInterval(interval) - }, []) - - // Enable boat controls - useBoatControls() - - // Enable AI opponents in battle stage - useAIOpponents() - - return ( - <> - {/* Camera */} - - - {/* Lighting - soft and warm */} - - - - - - {/* Sky dome */} - - - {/* Ocean */} - - - {/* Ocean rocks scattered around */} - - - {/* Islands - render all without virtualization */} - {islands.map((island) => ( - - ))} - - {/* Partner islands (battle stage) */} - {expandedIslands.map((island) => ( - - ))} - - {/* Virtualized coins */} - - - {/* World boundary indicators */} - - - {/* AI opponent ships */} - - - {/* Cannonballs */} - - - {/* Player boat */} - - - {/* Floating info for nearby discovered island */} - - - ) -} - -export function GameScene() { - return ( - - - - ) -} diff --git a/src/components/game/scene/Island.tsx b/src/components/game/scene/Island.tsx deleted file mode 100644 index 0277013d7..000000000 --- a/src/components/game/scene/Island.tsx +++ /dev/null @@ -1,643 +0,0 @@ -import { useMemo } from 'react' -import * as THREE from 'three' -import { COLORS, getLibraryColor } from '../utils/colors' -import type { IslandData } from '../utils/islandGenerator' -import { PalmTree } from './PalmTree' -import { BeachChair } from './BeachChair' -import { TikiShack } from './TikiShack' -import { Flag } from './Flag' -import { IslandLobe } from './IslandLobe' - -interface IslandProps { - data: IslandData - isDiscovered: boolean -} - -function seededRandom(seed: number) { - const x = Math.sin(seed) * 10000 - return x - Math.floor(x) -} - -export function Island({ data, isDiscovered }: IslandProps) { - const { - position, - rotation, - scale, - library, - partner, - palmCount, - hasCoconuts, - hasTikiShack, - elongation, - lobes, - } = data - - // Get color based on island type - const libraryColor = - data.type === 'library' && library - ? getLibraryColor(library.id) - : data.type === 'partner' && partner?.brandColor - ? partner.brandColor - : data.type === 'partner' - ? '#f59e0b' // Fallback amber for partners without brandColor - : '#8b5cf6' // Purple for showcase - - // Get ID for seeding - const seedId = library?.id ?? partner?.id ?? data.id - - // Sphere radius - island is top 5% of this sphere - const sphereRadius = 8 - const islandRadius = 2.2 * elongation - - // Height where sphere surface meets the water - const surfaceHeight = Math.sqrt( - sphereRadius * sphereRadius - islandRadius * islandRadius, - ) - const sphereCenterY = -surfaceHeight + 0.3 // Slight offset above water - - // Generate consistent layout - objects sit on top of sphere - const layout = useMemo(() => { - const seed = seedId.split('').reduce((a, c) => a + c.charCodeAt(0), 0) - - // Helper to get Y position on sphere surface given x,z - const getHeightOnSphere = (x: number, z: number) => { - const distFromCenter = Math.sqrt(x * x + z * z) - if (distFromCenter >= sphereRadius) return 0 - return ( - Math.sqrt( - sphereRadius * sphereRadius - distFromCenter * distFromCenter, - ) + sphereCenterY - ) - } - - // Flag exclusion zone - flag is at +X, +Z diagonal (45 degrees) - // We need to check in LOCAL space after accounting for island rotation - const _flagAngle = Math.PI * 0.25 // 45 degrees - const flagRadius = 1.8 - const flagExclusionRadius = 0.6 // Smaller exclusion for flag pole vs old sign - - // Check if a local position is too close to where the flag will be - // Flag is placed in world space at fixed angle, so we need to - // transform local coords to check against flag position - const isNearFlag = (localX: number, localZ: number) => { - // The flag is placed at world +X, +Z regardless of island rotation - // So in local space, we need to rotate backwards by island rotation - const cosR = Math.cos(-rotation) - const sinR = Math.sin(-rotation) - const flagLocalX = flagRadius * 0.707 * cosR + flagRadius * 0.707 * sinR - const flagLocalZ = -flagRadius * 0.707 * sinR + flagRadius * 0.707 * cosR - - const dx = localX - flagLocalX - const dz = localZ - flagLocalZ - return Math.sqrt(dx * dx + dz * dz) < flagExclusionRadius - } - - // Palm tree positions - avoid sign zone - const palmTints = ['#AAFFAA', '#CCFFCC', '#88FF88', '#BBFFBB', '#99FF99'] - const palmPositions: Array<{ - pos: [number, number, number] - scale: number - hasCoconuts: boolean - tint: string - }> = [] - for (let i = 0; i < palmCount; i++) { - let attempts = 0 - let x: number, z: number, angle: number, radius: number - - // Try to find a position not near the sign - do { - angle = seededRandom(seed + i * 100 + attempts * 7) * Math.PI * 2 - radius = 0.5 + seededRandom(seed + i * 101 + attempts * 7) * 1.2 - x = Math.cos(angle) * radius - z = Math.sin(angle) * radius - attempts++ - } while (isNearFlag(x, z) && attempts < 10) - - const y = getHeightOnSphere(x, z) - const tintIndex = Math.floor( - seededRandom(seed + i * 103) * palmTints.length, - ) - palmPositions.push({ - pos: [x, y, z], - scale: 0.5 + seededRandom(seed + i * 102) * 0.3, - hasCoconuts: i === 0 && hasCoconuts, - tint: palmTints[tintIndex], - }) - } - - // Beach chair position - on the sand ring, avoid sign zone - let chairAngle = seededRandom(seed + 200) * Math.PI * 2 - const chairRadius = 2.0 + seededRandom(seed + 201) * 0.5 - let chairX = Math.cos(chairAngle) * chairRadius - let chairZ = Math.sin(chairAngle) * chairRadius - - // If chair is near sign, move it to opposite side - if (isNearFlag(chairX, chairZ)) { - chairAngle += Math.PI // Flip to opposite side - chairX = Math.cos(chairAngle) * chairRadius - chairZ = Math.sin(chairAngle) * chairRadius - } - - const chairPos: [number, number, number] = [ - chairX, - getHeightOnSphere(chairX, chairZ), - chairZ, - ] - const chairRotation = chairAngle + Math.PI * 0.8 - - // Sign position - computed in local island space - // Will be transformed to world space separately - const signLocalRadius = 1.6 - const signLocalX = signLocalRadius - const signLocalZ = signLocalRadius - const signLocalY = getHeightOnSphere(signLocalX, signLocalZ) - - // Tiki shack near center (center is always safe from sign) - const shackX = (seededRandom(seed + 400) - 0.5) * 0.8 - const shackZ = (seededRandom(seed + 401) - 0.5) * 0.8 - const shackPos: [number, number, number] = [ - shackX, - getHeightOnSphere(shackX, shackZ), - shackZ, - ] - const shackRotation = seededRandom(seed + 402) * Math.PI * 2 - - return { - palmPositions, - chairPos, - chairRotation, - signLocalX, - signLocalZ, - signLocalY, - shackPos, - shackRotation, - getHeightOnSphere, - isNearFlag, - } - }, [seedId, palmCount, hasCoconuts, sphereRadius, sphereCenterY, rotation]) - - // Compute sign world position - always on +X, +Z side (toward camera) - // This is independent of island rotation - const signWorldPos: [number, number, number] = (() => { - const signRadius = 1.8 - // Fixed direction toward camera (+X, +Z diagonal) - const signOffsetX = signRadius * 0.707 // cos(45°) - const signOffsetZ = signRadius * 0.707 // sin(45°) - // Get height on sphere at this position (need to account for island rotation for height only) - const cosR = Math.cos(rotation) - const sinR = Math.sin(rotation) - // Convert world offset back to local (unscaled) for height calculation - const localX = signOffsetX * cosR + signOffsetZ * sinR - const localZ = -signOffsetX * sinR + signOffsetZ * cosR - const localY = layout.getHeightOnSphere(localX, localZ) - return [ - position[0] + signOffsetX * scale, - position[1] + localY * scale + 0.1, // small lift - position[2] + signOffsetZ * scale, - ] - })() - - // Create spherical cap geometry with vertex colors for foam → sand → grass gradient - const { islandGeometry, rockPositions, shrubPositions, grassTufts } = - useMemo(() => { - const seed = seedId.split('').reduce((a, c) => a + c.charCodeAt(0), 0) - - // Flag exclusion - compute flag local position for this island's rotation - const flagRadiusLocal = 1.8 - const flagExclusionRadiusLocal = 0.5 // Smaller for flag pole - const cosR = Math.cos(-rotation) - const sinR = Math.sin(-rotation) - const flagLocalXCalc = - flagRadiusLocal * 0.707 * cosR + flagRadiusLocal * 0.707 * sinR - const flagLocalZCalc = - -flagRadiusLocal * 0.707 * sinR + flagRadiusLocal * 0.707 * cosR - - const isNearFlagLocal = (x: number, z: number) => { - const dx = x - flagLocalXCalc - const dz = z - flagLocalZCalc - return Math.sqrt(dx * dx + dz * dz) < flagExclusionRadiusLocal - } - // Extend sphere cap further down to include underwater portion - const geo = new THREE.SphereGeometry( - sphereRadius, - 48, - 32, - 0, - Math.PI * 2, - 0, - Math.PI * 0.25, // Larger cap to extend below waterline - ) - - const posAttr = geo.attributes.position - const colors: number[] = [] - - // Define color zones - const foamColor = new THREE.Color('#E8F4F8') // Light foam/white - const shallowColor = new THREE.Color(COLORS.ocean.shallow) // Turquoise underwater - const sandColorLight = new THREE.Color(COLORS.sand.light) - const sandColorMid = new THREE.Color(COLORS.sand.mid) - const grassColorDark = new THREE.Color('#1B5E20') - const grassColorLight = new THREE.Color('#2E7D32') - - // Water level adapts to elongation - larger islands need higher foam threshold - // elongation ~1.0 = small island, ~1.3 = large island - const _waterLevel = 0.38 + (elongation - 1.0) * 0.25 - - // Add irregularity to shoreline and color variation - for (let i = 0; i < posAttr.count; i++) { - const x = posAttr.getX(i) - const y = posAttr.getY(i) - const z = posAttr.getZ(i) - - // Add noise to edge vertices for irregular shoreline - const angle = Math.atan2(z, x) - const distFromCenter = Math.sqrt(x * x + z * z) - const edgeNoise = - Math.sin(angle * 5 + seed) * 0.15 + - Math.sin(angle * 9 + seed * 2) * 0.08 + - Math.sin(angle * 13 + seed * 3) * 0.04 - - // Normalized Y: 0 = bottom of cap (underwater), 1 = top center - const normalizedY = (y - sphereRadius * 0.75) / (sphereRadius * 0.25) - - // Apply irregular edge to shoreline area - if (normalizedY < 0.5 && normalizedY > 0.1 && distFromCenter > 1) { - const noiseAmount = (0.5 - Math.abs(normalizedY - 0.3)) * 0.4 - posAttr.setX( - i, - x + - (x / distFromCenter) * - edgeNoise * - noiseAmount * - distFromCenter * - 0.12, - ) - posAttr.setZ( - i, - z + - (z / distFromCenter) * - edgeNoise * - noiseAmount * - distFromCenter * - 0.12, - ) - } - - // Absolute Y height for consistent coloring across all spheres - const absoluteY = y + sphereCenterY - - // Color noise for texture variation - const colorNoise = Math.sin(angle * 7 + seed) * 0.5 + 0.5 - - // Fixed height thresholds (absolute Y coordinates) - // Vertex Y ranges roughly from -1.5 (underwater edge) to 0.7 (top center) - const waterY = -0.6 - const foamY = -0.35 - const sandY = -0.25 - const grassY = 0.0 - - let color: THREE.Color - - if (absoluteY < waterY) { - // Underwater - shallow turquoise - color = shallowColor.clone() - color.lerp(new THREE.Color('#1A8A9A'), colorNoise * 0.2) - } else if (absoluteY < foamY) { - // Foam zone - white/light blue transition - const foamAmount = THREE.MathUtils.smoothstep( - absoluteY, - waterY, - foamY, - ) - color = shallowColor.clone().lerp(foamColor, foamAmount) - // Add sparkle to foam - color.lerp(new THREE.Color('#FFFFFF'), colorNoise * 0.3 * foamAmount) - } else if (absoluteY < sandY) { - // Sand zone - const sandProgress = THREE.MathUtils.smoothstep( - absoluteY, - foamY, - sandY, - ) - // Wet sand near water, dry sand higher up - const wetSand = sandColorLight.clone().lerp(foamColor, 0.15) - color = wetSand.clone().lerp(sandColorMid, sandProgress) - color.lerp( - sandColorMid.clone().multiplyScalar(0.95), - colorNoise * 0.15, - ) - } else { - // Grass zone - const grassProgress = THREE.MathUtils.smoothstep( - absoluteY, - sandY, - grassY, - ) - // Position-based noise for natural grass variation (not angle-based) - const grassNoise = - Math.sin(x * 3.7 + seed) * Math.cos(z * 4.1 + seed * 1.3) * 0.5 + - 0.5 - // Solid base grass with subtle noise variation - const baseGrass = grassColorDark.clone().lerp(grassColorLight, 0.3) - const grassColor = baseGrass - .clone() - .lerp(grassColorDark, grassNoise * 0.25) - color = sandColorMid.clone().lerp(grassColor, grassProgress) - } - - colors.push(color.r, color.g, color.b) - } - - geo.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3)) - geo.computeVertexNormals() - - // Generate rock positions for micro props - avoid sign zone - const rocks: Array<{ - pos: [number, number, number] - scale: number - rotation: number - }> = [] - const numRocks = 2 + Math.floor(seededRandom(seed + 500) * 3) - for (let i = 0; i < numRocks; i++) { - let attempts = 0 - let rx: number, rz: number, rockAngle: number, rockRadius: number - - do { - rockAngle = - seededRandom(seed + 600 + i * 10 + attempts * 7) * Math.PI * 2 - rockRadius = - 1.8 + seededRandom(seed + 601 + i * 10 + attempts * 7) * 0.6 - rx = Math.cos(rockAngle) * rockRadius - rz = Math.sin(rockAngle) * rockRadius - attempts++ - } while (isNearFlagLocal(rx, rz) && attempts < 10) - - const ry = - Math.sqrt( - Math.max(0, sphereRadius * sphereRadius - rx * rx - rz * rz), - ) + - sphereCenterY - - 0.05 - rocks.push({ - pos: [rx, ry, rz], - scale: 0.1 + seededRandom(seed + 602 + i * 10) * 0.15, - rotation: seededRandom(seed + 603 + i * 10) * Math.PI * 2, - }) - } - - // Generate shrub/bush positions on grass area - avoid sign zone - const shrubs: Array<{ - pos: [number, number, number] - scale: number - color: string - }> = [] - const shrubColors = [ - '#2D5A27', - '#3D7A37', - '#1E4620', - '#4A8B44', - '#2E6B28', - ] - const numShrubs = 4 + Math.floor(seededRandom(seed + 700) * 5) - for (let i = 0; i < numShrubs; i++) { - let attempts = 0 - let sx: number, sz: number, shrubAngle: number, shrubRadius: number - - do { - shrubAngle = - seededRandom(seed + 800 + i * 10 + attempts * 7) * Math.PI * 2 - shrubRadius = - 0.3 + seededRandom(seed + 801 + i * 10 + attempts * 7) * 1.0 - sx = Math.cos(shrubAngle) * shrubRadius - sz = Math.sin(shrubAngle) * shrubRadius - attempts++ - } while (isNearFlagLocal(sx, sz) && attempts < 10) - - const sy = - Math.sqrt( - Math.max(0, sphereRadius * sphereRadius - sx * sx - sz * sz), - ) + sphereCenterY - shrubs.push({ - pos: [sx, sy, sz], - scale: 0.08 + seededRandom(seed + 802 + i * 10) * 0.12, - color: - shrubColors[ - Math.floor(seededRandom(seed + 803 + i * 10) * shrubColors.length) - ], - }) - } - - // Generate grass tuft / flower positions - avoid sign zone - const grassTufts: Array<{ - pos: [number, number, number] - scale: number - color: string - }> = [] - const grassColors = ['#4CAF50', '#66BB6A', '#81C784', '#A5D6A7'] - const flowerColors = [ - '#FFEB3B', - '#FF9800', - '#E91E63', - '#9C27B0', - '#FFFFFF', - ] - const numTufts = 6 + Math.floor(seededRandom(seed + 900) * 6) - for (let i = 0; i < numTufts; i++) { - let attempts = 0 - let tx: number, tz: number, tuftAngle: number, tuftRadius: number - - do { - tuftAngle = - seededRandom(seed + 950 + i * 10 + attempts * 7) * Math.PI * 2 - tuftRadius = - 0.4 + seededRandom(seed + 951 + i * 10 + attempts * 7) * 1.3 - tx = Math.cos(tuftAngle) * tuftRadius - tz = Math.sin(tuftAngle) * tuftRadius - attempts++ - } while (isNearFlagLocal(tx, tz) && attempts < 10) - - const ty = - Math.sqrt( - Math.max(0, sphereRadius * sphereRadius - tx * tx - tz * tz), - ) + sphereCenterY - const isFlower = seededRandom(seed + 952 + i * 10) > 0.6 - grassTufts.push({ - pos: [tx, ty, tz], - scale: 0.03 + seededRandom(seed + 953 + i * 10) * 0.04, - color: isFlower - ? flowerColors[ - Math.floor( - seededRandom(seed + 954 + i * 10) * flowerColors.length, - ) - ] - : grassColors[ - Math.floor( - seededRandom(seed + 954 + i * 10) * grassColors.length, - ) - ], - }) - } - - return { - islandGeometry: geo, - rockPositions: rocks, - shrubPositions: shrubs, - grassTufts, - } - }, [sphereRadius, seedId, sphereCenterY, elongation, rotation]) - - const seed = seedId.split('').reduce((a, c) => a + c.charCodeAt(0), 0) - - return ( - <> - - {/* Soft foam edge - gradient ring */} - - - - - - {/* Shallow water ring - turquoise */} - - - - - - {/* Island - spherical cap with gradient */} - - - - - {/* Additional lobes for organic shape */} - {lobes.map((lobe, i) => ( - - ))} - - {/* Palm trees */} - {layout.palmPositions.map((palm, i) => ( - - ))} - - {/* Beach chair */} - - - {/* Tiki shack (conditional) */} - {hasTikiShack && ( - - )} - - {/* Rocks / micro props */} - {rockPositions.map((rock, i) => ( - - - - - ))} - - {/* Shrubs / small plants */} - {shrubPositions.map((shrub, i) => ( - - {/* Main bush - cluster of spheres */} - - - - - {/* Secondary smaller spheres for fullness */} - - - - - - - - - - ))} - - {/* Grass tufts and flowers */} - {grassTufts.map((tuft, i) => ( - - - - - ))} - - {/* Discovery beacon */} - {!isDiscovered && ( - - )} - - - {/* Flag */} - - - ) -} diff --git a/src/components/game/scene/IslandInfo3D.tsx b/src/components/game/scene/IslandInfo3D.tsx deleted file mode 100644 index b6bcdc71a..000000000 --- a/src/components/game/scene/IslandInfo3D.tsx +++ /dev/null @@ -1,258 +0,0 @@ -import { useRef, useState, Suspense } from 'react' -import { useFrame } from '@react-three/fiber' -import { RoundedBoxGeometry, Text } from '@react-three/drei' -import * as THREE from 'three' -import type { IslandData } from '../utils/islandGenerator' -import { getLibraryColor } from '../utils/colors' -import { set3DObjectClicked } from '../ui/TouchControls' -import { trackEvent } from '~/utils/analytics' - -interface IslandInfo3DProps { - island: IslandData - exiting?: boolean -} - -const FRAMEWORK_COLORS: Record = { - react: '#61DAFB', - vue: '#4FC08D', - solid: '#2C4F7C', - svelte: '#FF3E00', - angular: '#DD0031', - lit: '#325CCC', - qwik: '#18B6F6', - preact: '#673AB8', - vanilla: '#F7DF1E', -} - -export function IslandInfo3D({ island, exiting = false }: IslandInfo3DProps) { - const groupRef = useRef(null) - const scaleRef = useRef(0) - const velocityRef = useRef(0) - const [hovered, setHovered] = useState(false) - const { library, partner, position } = island - - const color = - island.type === 'library' && library - ? getLibraryColor(library.id) - : island.type === 'partner' && partner?.brandColor - ? partner.brandColor - : island.type === 'partner' - ? '#f59e0b' - : '#8b5cf6' - - const name = library?.name ?? partner?.name ?? 'Unknown' - const tagline = library?.tagline ?? 'Partner Island' - const isPartner = island.type === 'partner' && !!partner - - const handleClick = () => { - if (partner?.href) { - let destinationHost: string | undefined - try { - destinationHost = new URL(partner.href).host - } catch { - // Bad/relative href — track without host rather than dropping. - } - trackEvent('partner_clicked', { - partner_id: partner.id, - placement: 'ecosystem_game', - destination: 'external', - destination_host: destinationHost, - }) - window.open(partner.href, '_blank') - } else if (library) { - window.location.href = `/${library.id}` - } - } - - useFrame((state, delta) => { - if (groupRef.current) { - const t = state.clock.elapsedTime - - // Spring animation for scale (bounce in/out) - const target = exiting ? 0 : 1 - const stiffness = exiting ? 300 : 180 - const damping = exiting ? 20 : 12 - - const displacement = scaleRef.current - target - const springForce = -stiffness * displacement - const dampingForce = -damping * velocityRef.current - const acceleration = springForce + dampingForce - - velocityRef.current += acceleration * delta - scaleRef.current += velocityRef.current * delta - - // Clamp to prevent overshoot issues - scaleRef.current = Math.max(0, Math.min(1.2, scaleRef.current)) - - groupRef.current.scale.setScalar(scaleRef.current) - - // Bob animation - groupRef.current.position.y = 2.8 + Math.sin(t * 1.5) * 0.1 - } - }) - - const infoPos: [number, number, number] = [ - position[0] + 1, - position[1] + 0.5 + island.scale * 1.5, - position[2] + 1, - ] - - return ( - - set3DObjectClicked()} - onPointerOver={() => { - setHovered(true) - document.body.style.cursor = 'pointer' - }} - onPointerOut={() => { - setHovered(false) - document.body.style.cursor = 'auto' - }} - > - - - - - - - - - - - {/* Name */} - - - {name} - - - - {/* Badge for libraries */} - {library?.badge && ( - - - - - - - - {library.badge.toUpperCase()} - - - - )} - - {/* Tagline */} - - - {hovered - ? isPartner - ? 'Click to visit' - : 'Click to visit docs' - : tagline} - - - - {library?.frameworks && library.frameworks.length > 0 && ( - - {(() => { - const frameworks = library.frameworks!.slice(0, 6) - const gap = 0.08 - const paddingX = 0.12 - const charWidth = 0.1 - const boxHeight = 0.28 - - // Calculate widths for each framework - const widths = frameworks.map((fw) => { - const label = fw.charAt(0).toUpperCase() + fw.slice(1) - return label.length * charWidth + paddingX * 2 - }) - - const totalWidth = - widths.reduce((a, b) => a + b, 0) + - gap * (frameworks.length - 1) - let currentX = -totalWidth / 2 - - return frameworks.map((fw, i) => { - const label = fw.charAt(0).toUpperCase() + fw.slice(1) - const boxWidth = widths[i] - const x = currentX + boxWidth / 2 - currentX += boxWidth + gap - - return ( - - - - - - - - {label} - - - - ) - }) - })()} - - )} - - - ) -} diff --git a/src/components/game/scene/IslandLobe.tsx b/src/components/game/scene/IslandLobe.tsx deleted file mode 100644 index d2975b7a8..000000000 --- a/src/components/game/scene/IslandLobe.tsx +++ /dev/null @@ -1,162 +0,0 @@ -import { useMemo } from 'react' -import * as THREE from 'three' -import { COLORS } from '../utils/colors' - -interface IslandLobeProps { - position: [number, number, number] - scale: number - seed: number - elongation?: number -} - -export function IslandLobe({ - position, - scale, - seed, - elongation = 1, -}: IslandLobeProps) { - const sphereRadius = 8 - const islandRadius = 2.2 * elongation - - const surfaceHeight = Math.sqrt( - sphereRadius * sphereRadius - islandRadius * islandRadius, - ) - const sphereCenterY = -surfaceHeight + 0.3 - - const geometry = useMemo(() => { - const geo = new THREE.SphereGeometry( - sphereRadius, - 32, - 24, - 0, - Math.PI * 2, - 0, - Math.PI * 0.25, - ) - - const posAttr = geo.attributes.position - const colors: number[] = [] - - const foamColor = new THREE.Color('#E8F4F8') - const shallowColor = new THREE.Color(COLORS.ocean.shallow) - const sandColorLight = new THREE.Color(COLORS.sand.light) - const sandColorMid = new THREE.Color(COLORS.sand.mid) - const grassColorDark = new THREE.Color('#1B5E20') - const grassColorLight = new THREE.Color('#2E7D32') - - for (let i = 0; i < posAttr.count; i++) { - const x = posAttr.getX(i) - const y = posAttr.getY(i) - const z = posAttr.getZ(i) - - const angle = Math.atan2(z, x) - const distFromCenter = Math.sqrt(x * x + z * z) - const edgeNoise = - Math.sin(angle * 5 + seed) * 0.15 + - Math.sin(angle * 9 + seed * 2) * 0.08 - - const normalizedY = (y - sphereRadius * 0.75) / (sphereRadius * 0.25) - - if (normalizedY < 0.5 && normalizedY > 0.1 && distFromCenter > 1) { - const noiseAmount = (0.5 - Math.abs(normalizedY - 0.3)) * 0.4 - posAttr.setX( - i, - x + - (x / distFromCenter) * - edgeNoise * - noiseAmount * - distFromCenter * - 0.12, - ) - posAttr.setZ( - i, - z + - (z / distFromCenter) * - edgeNoise * - noiseAmount * - distFromCenter * - 0.12, - ) - } - - // Absolute Y height, scaled to world coordinates for consistent coloring - const absoluteY = (y + sphereCenterY) * scale - - const colorNoise = Math.sin(angle * 7 + seed) * 0.5 + 0.5 - - // Fixed height thresholds (world Y coordinates) - must match Island.tsx - const waterY = -0.6 - const foamY = -0.35 - const sandY = -0.25 - const grassY = 0.0 - - let color: THREE.Color - - if (absoluteY < waterY) { - color = shallowColor.clone() - color.lerp(new THREE.Color('#1A8A9A'), colorNoise * 0.2) - } else if (absoluteY < foamY) { - const foamAmount = THREE.MathUtils.smoothstep(absoluteY, waterY, foamY) - color = shallowColor.clone().lerp(foamColor, foamAmount) - color.lerp(new THREE.Color('#FFFFFF'), colorNoise * 0.3 * foamAmount) - } else if (absoluteY < sandY) { - const sandProgress = THREE.MathUtils.smoothstep(absoluteY, foamY, sandY) - const wetSand = sandColorLight.clone().lerp(foamColor, 0.15) - color = wetSand.clone().lerp(sandColorMid, sandProgress) - color.lerp(sandColorMid.clone().multiplyScalar(0.95), colorNoise * 0.15) - } else { - const grassProgress = THREE.MathUtils.smoothstep( - absoluteY, - sandY, - grassY, - ) - // Position-based noise for natural grass variation (not angle-based) - const grassNoise = - Math.sin(x * 3.7 + seed) * Math.cos(z * 4.1 + seed * 1.3) * 0.5 + 0.5 - // Solid base grass with subtle noise variation - const baseGrass = grassColorDark.clone().lerp(grassColorLight, 0.3) - const grassColor = baseGrass - .clone() - .lerp(grassColorDark, grassNoise * 0.25) - color = sandColorMid.clone().lerp(grassColor, grassProgress) - } - - colors.push(color.r, color.g, color.b) - } - - geo.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3)) - geo.computeVertexNormals() - - return geo - }, [sphereRadius, seed, scale, sphereCenterY]) - - return ( - - {/* Foam ring */} - - - - - - {/* Shallow water ring */} - - - - - - {/* Spherical cap */} - - - - - ) -} diff --git a/src/components/game/scene/Ocean.tsx b/src/components/game/scene/Ocean.tsx deleted file mode 100644 index 72f100b24..000000000 --- a/src/components/game/scene/Ocean.tsx +++ /dev/null @@ -1,212 +0,0 @@ -import { useRef, useMemo } from 'react' -import { useFrame } from '@react-three/fiber' -import * as THREE from 'three' -import { COLORS } from '../utils/colors' - -export function Ocean() { - const meshRef = useRef(null) - - const { geometry, material } = useMemo(() => { - const geo = new THREE.PlaneGeometry(500, 500, 200, 200) - geo.rotateX(-Math.PI / 2) - - const mat = new THREE.ShaderMaterial({ - uniforms: { - uTime: { value: 0 }, - uDeepColor: { value: new THREE.Color(COLORS.ocean.deep) }, - uMidColor: { value: new THREE.Color(COLORS.ocean.mid) }, - uSurfaceColor: { value: new THREE.Color(COLORS.ocean.surface) }, - uShallowColor: { value: new THREE.Color(COLORS.ocean.shallow) }, - uFoamColor: { value: new THREE.Color(COLORS.ocean.foam) }, - }, - vertexShader: ` - uniform float uTime; - varying vec2 vUv; - varying float vElevation; - varying vec3 vWorldPos; - varying vec3 vNormal; - - // Simplex noise - vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; } - vec2 mod289(vec2 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; } - vec3 permute(vec3 x) { return mod289(((x*34.0)+1.0)*x); } - - float snoise(vec2 v) { - const vec4 C = vec4(0.211324865405187, 0.366025403784439, - -0.577350269189626, 0.024390243902439); - vec2 i = floor(v + dot(v, C.yy)); - vec2 x0 = v - i + dot(i, C.xx); - vec2 i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0); - vec4 x12 = x0.xyxy + C.xxzz; - x12.xy -= i1; - i = mod289(i); - vec3 p = permute(permute(i.y + vec3(0.0, i1.y, 1.0)) + i.x + vec3(0.0, i1.x, 1.0)); - vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0); - m = m*m; m = m*m; - vec3 x = 2.0 * fract(p * C.www) - 1.0; - vec3 h = abs(x) - 0.5; - vec3 ox = floor(x + 0.5); - vec3 a0 = x - ox; - m *= 1.79284291400159 - 0.85373472095314 * (a0*a0 + h*h); - vec3 g; - g.x = a0.x * x0.x + h.x * x0.y; - g.yz = a0.yz * x12.xz + h.yz * x12.yw; - return 130.0 * dot(m, g); - } - - void main() { - vUv = uv; - vec3 pos = position; - - // Large rolling waves - very gentle - float wave1 = snoise(vec2(pos.x * 0.015 + uTime * 0.08, pos.z * 0.015 + uTime * 0.06)) * 0.1; - // Medium waves - float wave2 = snoise(vec2(pos.x * 0.04 - uTime * 0.1, pos.z * 0.04 + uTime * 0.08)) * 0.05; - // Small ripples - float wave3 = snoise(vec2(pos.x * 0.12 + uTime * 0.2, pos.z * 0.12 - uTime * 0.15)) * 0.03; - // Tiny detail - float wave4 = snoise(vec2(pos.x * 0.25 + uTime * 0.3, pos.z * 0.25)) * 0.015; - - float elevation = wave1 + wave2 + wave3 + wave4; - pos.y += elevation; - - vElevation = elevation; - vWorldPos = pos; - - // Calculate normal for lighting - float eps = 0.5; - float hL = snoise(vec2((pos.x - eps) * 0.015 + uTime * 0.08, pos.z * 0.015 + uTime * 0.06)) * 0.1; - float hR = snoise(vec2((pos.x + eps) * 0.015 + uTime * 0.08, pos.z * 0.015 + uTime * 0.06)) * 0.1; - float hD = snoise(vec2(pos.x * 0.015 + uTime * 0.08, (pos.z - eps) * 0.015 + uTime * 0.06)) * 0.1; - float hU = snoise(vec2(pos.x * 0.015 + uTime * 0.08, (pos.z + eps) * 0.015 + uTime * 0.06)) * 0.1; - vNormal = normalize(vec3(hL - hR, 2.0, hD - hU)); - - gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0); - } - `, - fragmentShader: ` - uniform float uTime; - uniform vec3 uDeepColor; - uniform vec3 uMidColor; - uniform vec3 uSurfaceColor; - uniform vec3 uShallowColor; - uniform vec3 uFoamColor; - varying vec2 vUv; - varying float vElevation; - varying vec3 vWorldPos; - varying vec3 vNormal; - - // Noise for foam patterns - vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; } - vec2 mod289(vec2 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; } - vec3 permute(vec3 x) { return mod289(((x*34.0)+1.0)*x); } - float snoise(vec2 v) { - const vec4 C = vec4(0.211324865405187, 0.366025403784439, -0.577350269189626, 0.024390243902439); - vec2 i = floor(v + dot(v, C.yy)); - vec2 x0 = v - i + dot(i, C.xx); - vec2 i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0); - vec4 x12 = x0.xyxy + C.xxzz; x12.xy -= i1; - i = mod289(i); - vec3 p = permute(permute(i.y + vec3(0.0, i1.y, 1.0)) + i.x + vec3(0.0, i1.x, 1.0)); - vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0); - m = m*m; m = m*m; - vec3 x = 2.0 * fract(p * C.www) - 1.0; - vec3 h = abs(x) - 0.5; - vec3 a0 = x - floor(x + 0.5); - m *= 1.79284291400159 - 0.85373472095314 * (a0*a0 + h*h); - vec3 g; g.x = a0.x * x0.x + h.x * x0.y; g.yz = a0.yz * x12.xz + h.yz * x12.yw; - return 130.0 * dot(m, g); - } - - void main() { - // Distance from center for depth gradient - float distFromCenter = length(vWorldPos.xz); - float depthFactor = clamp(distFromCenter / 80.0, 0.0, 1.0); - - // Normalize elevation to 0-1 - float normElev = clamp((vElevation + 0.8) / 1.6, 0.0, 1.0); - - // Base color - blend based on distance (deeper = darker blue) - vec3 nearColor = mix(uSurfaceColor, uShallowColor, normElev); - vec3 farColor = mix(uDeepColor, uMidColor, normElev * 0.5); - vec3 color = mix(nearColor, farColor, depthFactor * 0.7); - - // Add subtle color variation with noise - float colorNoise = snoise(vWorldPos.xz * 0.02) * 0.5 + 0.5; - color = mix(color, color * 0.9, colorNoise * 0.15); - - // Refraction-like color shifting based on view angle and waves - float refractionNoise1 = snoise(vWorldPos.xz * 0.08 + uTime * 0.12); - float refractionNoise2 = snoise(vWorldPos.xz * 0.12 - uTime * 0.08); - vec3 tealTint = vec3(0.1, 0.6, 0.5); - vec3 blueTint = vec3(0.1, 0.3, 0.7); - float refractionAmount = (refractionNoise1 * 0.5 + 0.5) * 0.25; - color = mix(color, mix(color, tealTint, 0.4), refractionAmount * (1.0 - depthFactor)); - color = mix(color, mix(color, blueTint, 0.3), refractionNoise2 * 0.15); - - // Specular highlight from sun - animated shimmer - vec3 lightDir = normalize(vec3(0.5, 0.8, 0.3)); - vec3 viewDir = normalize(vec3(0.0, 1.0, 0.5)); - vec3 halfDir = normalize(lightDir + viewDir); - float spec = pow(max(dot(vNormal, halfDir), 0.0), 64.0); - // Add shimmer variation - float shimmer = snoise(vWorldPos.xz * 0.5 + uTime * 0.8) * 0.3 + 0.7; - color += vec3(1.0, 0.98, 0.9) * spec * 0.5 * shimmer; - - // Foam on wave peaks - float foamNoise = snoise(vWorldPos.xz * 0.3 + uTime * 0.2) * 0.5 + 0.5; - float foamThreshold = 0.3; - if (vElevation > foamThreshold) { - float foamStrength = (vElevation - foamThreshold) / 0.5; - foamStrength = clamp(foamStrength * foamNoise * 1.5, 0.0, 1.0); - color = mix(color, uFoamColor, foamStrength * 0.5); - } - - // Multi-layer caustics for refraction effect - float caustic1 = snoise(vWorldPos.xz * 0.15 + uTime * 0.15); - float caustic2 = snoise(vWorldPos.xz * 0.25 - uTime * 0.1 + vec2(50.0, 30.0)); - float caustic3 = snoise(vWorldPos.xz * 0.08 + uTime * 0.05); - float causticPattern = pow(abs(caustic1), 1.5) + pow(abs(caustic2), 2.0) * 0.5; - causticPattern *= (caustic3 * 0.5 + 0.75); - // Teal/cyan caustic color - vec3 causticColor = vec3(0.15, 0.55, 0.6); - color += causticColor * causticPattern * 0.2; - - gl_FragColor = vec4(color, 0.97); - } - `, - transparent: true, - }) - - return { geometry: geo, material: mat } - }, []) - - useFrame((state) => { - if (material.uniforms) { - // eslint-disable-next-line react-hooks/immutability - material.uniforms.uTime.value = state.clock.elapsedTime - } - }) - - return ( - - ) -} - -// Wave height for boat bobbing (matches shader + ocean offset) -export function getWaveHeight(x: number, z: number, time: number): number { - const wave1 = - Math.sin(x * 0.015 + time * 0.08) * Math.cos(z * 0.015 + time * 0.06) * 0.1 - const wave2 = - Math.sin(x * 0.04 - time * 0.1) * Math.cos(z * 0.04 + time * 0.08) * 0.05 - const wave3 = - Math.sin(x * 0.12 + time * 0.2) * Math.cos(z * 0.12 - time * 0.15) * 0.03 - // Ocean mesh is at Y=-0.5, so subtract that offset - return wave1 + wave2 + wave3 - 0.5 -} diff --git a/src/components/game/scene/OceanRocks.tsx b/src/components/game/scene/OceanRocks.tsx deleted file mode 100644 index fdbd834c2..000000000 --- a/src/components/game/scene/OceanRocks.tsx +++ /dev/null @@ -1,224 +0,0 @@ -import { useMemo, useRef, useState } from 'react' -import { useFrame } from '@react-three/fiber' -import * as THREE from 'three' -import type { IslandData } from '../utils/islandGenerator' -import { useGameStore } from '../hooks/useGameStore' -import { CULL_DISTANCES } from '../hooks/useDistanceCulling' - -interface RockData { - position: [number, number, number] - scale: [number, number, number] - rotation: [number, number, number] - color: string -} - -interface RockGroupData { - position: [number, number, number] - rocks: RockData[] - foamRadius: number -} - -interface OceanRocksProps { - islands: IslandData[] - groupCount?: number - spread?: number -} - -function seededRandom(seed: number) { - const x = Math.sin(seed) * 10000 - return x - Math.floor(x) -} - -// Individual rock with animated rings -function AnimatedRock({ rock, index }: { rock: RockData; index: number }) { - const foamRef = useRef(null) - const waterRef = useRef(null) - const rockSize = Math.max(rock.scale[0], rock.scale[2]) - - useFrame((state) => { - const t = state.clock.elapsedTime - // Each rock has slightly different phase based on index - const phase = index * 0.7 - const scale = 1 + Math.sin(t * 0.8 + phase) * 0.12 - - if (foamRef.current) { - foamRef.current.scale.set(scale, scale, 1) - } - if (waterRef.current) { - // Water ring pulses slightly out of phase - const waterScale = 1 + Math.sin(t * 0.8 + phase + 0.5) * 0.1 - waterRef.current.scale.set(waterScale, waterScale, 1) - } - }) - - return ( - - {/* Rock mesh */} - - - - - - {/* Foam ring around this rock */} - - - - - - {/* Shallow water ring around this rock */} - - - - - - ) -} - -export function OceanRocks({ - islands, - groupCount = 20, - spread = 120, -}: OceanRocksProps) { - const groupRef = useRef(null) - const [visibleGroups, setVisibleGroups] = useState>(new Set()) - - const rockGroups = useMemo(() => { - const result: RockGroupData[] = [] - const rockColors = ['#7A8B8B', '#8B9A9A', '#6B7B7B', '#9AA8A8', '#5C6B6B'] - const minDistFromIsland = 10 - - for (let g = 0; g < groupCount; g++) { - const groupSeed = g * 54321 - - // Random group position - const groupX = (seededRandom(groupSeed) - 0.5) * spread - const groupZ = (seededRandom(groupSeed + 1) - 0.5) * spread - - // Check distance from all islands - let tooClose = false - for (const island of islands) { - const dx = groupX - island.position[0] - const dz = groupZ - island.position[2] - const dist = Math.sqrt(dx * dx + dz * dz) - if (dist < minDistFromIsland) { - tooClose = true - break - } - } - - if (tooClose) continue - - // 1-4 rocks per group - const rockCount = 1 + Math.floor(seededRandom(groupSeed + 2) * 4) - const rocks: RockData[] = [] - let maxRockScale = 0 - - for (let r = 0; r < rockCount; r++) { - const rockSeed = groupSeed + r * 100 - - // Position within group - first rock at center, others scattered nearby - const offsetDist = r === 0 ? 0 : 1.2 + seededRandom(rockSeed) * 1.0 - const offsetAngle = seededRandom(rockSeed + 1) * Math.PI * 2 - const localX = Math.cos(offsetAngle) * offsetDist - const localZ = Math.sin(offsetAngle) * offsetDist - - // Varying sizes - first rock tends to be larger - const sizeMultiplier = - r === 0 ? 1 : 0.4 + seededRandom(rockSeed + 2) * 0.5 - const baseScale = - (0.25 + seededRandom(rockSeed + 3) * 0.55) * sizeMultiplier - - maxRockScale = Math.max(maxRockScale, baseScale) - - rocks.push({ - position: [localX, -0.1 - baseScale * 0.1, localZ], - scale: [ - baseScale * (0.8 + seededRandom(rockSeed + 4) * 0.4), - baseScale * (0.4 + seededRandom(rockSeed + 5) * 0.4), - baseScale * (0.8 + seededRandom(rockSeed + 6) * 0.4), - ], - rotation: [ - seededRandom(rockSeed + 7) * 0.4, - seededRandom(rockSeed + 8) * Math.PI * 2, - seededRandom(rockSeed + 9) * 0.4, - ], - color: - rockColors[ - Math.floor(seededRandom(rockSeed + 10) * rockColors.length) - ], - }) - } - - result.push({ - position: [groupX, 0, groupZ], - rocks, - foamRadius: maxRockScale + 0.4 + rockCount * 0.15, - }) - } - - return result - }, [islands, groupCount, spread]) - - // Distance culling + gentle bob with waves - useFrame((state) => { - const { boatPosition } = useGameStore.getState() - const maxDistSq = CULL_DISTANCES.rock * CULL_DISTANCES.rock - const time = state.clock.elapsedTime - - // Update visibility based on distance - const newVisible = new Set() - rockGroups.forEach((group, i) => { - const dx = group.position[0] - boatPosition[0] - const dz = group.position[2] - boatPosition[2] - if (dx * dx + dz * dz < maxDistSq) { - newVisible.add(i) - } - }) - - // Only update state if changed - if ( - newVisible.size !== visibleGroups.size || - [...newVisible].some((i) => !visibleGroups.has(i)) - ) { - setVisibleGroups(newVisible) - } - - // Bob visible groups - if (groupRef.current) { - groupRef.current.children.forEach((group, i) => { - const offset = i * 0.7 - group.position.y = Math.sin(time * 0.4 + offset) * 0.04 - }) - } - }) - - return ( - - {rockGroups.map((group, gi) => ( - - {/* Individual rocks with animated foam/water rings */} - {group.rocks.map((rock, ri) => ( - - ))} - - ))} - - ) -} diff --git a/src/components/game/scene/PalmTree.tsx b/src/components/game/scene/PalmTree.tsx deleted file mode 100644 index 5c6ef7bef..000000000 --- a/src/components/game/scene/PalmTree.tsx +++ /dev/null @@ -1,95 +0,0 @@ -import { useRef, useMemo } from 'react' -import { useFrame } from '@react-three/fiber' -import { useGLTF } from '@react-three/drei' -import * as THREE from 'three' - -interface PalmTreeProps { - position?: [number, number, number] - scale?: number - hasCoconuts?: boolean - tint?: string -} - -export function PalmTree({ - position = [0, 0, 0], - scale = 1, - hasCoconuts = false, - tint, -}: PalmTreeProps) { - const groupRef = useRef(null) - - const { scene } = useGLTF('/models/palm-tree.glb') - - const { clonedScene, randomRotation } = useMemo(() => { - const clone = scene.clone() - const tintColor = tint ? new THREE.Color(tint) : null - - clone.traverse((child) => { - if (child instanceof THREE.Mesh) { - child.castShadow = true - child.receiveShadow = true - - if (child.material) { - child.material = child.material.clone() - const mat = child.material as THREE.MeshStandardMaterial - - // Apply tint by multiplying material color - if (tintColor && mat.color) { - mat.color.multiply(tintColor) - } - - // Fix texture filtering to remove pixelated stripes - if (mat.map) { - mat.map.minFilter = THREE.LinearMipmapLinearFilter - mat.map.magFilter = THREE.LinearFilter - mat.map.generateMipmaps = true - mat.map.anisotropy = 16 - mat.map.needsUpdate = true - } - } - } - }) - // Stable random rotation based on position - const rot = (position[0] * 1000 + position[2] * 100) % (Math.PI * 2) - return { clonedScene: clone, randomRotation: rot } - }, [scene, position, tint]) - - // Gentle swaying animation - useFrame((state) => { - if (groupRef.current) { - const time = state.clock.elapsedTime - groupRef.current.rotation.z = Math.sin(time * 0.4 + position[0]) * 0.03 - groupRef.current.rotation.x = Math.sin(time * 0.3 + position[2]) * 0.02 - } - }) - - return ( - - - - - - {/* Coconuts cluster */} - {hasCoconuts && ( - - {[ - [0.1, 0, 0.08], - [-0.08, -0.05, 0.1], - [0.02, 0.05, -0.1], - ].map((pos, i) => ( - - - - - ))} - - )} - - ) -} - -useGLTF.preload('/models/palm-tree.glb') diff --git a/src/components/game/scene/Ship.tsx b/src/components/game/scene/Ship.tsx deleted file mode 100644 index 358da36cd..000000000 --- a/src/components/game/scene/Ship.tsx +++ /dev/null @@ -1,206 +0,0 @@ -import { useRef, useMemo } from 'react' -import { useFrame } from '@react-three/fiber' -import { useGLTF } from '@react-three/drei' -import * as THREE from 'three' -import { useGameStore } from '../hooks/useGameStore' -import { getWaveHeight } from './Ocean' - -interface ShipProps { - color?: string -} - -export function Ship({ color = '#FFEEDD' }: ShipProps) { - const groupRef = useRef(null) - const wakeRef = useRef(null) - const cannonRef = useRef(null) - - const { scene } = useGLTF('/models/ship.glb') - - const clonedScene = useMemo(() => { - const clone = scene.clone() - const tintColor = new THREE.Color(color) - - clone.traverse((child) => { - if (child instanceof THREE.Mesh) { - child.castShadow = true - child.receiveShadow = true - - if (child.material) { - child.material = child.material.clone() - const mat = child.material as THREE.MeshStandardMaterial - mat.color.multiply(tintColor) - - if (mat.map) { - mat.map.minFilter = THREE.LinearMipmapLinearFilter - mat.map.magFilter = THREE.LinearFilter - mat.map.generateMipmaps = true - mat.map.anisotropy = 16 - mat.map.needsUpdate = true - } - } - } - }) - return clone - }, [scene, color]) - - // Wake particles - const wakeParticles = useMemo(() => { - const count = 100 - const positions = new Float32Array(count * 3) - const sizes = new Float32Array(count) - - for (let i = 0; i < count; i++) { - positions[i * 3] = 0 - positions[i * 3 + 1] = 0 - positions[i * 3 + 2] = 0 - sizes[i] = 0 - } - - const geometry = new THREE.BufferGeometry() - geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3)) - geometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1)) - - return geometry - }, []) - - // Animate ship with waves and wake - useFrame((state) => { - const { boatPosition, boatRotation, boatVelocity } = useGameStore.getState() - - if (groupRef.current) { - const time = state.clock.elapsedTime - - // Wave height at boat position - const waveY = getWaveHeight(boatPosition[0], boatPosition[2], time) - - // Gentle bobbing - const bobY = Math.sin(time * 1.8) * 0.03 - const bobRoll = Math.sin(time * 1.5) * 0.03 - const bobPitch = Math.sin(time * 2.2) * 0.02 - - // Wave-based tilting - const waveTiltX = - getWaveHeight(boatPosition[0] + 0.3, boatPosition[2], time) - waveY - const waveTiltZ = - getWaveHeight(boatPosition[0], boatPosition[2] + 0.3, time) - waveY - - groupRef.current.position.set( - boatPosition[0], - waveY + bobY + 0.2, - boatPosition[2], - ) - groupRef.current.rotation.set( - bobPitch + waveTiltZ * 0.4, - boatRotation, - bobRoll + waveTiltX * 0.4, - ) - - // Animate cannon (slight sway) - if (cannonRef.current) { - cannonRef.current.rotation.y = Math.sin(time * 0.5) * 0.1 - } - } - - // Update wake particles - if (wakeRef.current) { - const positions = wakeRef.current.geometry.attributes - .position as THREE.BufferAttribute - const sizes = wakeRef.current.geometry.attributes - .size as THREE.BufferAttribute - - for (let i = positions.count - 1; i > 0; i--) { - positions.setXYZ( - i, - positions.getX(i - 1), - positions.getY(i - 1) - 0.002, - positions.getZ(i - 1), - ) - const currentSize = sizes.getX(i - 1) - sizes.setX(i, currentSize > 0.01 ? currentSize * 0.995 : 0) - } - - if (boatVelocity > 0.05 && Math.random() < 0.25) { - const backOffset = 0.7 - const spread = (Math.random() - 0.5) * 0.5 - - const newX = - boatPosition[0] - - Math.sin(boatRotation) * backOffset + - Math.cos(boatRotation) * spread - const newZ = - boatPosition[2] - - Math.cos(boatRotation) * backOffset - - Math.sin(boatRotation) * spread - - positions.setXYZ(0, newX, 0.05, newZ) - sizes.setX(0, 0.2 + boatVelocity * 0.15) - } else { - positions.setXYZ(0, boatPosition[0], -10, boatPosition[2]) - sizes.setX(0, 0) - } - - positions.needsUpdate = true - sizes.needsUpdate = true - } - }) - - return ( - <> - - - - {/* Side cannon */} - - {/* Cannon base */} - - - - - {/* Cannon barrel */} - - - - - {/* Cannon muzzle */} - - - - - - - - {/* Wake/splash particles */} - - - - - ) -} - -useGLTF.preload('/models/ship.glb') diff --git a/src/components/game/scene/Sky.tsx b/src/components/game/scene/Sky.tsx deleted file mode 100644 index 4c91b6d48..000000000 --- a/src/components/game/scene/Sky.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import { useMemo } from 'react' -import * as THREE from 'three' -import { COLORS } from '../utils/colors' - -export function Sky() { - const geometry = useMemo(() => { - return new THREE.SphereGeometry(500, 32, 32) - }, []) - - const material = useMemo(() => { - // Gradient shader for sky - return new THREE.ShaderMaterial({ - uniforms: { - topColor: { value: new THREE.Color(COLORS.sky.top) }, - midColor: { value: new THREE.Color(COLORS.sky.mid) }, - bottomColor: { value: new THREE.Color(COLORS.sky.horizon) }, - }, - vertexShader: ` - varying vec3 vWorldPosition; - void main() { - vec4 worldPosition = modelMatrix * vec4(position, 1.0); - vWorldPosition = worldPosition.xyz; - gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); - } - `, - fragmentShader: ` - uniform vec3 topColor; - uniform vec3 midColor; - uniform vec3 bottomColor; - varying vec3 vWorldPosition; - - void main() { - float h = normalize(vWorldPosition).y; - - // Blend from bottom (horizon) to mid to top - vec3 color; - if (h < 0.0) { - color = bottomColor; - } else if (h < 0.3) { - color = mix(bottomColor, midColor, h / 0.3); - } else { - color = mix(midColor, topColor, (h - 0.3) / 0.7); - } - - gl_FragColor = vec4(color, 1.0); - } - `, - side: THREE.BackSide, - }) - }, []) - - return -} diff --git a/src/components/game/scene/TikiShack.tsx b/src/components/game/scene/TikiShack.tsx deleted file mode 100644 index a8d027fa2..000000000 --- a/src/components/game/scene/TikiShack.tsx +++ /dev/null @@ -1,57 +0,0 @@ -import { useMemo } from 'react' -import * as THREE from 'three' -import { COLORS } from '../utils/colors' - -interface TikiShackProps { - position?: [number, number, number] - rotation?: number - color: string -} - -export function TikiShack({ - position = [0, 0, 0], - rotation = 0, - color, -}: TikiShackProps) { - const roofGeometry = useMemo(() => { - return new THREE.ConeGeometry(1.2, 1, 6) - }, []) - - return ( - - {/* Posts */} - {[ - [-0.6, 0, -0.6], - [0.6, 0, -0.6], - [-0.6, 0, 0.6], - [0.6, 0, 0.6], - ].map((pos, i) => ( - - - - - ))} - - {/* Thatched roof */} - - - - - {/* Roof edge trim */} - - - - - - {/* Roof ornament */} - - - - - - ) -} diff --git a/src/components/game/scene/VirtualizedCoins.tsx b/src/components/game/scene/VirtualizedCoins.tsx deleted file mode 100644 index 49563d6ee..000000000 --- a/src/components/game/scene/VirtualizedCoins.tsx +++ /dev/null @@ -1,75 +0,0 @@ -import { useRef, useState } from 'react' -import { useFrame } from '@react-three/fiber' -import * as THREE from 'three' -import { useGameStore, type CoinData } from '../hooks/useGameStore' - -const RENDER_DISTANCE = 50 - -// Shared geometry and material -const coinGeometry = new THREE.CylinderGeometry(0.35, 0.35, 0.08, 12) -const coinMaterial = new THREE.MeshStandardMaterial({ - color: '#FFD700', - metalness: 0.8, - roughness: 0.3, - emissive: '#FF8C00', - emissiveIntensity: 0.4, -}) - -interface CoinMeshProps { - coin: CoinData -} - -function CoinMesh({ coin }: CoinMeshProps) { - const meshRef = useRef(null) - - useFrame((state) => { - if (meshRef.current) { - const t = state.clock.elapsedTime - meshRef.current.rotation.y = t * 2 - meshRef.current.position.y = - coin.position[1] + Math.sin(t * 2 + coin.id * 0.5) * 0.15 - } - }) - - return ( - - ) -} - -export function VirtualizedCoins() { - const [visibleCoins, setVisibleCoins] = useState([]) - - useFrame(() => { - const { coins, boatPosition } = useGameStore.getState() - - // Filter to nearby uncollected coins - const nowVisible = coins.filter((coin) => { - if (coin.collected) return false - const dx = coin.position[0] - boatPosition[0] - const dz = coin.position[2] - boatPosition[2] - const distSq = dx * dx + dz * dz - return distSq < RENDER_DISTANCE * RENDER_DISTANCE - }) - - // Only update state if the visible set changed - if ( - nowVisible.length !== visibleCoins.length || - nowVisible.some((c, i) => visibleCoins[i]?.id !== c.id) - ) { - setVisibleCoins(nowVisible) - } - }) - - return ( - <> - {visibleCoins.map((coin) => ( - - ))} - - ) -} diff --git a/src/components/game/scene/VirtualizedIslands.tsx b/src/components/game/scene/VirtualizedIslands.tsx deleted file mode 100644 index e3f7b9ee1..000000000 --- a/src/components/game/scene/VirtualizedIslands.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import { useState } from 'react' -import { useFrame } from '@react-three/fiber' -import { useGameStore } from '../hooks/useGameStore' -import { CULL_DISTANCES } from '../hooks/useDistanceCulling' -import { Island } from './Island' -import type { IslandData } from '../utils/islandGenerator' - -interface VirtualizedIslandsProps { - islands: IslandData[] -} - -export function VirtualizedIslands({ islands }: VirtualizedIslandsProps) { - const [visibleIslands, setVisibleIslands] = useState< - Array<{ island: IslandData; isDiscovered: boolean }> - >([]) - - useFrame(() => { - const { boatPosition, discoveredIslands } = useGameStore.getState() - const maxDistSq = CULL_DISTANCES.island * CULL_DISTANCES.island - - const nowVisible: Array<{ island: IslandData; isDiscovered: boolean }> = [] - for (const island of islands) { - const dx = island.position[0] - boatPosition[0] - const dz = island.position[2] - boatPosition[2] - if (dx * dx + dz * dz < maxDistSq) { - nowVisible.push({ - island, - isDiscovered: discoveredIslands.has(island.id), - }) - } - } - - // Only update if changed - if ( - nowVisible.length !== visibleIslands.length || - nowVisible.some( - (v, i) => - visibleIslands[i]?.island.id !== v.island.id || - visibleIslands[i]?.isDiscovered !== v.isDiscovered, - ) - ) { - setVisibleIslands(nowVisible) - } - }) - - return ( - <> - {visibleIslands.map(({ island, isDiscovered }) => ( - - ))} - - ) -} diff --git a/src/components/game/ui/TouchControls.tsx b/src/components/game/ui/TouchControls.tsx index 39e373d8e..5e6bc62e9 100644 --- a/src/components/game/ui/TouchControls.tsx +++ b/src/components/game/ui/TouchControls.tsx @@ -10,7 +10,7 @@ export function set3DObjectClicked() { }, 100) } -// Pointer state - shared with useBoatControls via module scope +// Pointer state read by the boat control system. let pointerActive = false let pointerX = 0 let pointerY = 0