File size: 10,122 Bytes
8a01471
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/**
 * Neural Network Connection Visualization
 * Shows dense connections between layers like actual neural networks
 */

import { useMemo, useRef } from 'react';
import * as THREE from 'three';
import { useFrame } from '@react-three/fiber';
import type { Position3D } from '@/schema/types';

export interface NeuralConnectionProps {
  sourcePosition: Position3D;
  targetPosition: Position3D;
  sourceNeurons?: number;
  targetNeurons?: number;
  color?: string;
  highlighted?: boolean;
  animated?: boolean;
  connectionDensity?: number; // 0-1, how many connections to show
  style?: 'single' | 'dense' | 'bundle';
}

/**
 * Single connection line between layers
 */
export function SingleConnection({
  sourcePosition,
  targetPosition,
  color = '#ffffff',
  highlighted = false,
}: NeuralConnectionProps) {
  const geometry = useMemo(() => {
    const points = [
      new THREE.Vector3(sourcePosition.x, sourcePosition.y, sourcePosition.z),
      new THREE.Vector3(targetPosition.x, targetPosition.y, targetPosition.z),
    ];
    return new THREE.BufferGeometry().setFromPoints(points);
  }, [sourcePosition, targetPosition]);
  
  return (
    <primitive object={new THREE.Line(geometry, new THREE.LineBasicMaterial({
      color: highlighted ? '#ffffff' : color,
      transparent: true,
      opacity: highlighted ? 1 : 0.5,
    }))} />
  );
}

/**
 * Dense connection bundle showing multiple lines
 */
export function DenseConnection({
  sourcePosition,
  targetPosition,
  sourceNeurons = 16,
  targetNeurons = 16,
  color = '#4488ff',
  highlighted = false,
  animated = true,
  connectionDensity = 0.3,
}: NeuralConnectionProps) {
  const groupRef = useRef<THREE.Group>(null);
  const materialRef = useRef<THREE.LineBasicMaterial>(null);
  
  // Limit connections for performance
  const maxConnections = 100;
  const numConnections = Math.min(
    Math.floor(sourceNeurons * targetNeurons * connectionDensity),
    maxConnections
  );
  
  // Generate connection lines
  const lines = useMemo(() => {
    const connections: { start: THREE.Vector3; end: THREE.Vector3 }[] = [];
    
    // Calculate source and target layer bounds
    const sourceSpread = Math.min(Math.sqrt(sourceNeurons) * 0.1, 0.4);
    const targetSpread = Math.min(Math.sqrt(targetNeurons) * 0.1, 0.4);
    
    for (let i = 0; i < numConnections; i++) {
      // Random positions within layer bounds
      const srcOffset = {
        y: (Math.random() - 0.5) * sourceSpread,
        z: (Math.random() - 0.5) * sourceSpread * 0.5,
      };
      const tgtOffset = {
        y: (Math.random() - 0.5) * targetSpread,
        z: (Math.random() - 0.5) * targetSpread * 0.5,
      };
      
      connections.push({
        start: new THREE.Vector3(
          sourcePosition.x + 0.3, // Offset from layer center
          sourcePosition.y + srcOffset.y,
          sourcePosition.z + srcOffset.z
        ),
        end: new THREE.Vector3(
          targetPosition.x - 0.3, // Offset from layer center
          targetPosition.y + tgtOffset.y,
          targetPosition.z + tgtOffset.z
        ),
      });
    }
    
    return connections;
  }, [sourcePosition, targetPosition, sourceNeurons, targetNeurons, numConnections]);
  
  // Animate opacity
  useFrame((state) => {
    if (animated && materialRef.current) {
      const pulse = Math.sin(state.clock.elapsedTime * 2) * 0.1 + 0.3;
      materialRef.current.opacity = highlighted ? 0.8 : pulse;
    }
  });
  
  // Create buffer geometry for all lines
  const geometry = useMemo(() => {
    const positions: number[] = [];
    
    lines.forEach(line => {
      positions.push(line.start.x, line.start.y, line.start.z);
      positions.push(line.end.x, line.end.y, line.end.z);
    });
    
    const geo = new THREE.BufferGeometry();
    geo.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
    return geo;
  }, [lines]);
  
  return (
    <group ref={groupRef}>
      <lineSegments geometry={geometry}>
        <lineBasicMaterial
          ref={materialRef}
          color={highlighted ? '#ffffff' : color}
          transparent
          opacity={0.3}
          depthWrite={false}
        />
      </lineSegments>
    </group>
  );
}

/**
 * Bundled connection - shows as a tube/pipe
 */
