Files
website/static/neural-network-background.js

1323 lines
48 KiB
JavaScript

/**
* Neural Network Background Animation
* Modern, darker, mystical theme using WebGL
* Subtle flowing network aesthetic
*/
class NeuralNetworkBackground {
constructor() {
// Canvas setup
this.canvas = document.createElement('canvas');
this.canvas.id = 'neural-network-background';
this.canvas.style.position = 'fixed';
this.canvas.style.top = '0';
this.canvas.style.left = '0';
this.canvas.style.width = '100%';
this.canvas.style.height = '100%';
this.canvas.style.zIndex = '-10'; // Ensure it's behind content but visible
this.canvas.style.pointerEvents = 'none';
this.canvas.style.opacity = '1'; // Force visibility
// If canvas already exists, remove it first
const existingCanvas = document.getElementById('neural-network-background');
if (existingCanvas) {
existingCanvas.remove();
}
// Append to body as first child to ensure it's behind everything
if (document.body.firstChild) {
document.body.insertBefore(this.canvas, document.body.firstChild);
} else {
document.body.appendChild(this.canvas);
}
// WebGL context
this.gl = this.canvas.getContext('webgl') || this.canvas.getContext('experimental-webgl');
if (!this.gl) {
console.warn('WebGL not supported, falling back to canvas rendering');
this.gl = null;
this.ctx = this.canvas.getContext('2d');
this.useWebGL = false;
} else {
this.useWebGL = true;
}
// Animation properties
this.nodes = [];
this.connections = [];
this.flows = []; // Flow animations along connections
this.animationFrameId = null;
this.isDarkMode = true; // Always use dark mode for the background
// Colors - Subtilere Farben mit weniger Intensität
this.darkModeColors = {
background: '#030610', // Dunkler Hintergrund beibehalten
nodeColor: '#6685cc', // Gedämpftere Knotenfarbe
nodePulse: '#a0b5e0', // Weniger intensives Pulsieren
connectionColor: '#485880', // Subtilere Verbindungen
flowColor: '#c0d7f0' // Sanfteres Blitz-Blau
};
// Farben für Light Mode dezenter und harmonischer gestalten
this.lightModeColors = {
background: '#f5f7fa', // Hellerer Hintergrund für subtileren Kontrast
nodeColor: '#5a77c2', // Gedämpfteres Blau
nodePulse: '#80b9e0', // Sanfteres Türkis für Glow
connectionColor: '#8a8fc0', // Dezenteres Lila
flowColor: '#6d97d0' // Sanfteres Blau für Blitze
};
// Konfigurationsobjekt für subtilere, sanftere Neuronen
this.config = {
nodeCount: 60, // Weniger Knoten für bessere Leistung und subtileres Aussehen
nodeSize: 2.8, // Kleinere Knoten für dezenteres Erscheinungsbild
nodeVariation: 0.6, // Weniger Varianz für gleichmäßigeres Erscheinungsbild
connectionDistance: 220, // Etwas geringere Verbindungsdistanz
connectionOpacity: 0.15, // Transparentere Verbindungen
animationSpeed: 0.02, // Langsamere Animation für sanftere Bewegung
pulseSpeed: 0.002, // Langsameres Pulsieren für subtilere Animation
flowSpeed: 0.6, // Langsamer für sanftere Animation
flowDensity: 0.002, // Deutlich weniger Blitze für subtileres Erscheinungsbild
flowLength: 0.12, // Kürzere Blitze für dezentere Effekte
maxConnections: 3, // Weniger Verbindungen für aufgeräumteres Erscheinungsbild
clusteringFactor: 0.4, // Moderate Clustering-Stärke
linesFadeDuration: 3500, // Längere Dauer für sanfteres Ein-/Ausblenden von Linien (ms)
linesWidth: 0.6, // Dünnere unterliegende Linien
linesOpacity: 0.25 // Geringere Opazität für Linien
};
// Initialize
this.init();
// Event listeners
window.addEventListener('resize', this.resizeCanvas.bind(this));
document.addEventListener('darkModeToggled', (event) => {
this.isDarkMode = event.detail.isDark;
});
// Log that the background is initialized
console.log('Neural Network Background initialized');
}
init() {
this.resizeCanvas();
if (this.useWebGL) {
this.initWebGL();
}
this.createNodes();
this.createConnections();
this.startAnimation();
}
resizeCanvas() {
const pixelRatio = window.devicePixelRatio || 1;
const width = window.innerWidth;
const height = window.innerHeight;
this.canvas.style.width = width + 'px';
this.canvas.style.height = height + 'px';
this.canvas.width = width * pixelRatio;
this.canvas.height = height * pixelRatio;
if (this.useWebGL) {
this.gl.viewport(0, 0, this.canvas.width, this.canvas.height);
} else if (this.ctx) {
this.ctx.scale(pixelRatio, pixelRatio);
}
// Recalculate node positions after resize
if (this.nodes.length) {
this.createNodes();
this.createConnections();
}
}
initWebGL() {
// Vertex shader
const vsSource = `
attribute vec2 aVertexPosition;
attribute float aPointSize;
uniform vec2 uResolution;
void main() {
// Convert from pixel to clip space
vec2 position = (aVertexPosition / uResolution) * 2.0 - 1.0;
// Flip Y coordinate
position.y = -position.y;
gl_Position = vec4(position, 0, 1);
gl_PointSize = aPointSize;
}
`;
// Fragment shader - Softer glow effect
const fsSource = `
precision mediump float;
uniform vec4 uColor;
void main() {
float distance = length(gl_PointCoord - vec2(0.5, 0.5));
// Softer glow with smoother falloff
float alpha = 1.0 - smoothstep(0.1, 0.5, distance);
alpha = pow(alpha, 1.5); // Make the glow even softer
gl_FragColor = vec4(uColor.rgb, uColor.a * alpha);
}
`;
// Initialize shaders
const vertexShader = this.loadShader(this.gl.VERTEX_SHADER, vsSource);
const fragmentShader = this.loadShader(this.gl.FRAGMENT_SHADER, fsSource);
// Create shader program
this.shaderProgram = this.gl.createProgram();
this.gl.attachShader(this.shaderProgram, vertexShader);
this.gl.attachShader(this.shaderProgram, fragmentShader);
this.gl.linkProgram(this.shaderProgram);
if (!this.gl.getProgramParameter(this.shaderProgram, this.gl.LINK_STATUS)) {
console.error('Unable to initialize the shader program: ' +
this.gl.getProgramInfoLog(this.shaderProgram));
return;
}
// Get attribute and uniform locations
this.programInfo = {
program: this.shaderProgram,
attribLocations: {
vertexPosition: this.gl.getAttribLocation(this.shaderProgram, 'aVertexPosition'),
pointSize: this.gl.getAttribLocation(this.shaderProgram, 'aPointSize')
},
uniformLocations: {
resolution: this.gl.getUniformLocation(this.shaderProgram, 'uResolution'),
color: this.gl.getUniformLocation(this.shaderProgram, 'uColor')
}
};
// Create buffers
this.positionBuffer = this.gl.createBuffer();
this.sizeBuffer = this.gl.createBuffer();
// Set clear color for WebGL context
const bgColor = this.hexToRgb(this.darkModeColors.background);
this.gl.clearColor(bgColor.r/255, bgColor.g/255, bgColor.b/255, 1.0);
}
loadShader(type, source) {
const shader = this.gl.createShader(type);
this.gl.shaderSource(shader, source);
this.gl.compileShader(shader);
if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) {
console.error('An error occurred compiling the shaders: ' +
this.gl.getShaderInfoLog(shader));
this.gl.deleteShader(shader);
return null;
}
return shader;
}
createNodes() {
this.nodes = [];
const width = this.canvas.width / (window.devicePixelRatio || 1);
const height = this.canvas.height / (window.devicePixelRatio || 1);
// Erstelle Cluster-Zentren für neuronale Netzwerkmuster
const clusterCount = Math.floor(5 + Math.random() * 4); // 5-8 Cluster
const clusters = [];
for (let i = 0; i < clusterCount; i++) {
clusters.push({
x: Math.random() * width,
y: Math.random() * height,
radius: 100 + Math.random() * 150
});
}
// Create nodes with random positions and properties
for (let i = 0; i < this.config.nodeCount; i++) {
// Entscheide, ob dieser Knoten zu einem Cluster gehört oder nicht
const useCluster = Math.random() < this.config.clusteringFactor;
let x, y;
if (useCluster && clusters.length > 0) {
// Wähle ein zufälliges Cluster
const cluster = clusters[Math.floor(Math.random() * clusters.length)];
const angle = Math.random() * Math.PI * 2;
const distance = Math.random() * cluster.radius;
// Platziere in der Nähe des Clusters mit einiger Streuung
x = cluster.x + Math.cos(angle) * distance;
y = cluster.y + Math.sin(angle) * distance;
// Stelle sicher, dass es innerhalb des Bildschirms bleibt
x = Math.max(0, Math.min(width, x));
y = Math.max(0, Math.min(height, y));
} else {
// Zufällige Position außerhalb von Clustern
x = Math.random() * width;
y = Math.random() * height;
}
// Bestimme die Knotengröße - wichtigere Knoten (in Clustern) sind größer
const nodeImportance = useCluster ? 1.2 : 0.8;
const size = this.config.nodeSize * nodeImportance + Math.random() * this.config.nodeVariation;
const node = {
x: x,
y: y,
size: size,
speed: {
x: (Math.random() - 0.5) * this.config.animationSpeed,
y: (Math.random() - 0.5) * this.config.animationSpeed
},
pulsePhase: Math.random() * Math.PI * 2, // Random starting phase
connections: [],
isActive: Math.random() < 0.3, // Some nodes start active for neural firing effect
lastFired: 0, // For neural firing animation
firingRate: 1000 + Math.random() * 4000 // Random firing rate in ms
};
this.nodes.push(node);
}
}
createConnections() {
this.connections = [];
this.flows = []; // Reset flows
// Create connections between nearby nodes
for (let i = 0; i < this.nodes.length; i++) {
const nodeA = this.nodes[i];
nodeA.connections = [];
// Sortiere andere Knoten nach Entfernung für bevorzugte nahe Verbindungen
const potentialConnections = [];
for (let j = 0; j < this.nodes.length; j++) {
if (i === j) continue;
const nodeB = this.nodes[j];
const dx = nodeB.x - nodeA.x;
const dy = nodeB.y - nodeA.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < this.config.connectionDistance) {
potentialConnections.push({
index: j,
distance: distance
});
}
}
// Sortiere nach Entfernung
potentialConnections.sort((a, b) => a.distance - b.distance);
// Wähle die nächsten N Verbindungen, maximal maxConnections
const maxConn = Math.min(
this.config.maxConnections,
potentialConnections.length,
1 + Math.floor(Math.random() * this.config.maxConnections)
);
for (let c = 0; c < maxConn; c++) {
const connection = potentialConnections[c];
const j = connection.index;
const nodeB = this.nodes[j];
const distance = connection.distance;
// Create weighted connection (closer = stronger)
const connectionStrength = Math.max(0, 1 - distance / this.config.connectionDistance);
const connOpacity = connectionStrength * this.config.connectionOpacity;
// Check if connection already exists
if (!this.connections.some(conn =>
(conn.from === i && conn.to === j) || (conn.from === j && conn.to === i)
)) {
// Neue Verbindung mit Ein-/Ausblend-Status
this.connections.push({
from: i,
to: j,
distance: distance,
opacity: connOpacity,
strength: connectionStrength,
hasFlow: false,
lastActivated: 0,
progress: 0, // Verbindung beginnt unsichtbar und baut sich auf
fadeState: 'in', // Status: 'in' = einblenden, 'visible' = sichtbar, 'out' = ausblenden
fadeStartTime: Date.now(), // Wann der Fade-Vorgang gestartet wurde
fadeTotalDuration: this.config.linesFadeDuration + Math.random() * 1000, // Zufällige Dauer
visibleDuration: 10000 + Math.random() * 15000, // Wie lange die Linie sichtbar bleibt
fadeProgress: 0, // Aktueller Fortschritt des Fade-Vorgangs (0-1)
buildSpeed: 0 // Geschwindigkeit, mit der die Verbindung aufgebaut wird
});
nodeA.connections.push(j);
nodeB.connections.push(i);
}
}
}
}
startAnimation() {
this.animationFrameId = requestAnimationFrame(this.animate.bind(this));
}
animate() {
// Update nodes
const width = this.canvas.width / (window.devicePixelRatio || 1);
const height = this.canvas.height / (window.devicePixelRatio || 1);
const now = Date.now();
// Simulate neural firing with reduced activity
for (let i = 0; i < this.nodes.length; i++) {
const node = this.nodes[i];
// Update pulse phase for smoother animation
node.pulsePhase += this.config.pulseSpeed * (1 + (node.connections.length * 0.04));
// Animate node position with gentler movement
node.x += node.speed.x * (Math.sin(now * 0.0003) * 0.4 + 0.4);
node.y += node.speed.y * (Math.cos(now * 0.0002) * 0.4 + 0.4);
// Keep nodes within bounds
if (node.x < 0 || node.x > width) {
node.speed.x *= -1;
node.x = Math.max(0, Math.min(width, node.x));
}
if (node.y < 0 || node.y > height) {
node.speed.y *= -1;
node.y = Math.max(0, Math.min(height, node.y));
}
// Check if node should fire based on reduced firing rate
if (now - node.lastFired > node.firingRate * 1.3) { // 30% langsamere Feuerrate
node.isActive = true;
node.lastFired = now;
node.activationTime = now; // Track when activation started
// Activate connected nodes with probability based on connection strength
for (const connIndex of node.connections) {
// Find the connection
const conn = this.connections.find(c =>
(c.from === i && c.to === connIndex) || (c.from === connIndex && c.to === i)
);
if (conn) {
// Mark connection as recently activated
conn.lastActivated = now;
// Wenn eine Verbindung aktiviert wird, verlängere ggf. ihre Sichtbarkeit
if (conn.fadeState === 'out') {
conn.fadeState = 'visible';
conn.fadeStartTime = now;
}
// Verbindung soll schneller aufgebaut werden, wenn ein Neuron feuert
if (conn.progress < 1) {
conn.buildSpeed = 0.015 + Math.random() * 0.01; // Schnellerer Aufbau während der Aktivierung
}
// Reduzierte Wahrscheinlichkeit für neue Flows
if (this.flows.length < 4 && Math.random() < conn.strength * 0.5) { // Reduzierte Wahrscheinlichkeit
this.flows.push({
connection: conn,
progress: 0,
direction: conn.from === i, // Flow from activated node
length: this.config.flowLength + Math.random() * 0.05, // Geringere Variation
intensity: 0.5 + Math.random() * 0.3, // Geringere Intensität für subtilere Darstellung
creationTime: now,
totalDuration: 1000 + Math.random() * 600 // Längere Dauer für sanftere Animation
});
}
// Probability for connected node to activate
if (Math.random() < conn.strength * 0.5) {
this.nodes[connIndex].isActive = true;
this.nodes[connIndex].activationTime = now;
this.nodes[connIndex].lastFired = now - Math.random() * 500; // Slight variation
}
}
}
} else if (now - node.lastFired > 400) { // Deactivate after longer period
node.isActive = false;
}
}
// Aktualisiere die Ein-/Ausblendung von Verbindungen
for (const connection of this.connections) {
const elapsedTime = now - connection.fadeStartTime;
// Update connection fade status
if (connection.fadeState === 'in') {
// Einblenden
connection.fadeProgress = Math.min(1.0, elapsedTime / connection.fadeTotalDuration);
if (connection.fadeProgress >= 1.0) {
connection.fadeState = 'visible';
connection.fadeStartTime = now;
}
} else if (connection.fadeState === 'visible') {
// Verbindung ist vollständig sichtbar
if (elapsedTime > connection.visibleDuration) {
connection.fadeState = 'out';
connection.fadeStartTime = now;
connection.fadeProgress = 1.0;
// Setze den Fortschritt zurück, damit die Verbindung neu aufgebaut werden kann
if (Math.random() < 0.7) {
connection.progress = 0;
}
}
} else if (connection.fadeState === 'out') {
// Ausblenden
connection.fadeProgress = Math.max(0.0, 1.0 - (elapsedTime / connection.fadeTotalDuration));
if (connection.fadeProgress <= 0.0) {
// Setze Verbindung zurück, damit sie wieder eingeblendet werden kann
if (Math.random() < 0.4) { // 40% Chance, direkt wieder einzublenden
connection.fadeState = 'in';
connection.fadeStartTime = now;
connection.fadeProgress = 0.0;
connection.visibleDuration = 10000 + Math.random() * 15000; // Neue Dauer generieren
// Setze den Fortschritt zurück, damit die Verbindung neu aufgebaut werden kann
connection.progress = 0;
} else {
// Kurze Pause, bevor die Verbindung wieder erscheint
connection.fadeState = 'hidden';
connection.fadeStartTime = now;
connection.hiddenDuration = 3000 + Math.random() * 7000;
// Setze den Fortschritt zurück, damit die Verbindung neu aufgebaut werden kann
connection.progress = 0;
}
}
} else if (connection.fadeState === 'hidden') {
// Verbindung ist unsichtbar, warte auf Wiedereinblendung
if (elapsedTime > connection.hiddenDuration) {
connection.fadeState = 'in';
connection.fadeStartTime = now;
connection.fadeProgress = 0.0;
// Verbindung wird komplett neu aufgebaut
connection.progress = 0;
}
}
// Animierter Verbindungsaufbau: progress inkrementieren, aber nur wenn aktiv
if (connection.progress < 1) {
// Verbindung wird nur aufgebaut, wenn sie gerade aktiv ist oder ein Blitz sie aufbaut
const buildingSpeed = connection.buildSpeed || 0.002; // Langsamer Standard-Aufbau
// Bau die Verbindung auf, wenn sie kürzlich aktiviert wurde
if (now - connection.lastActivated < 2000) {
connection.progress += buildingSpeed;
if (connection.progress > 1) connection.progress = 1;
}
// Zurücksetzen der Aufbaugeschwindigkeit
connection.buildSpeed = 0;
}
}
// Update flows with proper fading
this.updateFlows(now);
// Seltener neue Flows erstellen
if (Math.random() < this.config.flowDensity * 0.8 && this.flows.length < 4) { // Reduzierte Kapazität und Rate
this.createNewFlow(now);
}
// Recalculate connections occasionally for a living network
if (Math.random() < 0.005) { // Only recalculate 0.5% of the time for performance
this.createConnections();
}
// Render
if (this.useWebGL) {
this.renderWebGL(now);
} else {
this.renderCanvas(now);
}
// Continue animation
this.animationFrameId = requestAnimationFrame(this.animate.bind(this));
}
// Updated method to update flow animations with proper fading
updateFlows(now) {
// Update existing flows
for (let i = this.flows.length - 1; i >= 0; i--) {
const flow = this.flows[i];
// Calculate flow age for fading effects
const flowAge = now - flow.creationTime;
const flowProgress = flowAge / flow.totalDuration;
// Update flow progress
flow.progress += this.config.flowSpeed / flow.connection.distance;
// Remove completed or expired flows
if (flow.progress > 1.0 || flowProgress >= 1.0) {
this.flows.splice(i, 1);
}
}
}
// Updated method to create flow animations with timing info
createNewFlow(now) {
if (this.connections.length === 0 || this.flows.length >= 6) return;
// Select a random connection with preference for more connected nodes
let connectionIdx = Math.floor(Math.random() * this.connections.length);
let attempts = 0;
// Try to find a connection with more connected nodes
while (attempts < 5) {
const testIdx = Math.floor(Math.random() * this.connections.length);
const testConn = this.connections[testIdx];
const fromNode = this.nodes[testConn.from];
if (fromNode.connections.length > 2) {
connectionIdx = testIdx;
break;
}
attempts++;
}
const connection = this.connections[connectionIdx];
// Verbindung als "im Aufbau" markieren, wenn sie noch nicht vollständig ist
if (connection.progress < 1) {
connection.buildSpeed = 0.015 + Math.random() * 0.01; // Schnellerer Aufbau während eines Blitzes
}
// Create a new flow along this connection
this.flows.push({
connection: connection,
progress: 0,
direction: Math.random() > 0.5, // Randomly decide direction
length: this.config.flowLength + Math.random() * 0.1, // Slightly vary lengths
creationTime: now,
totalDuration: 800 + Math.random() * 500 // Zufällige Gesamtdauer (800-1300ms)
});
}
renderWebGL(now) {
this.gl.clear(this.gl.COLOR_BUFFER_BIT);
const width = this.canvas.width / (window.devicePixelRatio || 1);
const height = this.canvas.height / (window.devicePixelRatio || 1);
// Select shader program
this.gl.useProgram(this.programInfo.program);
// Set resolution uniform
this.gl.uniform2f(this.programInfo.uniformLocations.resolution, width, height);
// Draw connections first (behind nodes)
this.renderConnectionsWebGL(now);
// Draw flows on top of connections
this.renderFlowsWebGL(now);
// Draw nodes
this.renderNodesWebGL(now);
}
renderNodesWebGL(now) {
// Prepare node positions for WebGL
const positions = new Float32Array(this.nodes.length * 2);
const sizes = new Float32Array(this.nodes.length);
for (let i = 0; i < this.nodes.length; i++) {
const node = this.nodes[i];
positions[i * 2] = node.x;
positions[i * 2 + 1] = node.y;
// Sanftere Pulsation mit moderaterem Aktivierungsboost
const activationBoost = node.isActive ? 1.4 : 1.0;
let pulse = (Math.sin(node.pulsePhase) * 0.35 + 1.3) * activationBoost;
// Größe basierend auf Konnektivität und Wichtigkeit, aber subtiler
const connectivityFactor = 1 + (node.connections.length / this.config.maxConnections) * 1.1;
sizes[i] = node.size * pulse * connectivityFactor;
}
// Bind position buffer
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.positionBuffer);
this.gl.bufferData(this.gl.ARRAY_BUFFER, positions, this.gl.STATIC_DRAW);
this.gl.vertexAttribPointer(
this.programInfo.attribLocations.vertexPosition,
2, // components per vertex
this.gl.FLOAT, // data type
false, // normalize
0, // stride
0 // offset
);
this.gl.enableVertexAttribArray(this.programInfo.attribLocations.vertexPosition);
// Bind size buffer
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.sizeBuffer);
this.gl.bufferData(this.gl.ARRAY_BUFFER, sizes, this.gl.STATIC_DRAW);
this.gl.vertexAttribPointer(
this.programInfo.attribLocations.pointSize,
1, // components per vertex
this.gl.FLOAT, // data type
false, // normalize
0, // stride
0 // offset
);
this.gl.enableVertexAttribArray(this.programInfo.attribLocations.pointSize);
// Enable blending for all nodes
this.gl.enable(this.gl.BLEND);
this.gl.blendFunc(this.gl.SRC_ALPHA, this.gl.ONE); // Additive blending for glow
// Draw each node individually with its own color
for (let i = 0; i < this.nodes.length; i++) {
const node = this.nodes[i];
// Set node color - sanftere Hervorhebung von aktiven Knoten
const colorObj = this.isDarkMode ? this.darkModeColors : this.lightModeColors;
const nodeColor = this.hexToRgb(colorObj.nodeColor);
const nodePulseColor = this.hexToRgb(colorObj.nodePulse);
// Use pulse color for active nodes
let r = nodeColor.r / 255;
let g = nodeColor.g / 255;
let b = nodeColor.b / 255;
// Active nodes get slightly brighter color - subtiler
if (node.isActive) {
r = (r * 0.7 + nodePulseColor.r / 255 * 0.3);
g = (g * 0.7 + nodePulseColor.g / 255 * 0.3);
b = (b * 0.7 + nodePulseColor.b / 255 * 0.3);
}
// Subtilere Knoten mit reduzierter Opazität
this.gl.uniform4f(
this.programInfo.uniformLocations.color,
r, g, b,
node.isActive ? 0.85 : 0.75 // Geringere Sichtbarkeit für subtileres Erscheinungsbild
);
// Draw each node individually for better control
this.gl.drawArrays(this.gl.POINTS, i, 1);
}
}
renderConnectionsWebGL(now) {
for (const connection of this.connections) {
// Überspringe Verbindungen, die komplett unsichtbar sind
if (connection.fadeState === 'hidden' || connection.fadeProgress <= 0) continue;
const fromNode = this.nodes[connection.from];
const toNode = this.nodes[connection.to];
const progress = connection.progress || 1;
const x1 = fromNode.x;
const y1 = fromNode.y;
const x2 = fromNode.x + (toNode.x - fromNode.x) * progress;
const y2 = fromNode.y + (toNode.y - fromNode.y) * progress;
// Calculate opacity based on fade state
let opacity = connection.opacity * connection.fadeProgress;
// Erhöhe kurzzeitig die Opazität bei kürzlich aktivierten Verbindungen
if (connection.lastActivated && now - connection.lastActivated < 800) {
const timeFactor = 1 - ((now - connection.lastActivated) / 800);
opacity = Math.max(opacity, timeFactor * 0.3);
}
const positions = new Float32Array([
x1, y1,
x2, y2
]);
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.positionBuffer);
this.gl.bufferData(this.gl.ARRAY_BUFFER, positions, this.gl.STATIC_DRAW);
this.gl.vertexAttribPointer(
this.programInfo.attribLocations.vertexPosition,
2,
this.gl.FLOAT,
false,
0,
0
);
this.gl.enableVertexAttribArray(this.programInfo.attribLocations.vertexPosition);
this.gl.disableVertexAttribArray(this.programInfo.attribLocations.pointSize);
// Set color with calculated opacity
const colorObj = this.isDarkMode ? this.darkModeColors : this.lightModeColors;
const connColor = this.hexToRgb(colorObj.connectionColor);
this.gl.uniform4f(
this.programInfo.uniformLocations.color,
connColor.r / 255,
connColor.g / 255,
connColor.b / 255,
opacity
);
this.gl.enable(this.gl.BLEND);
this.gl.blendFunc(this.gl.SRC_ALPHA, this.gl.ONE);
this.gl.lineWidth(this.config.linesWidth);
this.gl.drawArrays(this.gl.LINES, 0, 2);
}
}
// New method to render the flowing animations
renderFlowsWebGL(now) {
// Für jeden Flow einen dezenten, echten Blitz als Zickzack zeichnen und Funken erzeugen
for (const flow of this.flows) {
const connection = flow.connection;
const fromNode = this.nodes[connection.from];
const toNode = this.nodes[connection.to];
const startProgress = flow.progress;
const endProgress = Math.min(1, startProgress + flow.length);
if (startProgress >= 1 || endProgress <= 0) continue;
const direction = flow.direction ? 1 : -1;
let p1, p2;
if (direction > 0) {
p1 = {
x: fromNode.x + (toNode.x - fromNode.x) * startProgress,
y: fromNode.y + (toNode.y - fromNode.y) * startProgress
};
p2 = {
x: fromNode.x + (toNode.x - fromNode.x) * endProgress,
y: fromNode.y + (toNode.y - fromNode.y) * endProgress
};
} else {
p1 = {
x: toNode.x + (fromNode.x - toNode.x) * startProgress,
y: toNode.y + (fromNode.y - toNode.y) * startProgress
};
p2 = {
x: toNode.x + (fromNode.x - toNode.x) * endProgress,
y: toNode.y + (fromNode.y - toNode.y) * endProgress
};
}
// Zickzack-Blitz generieren
const zigzag = this.generateZigZagPoints(p1, p2, 8, 10);
for (let i = 0; i < zigzag.length - 1; i++) {
const positions = new Float32Array([
zigzag[i].x, zigzag[i].y,
zigzag[i + 1].x, zigzag[i + 1].y
]);
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.positionBuffer);
this.gl.bufferData(this.gl.ARRAY_BUFFER, positions, this.gl.STATIC_DRAW);
this.gl.vertexAttribPointer(
this.programInfo.attribLocations.vertexPosition,
2,
this.gl.FLOAT,
false,
0,
0
);
this.gl.enableVertexAttribArray(this.programInfo.attribLocations.vertexPosition);
this.gl.disableVertexAttribArray(this.programInfo.attribLocations.pointSize);
// Dezenter, leuchtender Blitz
const colorObj = this.isDarkMode ? this.darkModeColors : this.lightModeColors;
const flowColor = this.hexToRgb(colorObj.flowColor);
this.gl.uniform4f(
this.programInfo.uniformLocations.color,
flowColor.r / 255,
flowColor.g / 255,
flowColor.b / 255,
0.55 // Dezent, aber sichtbar
);
this.gl.enable(this.gl.BLEND);
this.gl.blendFunc(this.gl.SRC_ALPHA, this.gl.ONE);
this.gl.lineWidth(1.3); // Schmaler Blitz
this.gl.drawArrays(this.gl.LINES, 0, 2);
}
// Funken erzeugen - echte elektrische Funken
const sparks = this.generateSparkPoints(zigzag, 7 + Math.floor(Math.random() * 3));
for (const spark of sparks) {
// Helles Weiß-Blau für elektrische Funken
this.gl.uniform4f(
this.programInfo.uniformLocations.color,
0.88, 0.95, 1.0, 0.65 // Elektrisches Blau-Weiß
);
// Position für den Funken setzen
const sparkPos = new Float32Array([spark.x, spark.y]);
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.positionBuffer);
this.gl.bufferData(this.gl.ARRAY_BUFFER, sparkPos, this.gl.STATIC_DRAW);
// Punktgröße setzen
const sizes = new Float32Array([spark.size * 3.0]);
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.sizeBuffer);
this.gl.bufferData(this.gl.ARRAY_BUFFER, sizes, this.gl.STATIC_DRAW);
this.gl.vertexAttribPointer(
this.programInfo.attribLocations.vertexPosition,
2,
this.gl.FLOAT,
false,
0,
0
);
this.gl.enableVertexAttribArray(this.programInfo.attribLocations.vertexPosition);
this.gl.vertexAttribPointer(
this.programInfo.attribLocations.pointSize,
1,
this.gl.FLOAT,
false,
0,
0
);
this.gl.enableVertexAttribArray(this.programInfo.attribLocations.pointSize);
this.gl.drawArrays(this.gl.POINTS, 0, 1);
}
}
}
renderCanvas(now) {
// Clear canvas
const width = this.canvas.width / (window.devicePixelRatio || 1);
const height = this.canvas.height / (window.devicePixelRatio || 1);
this.ctx.clearRect(0, 0, width, height);
// Set background
const backgroundColor = this.isDarkMode
? this.darkModeColors.background
: this.lightModeColors.background;
this.ctx.fillStyle = backgroundColor;
this.ctx.fillRect(0, 0, width, height);
// Draw connections with fade effects
const connectionColor = this.isDarkMode
? this.darkModeColors.connectionColor
: this.lightModeColors.connectionColor;
for (const connection of this.connections) {
// Überspringe Verbindungen, die komplett unsichtbar sind
if (connection.fadeState === 'hidden' || connection.fadeProgress <= 0) continue;
const fromNode = this.nodes[connection.from];
const toNode = this.nodes[connection.to];
// Zeichne nur den Teil der Verbindung, der schon aufgebaut wurde
const progress = connection.progress || 0;
if (progress <= 0) continue; // Skip if no progress yet
const x1 = fromNode.x;
const y1 = fromNode.y;
// Endpunkt basiert auf dem aktuellen Fortschritt
const x2 = x1 + (toNode.x - x1) * progress;
const y2 = y1 + (toNode.y - y1) * progress;
// Zeichne die unterliegende Linie mit Ein-/Ausblendung
this.ctx.beginPath();
this.ctx.moveTo(x1, y1);
this.ctx.lineTo(x2, y2);
const rgbColor = this.hexToRgb(connectionColor);
// Calculate opacity based on fade state
let opacity = connection.opacity * connection.fadeProgress;
// Erhöhe kurzzeitig die Opazität bei kürzlich aktivierten Verbindungen
if (connection.lastActivated && now - connection.lastActivated < 800) {
const timeFactor = 1 - ((now - connection.lastActivated) / 800);
opacity = Math.max(opacity, timeFactor * this.config.linesOpacity);
}
this.ctx.strokeStyle = `rgba(${rgbColor.r}, ${rgbColor.g}, ${rgbColor.b}, ${opacity})`;
this.ctx.lineWidth = this.config.linesWidth;
// Leichter Glow-Effekt für die Linien
if (opacity > 0.1) {
this.ctx.shadowColor = `rgba(${rgbColor.r}, ${rgbColor.g}, ${rgbColor.b}, 0.15)`;
this.ctx.shadowBlur = 3;
} else {
this.ctx.shadowBlur = 0;
}
this.ctx.stroke();
// Zeichne einen Fortschrittspunkt am Ende der sich aufbauenden Verbindung
if (progress < 0.95 && connection.fadeProgress > 0.5) {
this.ctx.beginPath();
this.ctx.arc(x2, y2, 1.5, 0, Math.PI * 2);
this.ctx.fillStyle = `rgba(${rgbColor.r}, ${rgbColor.g}, ${rgbColor.b}, ${opacity * 1.3})`;
this.ctx.fill();
}
this.ctx.shadowBlur = 0; // Reset shadow for other elements
}
// Draw flows with fading effect
this.renderFlowsCanvas(now);
// Draw nodes with enhanced animations
const nodeColor = this.isDarkMode
? this.darkModeColors.nodeColor
: this.lightModeColors.nodeColor;
const nodePulse = this.isDarkMode
? this.darkModeColors.nodePulse
: this.lightModeColors.nodePulse;
for (const node of this.nodes) {
// Verbesserte Pulsation mit Aktivierungsboost
const activationBoost = node.isActive ? 1.7 : 1.0;
const pulse = (Math.sin(node.pulsePhase) * 0.45 + 1.4) * activationBoost;
// Größe basierend auf Konnektivität und Wichtigkeit
const connectivityFactor = 1 + (node.connections.length / this.config.maxConnections) * 1.4;
const nodeSize = node.size * pulse * connectivityFactor;
// Verbesserte Leuchtkraft und Glow-Effekt
const rgbNodeColor = this.hexToRgb(nodeColor);
const rgbPulseColor = this.hexToRgb(nodePulse);
// Mische Farben basierend auf Aktivierung
let r, g, b;
if (node.isActive) {
r = (rgbNodeColor.r * 0.3 + rgbPulseColor.r * 0.7);
g = (rgbNodeColor.g * 0.3 + rgbPulseColor.g * 0.7);
b = (rgbNodeColor.b * 0.3 + rgbPulseColor.b * 0.7);
} else {
r = rgbNodeColor.r;
g = rgbNodeColor.g;
b = rgbNodeColor.b;
}
// Äußerer Glow
const glow = this.ctx.createRadialGradient(
node.x, node.y, 0,
node.x, node.y, nodeSize * 4.5
);
// Intensiveres Zentrum und weicherer Übergang
glow.addColorStop(0, `rgba(${r}, ${g}, ${b}, ${node.isActive ? 0.95 : 0.8})`);
glow.addColorStop(0.4, `rgba(${r}, ${g}, ${b}, 0.45)`);
glow.addColorStop(1, `rgba(${r}, ${g}, ${b}, 0)`);
this.ctx.beginPath();
this.ctx.arc(node.x, node.y, nodeSize, 0, Math.PI * 2);
this.ctx.fillStyle = glow;
this.ctx.globalAlpha = node.isActive ? 1.0 : 0.92;
this.ctx.fill();
// Innerer Kern für stärkeren Leuchteffekt
if (node.isActive) {
this.ctx.beginPath();
this.ctx.arc(node.x, node.y, nodeSize * 0.4, 0, Math.PI * 2);
this.ctx.fillStyle = `rgba(${rgbPulseColor.r}, ${rgbPulseColor.g}, ${rgbPulseColor.b}, 0.9)`;
this.ctx.fill();
}
this.ctx.globalAlpha = 1.0;
}
}
// New method to render flows in Canvas mode with fading
renderFlowsCanvas(now) {
if (!this.flows.length) return;
// Für jeden Flow in der Blitzanimation
for (const flow of this.flows) {
const connection = flow.connection;
const fromNode = this.nodes[connection.from];
const toNode = this.nodes[connection.to];
// Berechne den Fortschritt der Connection und des Flows
const connProgress = connection.progress || 1;
// Flussrichtung bestimmen
const [startNode, endNode] = flow.direction ? [fromNode, toNode] : [toNode, fromNode];
// Berücksichtige den Verbindungs-Fortschritt
const maxDistance = Math.min(connProgress, 1) * Math.sqrt(
Math.pow(endNode.x - startNode.x, 2) +
Math.pow(endNode.y - startNode.y, 2)
);
// Berechne den aktuellen Fortschritt mit Ein- und Ausblendung
const flowAge = now - flow.creationTime;
const flowLifetime = flow.totalDuration;
let fadeFactor = 1.0;
// Sanftere Ein- und Ausblendung für Blitzeffekte
if (flowAge < flowLifetime * 0.3) {
// Einblenden - sanfter und länger
fadeFactor = flowAge / (flowLifetime * 0.3);
} else if (flowAge > flowLifetime * 0.7) {
// Ausblenden - sanfter und länger
fadeFactor = 1.0 - ((flowAge - flowLifetime * 0.7) / (flowLifetime * 0.3));
}
// Flow-Fortschritt
const startProgress = Math.max(0.0, flow.progress - flow.length);
const endProgress = Math.min(flow.progress, connProgress);
// Start- und Endpunkte basierend auf dem Fortschritt
const p1 = {
x: startNode.x + (endNode.x - startNode.x) * startProgress,
y: startNode.y + (endNode.y - startNode.y) * startProgress
};
const p2 = {
x: startNode.x + (endNode.x - startNode.x) * endProgress,
y: startNode.y + (endNode.y - startNode.y) * endProgress
};
// Prüfe, ob der Fluss den aktuellen Verbindungsfortschritt überschritten hat
if (endProgress > connProgress) continue;
// Farbe des Flusses basierend auf dem aktuellen Modus
const flowColor = this.isDarkMode ? this.darkModeColors.flowColor : this.lightModeColors.flowColor;
const rgbFlowColor = this.hexToRgb(flowColor);
const baseAngle = Math.atan2(p2.y - p1.y, p2.x - p1.x);
this.ctx.save();
// Subtilere Untergrundspur für den Blitz
this.ctx.beginPath();
this.ctx.moveTo(p1.x, p1.y);
this.ctx.lineTo(p2.x, p2.y);
this.ctx.strokeStyle = `rgba(${rgbFlowColor.r}, ${rgbFlowColor.g}, ${rgbFlowColor.b}, ${0.15 * fadeFactor})`;
this.ctx.lineWidth = 3;
this.ctx.shadowColor = `rgba(${rgbFlowColor.r}, ${rgbFlowColor.g}, ${rgbFlowColor.b}, ${0.1 * fadeFactor})`;
this.ctx.shadowBlur = 7;
this.ctx.stroke();
// Zickzack-Blitz mit geringerer Vibration generieren
const zigzag = this.generateZigZagPoints(p1, p2, 6, 7);
// Hauptblitz mit dezenterem Ein-/Ausblendeffekt
this.ctx.strokeStyle = `rgba(${rgbFlowColor.r}, ${rgbFlowColor.g}, ${rgbFlowColor.b}, ${0.5 * fadeFactor})`;
this.ctx.lineWidth = 1.2;
this.ctx.shadowColor = `rgba(${rgbFlowColor.r}, ${rgbFlowColor.g}, ${rgbFlowColor.b}, ${0.25 * fadeFactor})`;
this.ctx.shadowBlur = 6;
this.ctx.beginPath();
this.ctx.moveTo(zigzag[0].x, zigzag[0].y);
for (let i = 1; i < zigzag.length; i++) {
this.ctx.lineTo(zigzag[i].x, zigzag[i].y);
}
this.ctx.stroke();
// Weniger Funken mit geringerer Vibration
const sparks = this.generateSparkPoints(zigzag, 4 + Math.floor(Math.random() * 2));
// Dezenteres Funkenlicht mit Ein-/Ausblendeffekt
const sparkBaseOpacity = this.isDarkMode ? 0.65 : 0.55;
const sparkBaseColor = this.isDarkMode
? `rgba(220, 235, 245, ${sparkBaseOpacity * fadeFactor})`
: `rgba(180, 220, 245, ${sparkBaseOpacity * fadeFactor})`;
for (const spark of sparks) {
this.ctx.beginPath();
// Subtilere Stern/Funken-Form
const points = 4 + Math.floor(Math.random() * 3); // 4-6 Spitzen
const outerRadius = spark.size * 1.8;
const innerRadius = spark.size * 0.4;
for (let i = 0; i < points * 2; i++) {
const radius = i % 2 === 0 ? outerRadius : innerRadius;
const angle = (i * Math.PI) / points;
const x = spark.x + Math.cos(angle) * radius;
const y = spark.y + Math.sin(angle) * radius;
if (i === 0) {
this.ctx.moveTo(x, y);
} else {
this.ctx.lineTo(x, y);
}
}
this.ctx.closePath();
this.ctx.fillStyle = sparkBaseColor;
this.ctx.shadowColor = this.isDarkMode
? `rgba(170, 215, 245, ${0.4 * fadeFactor})`
: `rgba(140, 200, 245, ${0.3 * fadeFactor})`;
this.ctx.shadowBlur = 7;
this.ctx.fill();
}
// Dezenterer Fortschrittseffekt an der Spitze des Blitzes
if (endProgress >= connProgress - 0.05 && connProgress < 0.95) {
const tipGlow = this.ctx.createRadialGradient(
p2.x, p2.y, 0,
p2.x, p2.y, 6
);
tipGlow.addColorStop(0, `rgba(${rgbFlowColor.r}, ${rgbFlowColor.g}, ${rgbFlowColor.b}, ${0.7 * fadeFactor})`);
tipGlow.addColorStop(1, `rgba(${rgbFlowColor.r}, ${rgbFlowColor.g}, ${rgbFlowColor.b}, 0)`);
this.ctx.fillStyle = tipGlow;
this.ctx.beginPath();
this.ctx.arc(p2.x, p2.y, 6, 0, Math.PI * 2);
this.ctx.fill();
}
// Sanftere Start- und Endblitz-Fades
if (startProgress < 0.1) {
const startFade = startProgress / 0.1; // 0 bis 1
const startGlow = this.ctx.createRadialGradient(
p1.x, p1.y, 0,
p1.x, p1.y, 8 * startFade
);
startGlow.addColorStop(0, `rgba(${rgbFlowColor.r}, ${rgbFlowColor.g}, ${rgbFlowColor.b}, ${0.4 * fadeFactor * startFade})`);
startGlow.addColorStop(1, `rgba(${rgbFlowColor.r}, ${rgbFlowColor.g}, ${rgbFlowColor.b}, 0)`);
this.ctx.fillStyle = startGlow;
this.ctx.beginPath();
this.ctx.arc(p1.x, p1.y, 8 * startFade, 0, Math.PI * 2);
this.ctx.fill();
}
this.ctx.restore();
}
}
// Helper method to convert hex to RGB
hexToRgb(hex) {
// Remove # if present
hex = hex.replace(/^#/, '');
// Handle rgba hex format
let alpha = 1;
if (hex.length === 8) {
alpha = parseInt(hex.slice(6, 8), 16) / 255;
hex = hex.slice(0, 6);
}
// Parse hex values
const bigint = parseInt(hex, 16);
const r = (bigint >> 16) & 255;
const g = (bigint >> 8) & 255;
const b = bigint & 255;
return { r, g, b, a: alpha };
}
// Cleanup method
destroy() {
if (this.animationFrameId) {
cancelAnimationFrame(this.animationFrameId);
}
window.removeEventListener('resize', this.resizeCanvas.bind(this));
if (this.canvas && this.canvas.parentNode) {
this.canvas.parentNode.removeChild(this.canvas);
}
if (this.gl) {
// Clean up WebGL resources
this.gl.deleteBuffer(this.positionBuffer);
this.gl.deleteBuffer(this.sizeBuffer);
this.gl.deleteProgram(this.shaderProgram);
}
}
// Hilfsfunktion: Erzeuge Zickzack-Punkte für einen Blitz mit geringerer Vibration
generateZigZagPoints(start, end, segments = 5, amplitude = 8) {
const points = [start];
const mainAngle = Math.atan2(end.y - start.y, end.x - start.x);
// Berechne die Gesamtlänge des Blitzes
const totalDistance = Math.sqrt(
Math.pow(end.x - start.x, 2) +
Math.pow(end.y - start.y, 2)
);
// Geringere Amplitude für subtilere Zickzack-Muster
const baseAmplitude = totalDistance * 0.12; // Reduziert für sanfteres Erscheinungsbild
for (let i = 1; i < segments; i++) {
const t = i / segments;
const x = start.x + (end.x - start.x) * t;
const y = start.y + (end.y - start.y) * t;
// Geringere Vibration durch kleinere Zufallsvariationen
const perpendicularAngle = mainAngle + Math.PI/2;
const variation = (Math.random() * 0.8 - 0.4); // Kleinere Variation für sanftere Muster
// Mal Links, mal Rechts für sanften Blitz
const directionFactor = (i % 2 === 0) ? 1 : -1;
const offset = baseAmplitude * (Math.sin(i * Math.PI) + variation) * directionFactor;
points.push({
x: x + Math.cos(perpendicularAngle) * offset,
y: y + Math.sin(perpendicularAngle) * offset
});
}
points.push(end);
return points;
}
// Hilfsfunktion: Erzeuge dezentere Funkenpunkte mit gemäßigter Verteilung
generateSparkPoints(zigzag, sparkCount = 4) {
const sparks = [];
// Weniger Funken
const actualSparkCount = Math.min(sparkCount, zigzag.length);
// Funken an zufälligen Stellen entlang des Blitzes
for (let i = 0; i < actualSparkCount; i++) {
// Zufälliges Segment des Zickzacks auswählen
const segIndex = Math.floor(Math.random() * (zigzag.length - 1));
// Bestimme Richtung des Segments
const dx = zigzag[segIndex + 1].x - zigzag[segIndex].x;
const dy = zigzag[segIndex + 1].y - zigzag[segIndex].y;
const segmentAngle = Math.atan2(dy, dx);
// Zufällige Position entlang des Segments
const t = Math.random();
const x = zigzag[segIndex].x + dx * t;
const y = zigzag[segIndex].y + dy * t;
// Rechtwinkliger Versatz vom Segment (sanftere Verteilung)
const offsetAngle = segmentAngle + Math.PI/2;
const offsetDistance = Math.random() * 4 - 2; // Geringerer Offset für dezentere Funken
sparks.push({
x: x + Math.cos(offsetAngle) * offsetDistance,
y: y + Math.sin(offsetAngle) * offsetDistance,
size: 1 + Math.random() * 1.5 // Kleinere Funkengröße für subtilere Effekte
});
}
return sparks;
}
}
// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
// Short delay to ensure DOM is fully loaded
setTimeout(() => {
if (!window.neuralNetworkBackground) {
console.log('Creating Neural Network Background');
window.neuralNetworkBackground = new NeuralNetworkBackground();
}
}, 100);
});
// Re-initialize when page is fully loaded (for safety)
window.addEventListener('load', () => {
if (!window.neuralNetworkBackground) {
console.log('Re-initializing Neural Network Background on full load');
window.neuralNetworkBackground = new NeuralNetworkBackground();
}
});
// Event listener to clean up when the window is closed
window.addEventListener('beforeunload', function() {
if (window.neuralNetworkBackground) {
window.neuralNetworkBackground.destroy();
}
});