File size: 9,214 Bytes
01d5a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
'use client';

import type React from 'react';
import { useEffect, useRef, useState } from 'react';
import * as THREE from 'three';

interface NameNode {
  name: string;
  size: number;
  color: string;
  position: [number, number, number];
}

interface NetworkSphereProps {
  onInitialized?: () => void;
}

const NetworkSphere: React.FC<NetworkSphereProps> = ({ onInitialized }) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const [isInitialized, setIsInitialized] = useState(false);
  const sceneRef = useRef<THREE.Scene | null>(null);
  const rendererRef = useRef<THREE.WebGLRenderer | null>(null);

  useEffect(() => {
    if (typeof window === 'undefined') return;

    const checkWebGLAvailability = (): boolean => {
      try {
        const canvas = document.createElement('canvas');
        const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');

        return !!gl;
      } catch {
        return false;
      }
    };

    // Store animation frame ID for cleanup
    let animationFrameId: number;
    // Store scene and renderer references for cleanup
    let scene: THREE.Scene;
    let renderer: THREE.WebGLRenderer;
    let camera: THREE.PerspectiveCamera;

    // Function to initialize the sphere
    const initializeSphere = () => {
      if (!containerRef.current) return;

      // Create scene
      scene = new THREE.Scene();
      sceneRef.current = scene;
      scene.background = null; // Transparent background

      // Create camera
      camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 2000);
      camera.position.z = 650;

      // Create renderer
      try {
        if (!checkWebGLAvailability()) {
          throw new Error('Your browser does not support WebGL');
        }

        renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
        rendererRef.current = renderer;
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.setPixelRatio(window.devicePixelRatio);
        containerRef.current.appendChild(renderer.domElement);
      } catch (error) {
        console.error('WebGL renderer creation failed:', error);

        onInitialized?.();

        return;
      }

      // Define sphere radius
      const radius = 320;

      // Create nodes
      const names: NameNode[] = [];
      const colors = ['#4ecdc4', '#ff6b6b', '#ffd93d'];
      const sizes = [0.9, 1.0, 1.1, 1.2, 1.3];

      // Create 40 nodes, reducing density
      for (let i = 0; i < 40; i++) {
        names.push({
          name: `Node${i}`,
          size: sizes[Math.floor(Math.random() * sizes.length)],
          color: colors[Math.floor(Math.random() * colors.length)],
          position: randomSpherePoint(radius)
        });
      }

      // Only create colored dots, don't display names
      const dotGeometry = new THREE.SphereGeometry(3.5, 16, 16);
      const dotMaterials = {
        '#4ecdc4': new THREE.MeshBasicMaterial({ color: 0x4ecdc4 }),
        '#ff6b6b': new THREE.MeshBasicMaterial({ color: 0xff6b6b }),
        '#ffd93d': new THREE.MeshBasicMaterial({ color: 0xffd93d })
      };

      // Create dots for each node
      names.forEach((node) => {
        const material = dotMaterials[node.color as keyof typeof dotMaterials];
        const dot = new THREE.Mesh(dotGeometry, material);

        dot.position.set(...node.position);
        scene.add(dot);
      });

      // Connect each node with more nearby nodes
      const maxConnections = 5; // Increased maximum number of connections per node
      const maxDistance = radius * 1.5; // Increased maximum distance for connections

      names.forEach((node, index) => {
        // Calculate distances to all other nodes
        const distances: { index: number; distance: number }[] = names.map(
          (otherNode, otherIndex) => {
            if (index === otherIndex)
              return {
                index: otherIndex,
                distance: Infinity
              }; // Don't connect to self

            const dx = node.position[0] - otherNode.position[0];
            const dy = node.position[1] - otherNode.position[1];
            const dz = node.position[2] - otherNode.position[2];

            return {
              index: otherIndex,
              distance: Math.sqrt(dx * dx + dy * dy + dz * dz)
            };
          }
        );

        // Sort by distance and take the closest nodes
        distances.sort((a, b) => a.distance - b.distance);
        const connectCount = Math.floor(Math.random() * maxConnections) + 1; // At least one connection

        for (let i = 0; i < connectCount && i < distances.length; i++) {
          if (distances[i].distance > maxDistance) continue;

          // Only create connection if the other node's index is higher
          // This prevents creating the same connection twice
          if (distances[i].index > index) {
            const otherNode = names[distances[i].index];

            // Create curved arc geometry that follows the sphere's surface
            const points = [];

            // Calculate the great circle arc between the two points
            // First, normalize the positions to get direction vectors
            const startPos = new THREE.Vector3(...node.position).normalize();
            const endPos = new THREE.Vector3(...otherNode.position).normalize();

            // Calculate the angle between the two points
            // const angle = startPos.angleTo(endPos);

            // Create intermediate points along the great circle arc
            const segments = 12; // More segments for smoother curves

            for (let j = 0; j <= segments; j++) {
              // Interpolation factor
              const t = j / segments;

              // Spherical linear interpolation (SLERP) between the two points
              const interpVec = new THREE.Vector3().copy(startPos).lerp(endPos, t).normalize();

              // Scale to the sphere radius
              const pointOnSphere = interpVec.multiplyScalar(radius);

              points.push(pointOnSphere);
            }

            const lineGeometry = new THREE.BufferGeometry().setFromPoints(points);

            // Create connection with varying opacity based on distance
            const opacity = Math.max(0.25, 0.45 - (distances[i].distance / maxDistance) * 0.2);
            const lineMaterial = new THREE.LineBasicMaterial({
              color: 0xadd8e6, // Light blue color - keeping original color
              transparent: true,
              opacity: opacity
            });

            const line = new THREE.Line(lineGeometry, lineMaterial);

            scene.add(line);
          }
        }
      });

      // Animation
      const rotationSpeed = 0.0005;
      const animate = () => {
        animationFrameId = requestAnimationFrame(animate);

        // Rotate all elements
        scene.rotation.y += rotationSpeed;
        scene.rotation.x += rotationSpeed / 2;

        renderer.render(scene, camera);
      };

      animate();

      // Mark as initialized
      setIsInitialized(true);

      // Notify parent component that initialization is complete
      if (onInitialized) {
        // Use setTimeout to ensure this happens after the component is fully rendered
        setTimeout(() => {
          onInitialized();
        }, 0);
      }
    };

    // Handle window resize
    const handleResize = () => {
      if (!camera || !renderer) return;

      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
    };

    // Initialize the sphere
    initializeSphere();

    // Add resize event listener
    window.addEventListener('resize', handleResize);

    // Cleanup function
    return () => {
      window.removeEventListener('resize', handleResize);

      // Cancel any pending animation frames
      if (animationFrameId) {
        cancelAnimationFrame(animationFrameId);
      }

      // Remove renderer from DOM
      if (containerRef.current && rendererRef.current) {
        containerRef.current.removeChild(rendererRef.current.domElement);
      }

      // Release resources
      if (sceneRef.current) {
        sceneRef.current.clear();
      }

      if (rendererRef.current) {
        rendererRef.current.dispose();
      }
    };
  }, []);

  // Generate random points on a sphere
  function randomSpherePoint(radius: number): [number, number, number] {
    const u = Math.random();
    const v = Math.random();
    const theta = 2 * Math.PI * u;
    const phi = Math.acos(2 * v - 1);

    const x = radius * Math.sin(phi) * Math.cos(theta);
    const y = radius * Math.sin(phi) * Math.sin(theta);
    const z = radius * Math.cos(phi);

    return [x, y, z];
  }

  // Since we no longer display names, the text sprite creation function has been removed

  return (
    <div
      ref={containerRef}
      className="fixed inset-0 -z-10 w-screen h-screen overflow-hidden"
      style={{
        pointerEvents: 'none',
        opacity: isInitialized ? 1 : 0,
        transition: 'opacity 0.5s ease-in-out'
      }}
    />
  );
};

export default NetworkSphere;