export function BundledConnection({
  sourcePosition,
  targetPosition,
  sourceNeurons = 16,
  targetNeurons = 16,
  color = '#4488ff',
  highlighted = false,
  animated = true,
}: NeuralConnectionProps) {
  const meshRef = useRef<THREE.Mesh>(null);
  
  // Calculate bundle thickness based on connection count
  const connectionStrength = Math.log2(Math.min(sourceNeurons, targetNeurons) + 1) * 0.02;
  const thickness = Math.max(0.02, Math.min(connectionStrength, 0.1));
  
  // Create tube path
  const curve = useMemo(() => {
    const start = new THREE.Vector3(sourcePosition.x, sourcePosition.y, sourcePosition.z);
    const end = new THREE.Vector3(targetPosition.x, targetPosition.y, targetPosition.z);
    
    // Bezier control points for smooth curve
    const midX = (start.x + end.x) / 2;
    const control1 = new THREE.Vector3(midX, start.y, start.z);
    const control2 = new THREE.Vector3(midX, end.y, end.z);
    
    return new THREE.CubicBezierCurve3(start, control1, control2, end);
  }, [sourcePosition, targetPosition]);
  
  const geometry = useMemo(() => {
    return new THREE.TubeGeometry(curve, 20, thickness, 8, false);
  }, [curve, thickness]);
  
  // Animate flow effect
  useFrame((state) => {
    if (animated && meshRef.current) {
      const material = meshRef.current.material as THREE.MeshStandardMaterial;
      if (material.emissiveIntensity !== undefined) {
        material.emissiveIntensity = Math.sin(state.clock.elapsedTime * 3) * 0.2 + 0.3;
      }
    }
  });
  
  const baseColor = new THREE.Color(color);
  
  return (
    <mesh ref={meshRef} geometry={geometry}>
      <meshStandardMaterial
        color={highlighted ? '#ffffff' : baseColor}
        emissive={baseColor}
        emissiveIntensity={0.3}
        transparent
        opacity={highlighted ? 0.9 : 0.6}
        metalness={0.3}
        roughness={0.7}
      />
    </mesh>
  );
}

/**
 * Flow particles along connection
 */
export function FlowParticles({
  sourcePosition,
  targetPosition,
  color = '#ffffff',
  particleCount = 5,
  speed = 1,
}: {
  sourcePosition: Position3D;
  targetPosition: Position3D;
  color?: string;
  particleCount?: number;
  speed?: number;
}) {
  const particlesRef = useRef<THREE.Points>(null);
  
  // Create particle positions
  const { positions, offsets } = useMemo(() => {
    const pos = new Float32Array(particleCount * 3);
    const off = new Float32Array(particleCount);
    
    for (let i = 0; i < particleCount; i++) {
      off[i] = i / particleCount; // Spread particles along path
      
      // Initial positions will be updated in useFrame
      pos[i * 3] = sourcePosition.x;
      pos[i * 3 + 1] = sourcePosition.y;
      pos[i * 3 + 2] = sourcePosition.z;
    }
    
    return { positions: pos, offsets: off };
  }, [sourcePosition, particleCount]);
  
  const geometry = useMemo(() => {
    const geo = new THREE.BufferGeometry();
    geo.setAttribute('position', new THREE.BufferAttribute(positions, 3));
    return geo;
  }, [positions]);
  
  // Animate particles
  useFrame((state) => {
    if (particlesRef.current) {
      const posAttr = particlesRef.current.geometry.getAttribute('position') as THREE.BufferAttribute;
      
      for (let i = 0; i < particleCount; i++) {
        // Calculate t along path (0 to 1)
        const t = ((state.clock.elapsedTime * speed + offsets[i]) % 1);
        
        // Lerp position
        posAttr.setXYZ(
          i,
          sourcePosition.x + (targetPosition.x - sourcePosition.x) * t,
          sourcePosition.y + (targetPosition.y - sourcePosition.y) * t,
          sourcePosition.z + (targetPosition.z - sourcePosition.z) * t
        );
      }
      
      posAttr.needsUpdate = true;
    }
  });
  
  return (
    <points ref={particlesRef} geometry={geometry}>
      <pointsMaterial
        color={color}
        size={0.05}
        transparent
        opacity={0.8}
        sizeAttenuation
      />
    </points>
  );
}

/**
 * Smart connection that chooses visualization based on layer sizes
 */
export function SmartConnection({
  sourcePosition,
  targetPosition,
  sourceNeurons = 16,
  targetNeurons = 16,
  color = '#4488ff',
  highlighted = false,
  animated = true,
  style = 'bundle',
}: NeuralConnectionProps) {
  const totalConnections = sourceNeurons * targetNeurons;
  
  // Choose visualization based on connection count
  if (style === 'single' || totalConnections < 50) {
    return (
      <SingleConnection
        sourcePosition={sourcePosition}
        targetPosition={targetPosition}
        color={color}
        highlighted={highlighted}
      />
    );
  }
  
  if (style === 'dense' || totalConnections < 500) {
    return (
      <>
        <DenseConnection
          sourcePosition={sourcePosition}
          targetPosition={targetPosition}
          sourceNeurons={sourceNeurons}
          targetNeurons={targetNeurons}
          color={color}
          highlighted={highlighted}
          animated={animated}
          connectionDensity={0.2}
        />
        {animated && (
          <FlowParticles
            sourcePosition={sourcePosition}
            targetPosition={targetPosition}
            color={color}
            particleCount={3}
            speed={0.5}
          />
        )}
      </>
    );
  }
  
  // For very dense connections, use bundled representation
  return (
    <>
      <BundledConnection
        sourcePosition={sourcePosition}
        targetPosition={targetPosition}
        sourceNeurons={sourceNeurons}
        targetNeurons={targetNeurons}
        color={color}
        highlighted={highlighted}
        animated={animated}
      />
      {animated && (
        <FlowParticles
          sourcePosition={sourcePosition}
          targetPosition={targetPosition}
          color="#ffffff"
          particleCount={5}
          speed={0.8}
        />
      )}
    </>
  );
}