feature/clothsimulation #28

Merged
lobo merged 8 commits from feature/clothsimulation into main 2026-02-24 09:31:35 +01:00
7 changed files with 154 additions and 22 deletions
Showing only changes of commit ab3bca4395 - Show all commits

View File

@@ -3,11 +3,15 @@
<mat-card-title>{{ 'CLOTH.TITLE' | translate }}</mat-card-title>
</mat-card-header>
<mat-card-content>
<app-information [algorithmInformation]="algoInformation"/>
<div class="controls-container">
<div class="controls-panel">
<button mat-raised-button color="primary" (click)="toggleWind()">
{{ isWindActive ? ('CLOTH.WIND_OFF' | translate) : ('CLOTH.WIND_ON' | translate) }}
</button>
<button mat-raised-button color="primary" (click)="toggleMesh()">
{{ isOutlineActive ? ('CLOTH.OUTLINE_OFF' | translate) : ('CLOTH.OUTLINE_ON' | translate) }}
</button>
</div>
</div>
<app-babylon-canvas

View File

@@ -17,6 +17,9 @@ import {
} from './cloth.shader';
import {MatButton} from '@angular/material/button';
import {ClothBuffers, ClothConfig, ClothData, ClothPipelines} from './cloth.model';
import {Information} from '../information/information';
import {AlgorithmInformation} from '../information/information.models';
import {UrlConstants} from '../../../constants/UrlConstants';
@Component({
selector: 'app-cloth',
@@ -27,7 +30,8 @@ import {ClothBuffers, ClothConfig, ClothData, ClothPipelines} from './cloth.mode
MatCardTitle,
TranslatePipe,
BabylonCanvas,
MatButton
MatButton,
Information
],
templateUrl: './cloth.component.html',
styleUrl: './cloth.component.scss',
@@ -37,7 +41,7 @@ export class ClothComponent {
private simulationTime: number = 0;
private clothMesh: GroundMesh | null = null;
public isWindActive: boolean = false;
public isOutlineActive: boolean = false;
public renderConfig: RenderConfig = {
mode: '3D',
@@ -45,6 +49,39 @@ export class ClothComponent {
shaderLanguage: ShaderLanguage.WGSL
};
algoInformation: AlgorithmInformation = {
title: 'CLOTH.EXPLANATION.TITLE',
entries: [
{
name: 'CLOTH.EXPLANATION.CLOTH_SIMULATION_EXPLANATION_TITLE',
description: 'CLOTH.EXPLANATION.CLOTH_SIMULATION_EXPLANATION',
link: UrlConstants.MANDELBULB_WIKI,
translateName: true
},
{
name: 'CLOTH.EXPLANATION.XPBD_EXPLANATION_TITLE',
description: 'CLOTH.EXPLANATION.XPBD_EXPLANATION',
link: UrlConstants.MANDELBOX_WIKI,
translateName: true
},
{
name: 'CLOTH.EXPLANATION.GPU_PARALLELIZATION_EXPLANATION_TITLE',
description: 'CLOTH.EXPLANATION.GPU_PARALLELIZATION_EXPLANATION',
link: UrlConstants.JULIA3D_WIKI,
translateName: true
},
{
name: 'CLOTH.EXPLANATION.DATA_STRUCTURES_EXPLANATION_TITLE',
description: 'CLOTH.EXPLANATION.DATA_STRUCTURES_EXPLANATION',
link: UrlConstants.JULIA3D_WIKI,
translateName: true
}
],
disclaimer: 'CLOTH.EXPLANATION.DISCLAIMER',
disclaimerBottom: '',
disclaimerListEntry: ['CLOTH.EXPLANATION.DISCLAIMER_1', 'CLOTH.EXPLANATION.DISCLAIMER_2', 'CLOTH.EXPLANATION.DISCLAIMER_3', 'CLOTH.EXPLANATION.DISCLAIMER_4']
};
/**
* Called when the Babylon scene is ready.
* @param event The scene event data.
@@ -58,6 +95,14 @@ export class ClothComponent {
this.isWindActive = !this.isWindActive;
}
public toggleMesh(): void {
this.isOutlineActive = !this.isOutlineActive;
if (!this.clothMesh?.material) {
return;
}
this.clothMesh.material.wireframe = this.isOutlineActive;
}
/**
* Initializes and starts the cloth simulation.
*/
@@ -151,11 +196,38 @@ export class ClothComponent {
for (let x = 0; x < config.gridWidth; x++) addConstraint(constraintsP3, y * config.gridWidth + x, (y + 1) * config.gridWidth + x);
}
const constraintsP4: number[] = [];
const constraintsP5: number[] = [];
const constraintsP6: number[] = [];
const constraintsP7: number[] = [];
const diagSpacing = config.spacing * Math.SQRT2;
const addDiagConstraint = (arr: number[], a: number, b: number): void => {
arr.push(a, b, diagSpacing, 1.0);
};
for (let y = 0; y < config.gridHeight - 1; y++) {
const arr = (y % 2 === 0) ? constraintsP4 : constraintsP5;
for (let x = 0; x < config.gridWidth - 1; x++) {
addDiagConstraint(arr, y * config.gridWidth + x, (y + 1) * config.gridWidth + (x + 1));
}
}
for (let y = 0; y < config.gridHeight - 1; y++) {
const arr = (y % 2 === 0) ? constraintsP6 : constraintsP7;
for (let x = 0; x < config.gridWidth - 1; x++) {
addDiagConstraint(arr, y * config.gridWidth + (x + 1), (y + 1) * config.gridWidth + x);
}
}
return {
positions: positionsData,
prevPositions: prevPositionsData,
velocities: velocitiesData,
constraints: [constraintsP0, constraintsP1, constraintsP2, constraintsP3],
constraints: [
constraintsP0, constraintsP1, constraintsP2, constraintsP3,
constraintsP4, constraintsP5, constraintsP6, constraintsP7
],
params: new Float32Array(8)
};
}
@@ -293,10 +365,9 @@ export class ClothComponent {
// 2. XPBD Solver (Substeps) - Graph Coloring Phase
for (let i = 0; i < substeps; i++) {
pipelines.solvers[0].dispatch(dispatchXConstraints[0], 1, 1);
pipelines.solvers[1].dispatch(dispatchXConstraints[1], 1, 1);
pipelines.solvers[2].dispatch(dispatchXConstraints[2], 1, 1);
pipelines.solvers[3].dispatch(dispatchXConstraints[3], 1, 1);
for (let phase = 0; phase < pipelines.solvers.length; phase++) {
pipelines.solvers[phase].dispatch(dispatchXConstraints[phase], 1, 1);
}
}
// 3. Update velocities

View File

@@ -22,22 +22,23 @@ export const CLOTH_SHARED_STRUCTS = `
// ==========================================
export const CLOTH_VERTEX_SHADER_WGSL = `
attribute uv : vec2<f32>;
// Storage Buffer
var<storage, read> positions : array<vec4<f32>>;
// Babylon Preprocessor Magic
uniform viewProjection : mat4x4<f32>;
// Varyings, um Daten an den Fragment-Shader zu senden
varying vUV : vec2<f32>;
varying vWorldPos : vec3<f32>; // NEU: Wir brauchen die 3D-Position für das Licht!
@vertex
fn main(input : VertexInputs) -> FragmentInputs {
var output : FragmentInputs;
let worldPos = positions[input.vertexIndex].xyz;
output.position = uniforms.viewProjection * vec4<f32>(worldPos, 1.0);
output.vUV = input.uv;
output.vWorldPos = worldPos; // Position weitergeben
return output;
}
@@ -48,13 +49,24 @@ export const CLOTH_VERTEX_SHADER_WGSL = `
// ==========================================
export const CLOTH_FRAGMENT_SHADER_WGSL = `
varying vUV : vec2<f32>;
varying vWorldPos : vec3<f32>;
@fragment
fn main(input: FragmentInputs) -> FragmentOutputs {
var output: FragmentOutputs;
let color = vec3<f32>(input.vUV.x * 0.8, input.vUV.y * 0.8, 0.9);
output.color = vec4<f32>(color, 1.0);
let dx = dpdx(input.vWorldPos);
let dy = dpdy(input.vWorldPos);
let normal = normalize(cross(dx, dy));
let lightDir = normalize(vec3<f32>(1.0, 1.0, 0.5));
let diffuse = max(0.0, abs(dot(normal, lightDir)));
let ambient = 0.3;
let lightIntensity = ambient + (diffuse * 0.7);
let grid = (floor(input.vUV.x * 20.0) + floor(input.vUV.y * 20.0)) % 2.0;
let baseColor = mix(vec3<f32>(0.8, 0.4, 0.15), vec3<f32>(0.9, 0.5, 0.2), grid);
let finalColor = baseColor * lightIntensity;
output.color = vec4<f32>(finalColor, 1.0);
return output;
}

View File

@@ -5,7 +5,14 @@
@for (algo of algorithmInformation.entries; track algo)
{
<p>
<strong>{{ algo.name }}</strong> {{ algo.description | translate }}
<strong>
@if(algo.translateName){
{{ algo.name | translate}}
} @else {
{{ algo.name }}
}
</strong>
{{ algo.description | translate }}
<a href="{{algo.link}}" target="_blank" rel="noopener noreferrer">Wikipedia</a>
</p>
}

View File

@@ -10,5 +10,5 @@ export interface AlgorithmEntry {
name: string;
description: string;
link: string;
translateName?: boolean;
}

View File

@@ -57,7 +57,8 @@
"K8S": "Kubernetes / k3d",
"POSTGRES": "PostgreSQL",
"MONGO": "MongoDB",
"GRAFANA": "Grafana/Prometheus"
"GRAFANA": "Grafana/Prometheus",
"DOCKER": "Docker"
},
"XP": {
"COMPANY8": {
@@ -472,9 +473,27 @@
}
},
"CLOTH": {
"TITLE": "Stoff-Simulation",
"TITLE": "Stoffsimulation",
"WIND_ON": "Wind Einschalten",
"WIND_OFF": "Wind Ausschalten"
"WIND_OFF": "Wind Ausschalten",
"OUTLINE_ON": "Mesh anzeigen",
"OUTLINE_OFF": "Mesh ausschalten",
"EXPLANATION": {
"TITLE": "Echtzeit-Stoffsimulation auf der GPU",
"CLOTH_SIMULATION_EXPLANATION_TITLE": "Stoffsimulation",
"XPBD_EXPLANATION_TITLE": "XPBD (Extended Position-Based Dynamics)",
"GPU_PARALLELIZATION_EXPLANATION_TITLE": "GPU Parallelisierung",
"DATA_STRUCTURES_EXPLANATION_TITLE": "Datenstrukturen",
"CLOTH_SIMULATION_EXPLANATION": "Stoffsimulationen modellieren Textilien meist als ein Gitter aus Massepunkten (Vertices), die durch unsichtbare Verbindungen zusammengehalten werden. Ziel ist es, physikalische Einflüsse wie Schwerkraft, Wind und Kollisionen in Echtzeit darzustellen, ohne dass das Material zerreißt oder sich unnatürlich wie Gummi dehnt.",
"XPBD_EXPLANATION": "XPBD (Extended Position-Based Dynamics) ist ein moderner Algorithmus, der statt Beschleunigungen direkt die Positionen der Punkte manipuliert, um Abstandsbedingungen (Constraints) zu erfüllen. Das 'Extended' bedeutet, dass echte physikalische Steifigkeit unabhängig von der Framerate simuliert wird. Vorteil: Absolut stabil, explodiert nicht und topologische Änderungen (wie das Zerschneiden von Stoff) sind trivial. Nachteil: Es ist ein iteratives Näherungsverfahren und physikalisch minimal weniger akkurat als komplexe Matrix-Löser.",
"GPU_PARALLELIZATION_EXPLANATION": "Um zehntausende Punkte parallel auf der Grafikkarte zu berechnen, muss man 'Race Conditions' verhindern also dass zwei Rechenkerne gleichzeitig denselben Knotenpunkt verschieben. Die Lösung nennt sich 'Independent Sets' (oder Graph Coloring): Die Verbindungen werden in isolierte Gruppen (z. B. 4 Phasen bei einem Gitter) unterteilt, in denen sich kein einziger Punkt überschneidet. So kann die GPU jede Gruppe blind und mit maximaler Geschwindigkeit abarbeiten.",
"DATA_STRUCTURES_EXPLANATION": "Für maximale GPU-Performance müssen Daten speicherfreundlich ausgerichtet werden (16-Byte-Alignment). Anstatt viele einzelne Variablen zu nutzen, packt man Informationen clever in 4er-Blöcke (vec4). Ein Vertex speichert so z. B. [X, Y, Z, Inverse_Masse]. Hat ein Punkt die inverse Masse 0.0, wird er vom Algorithmus ignoriert und schwebt unbeweglich in der Luft ein eleganter Trick für Aufhängungen ohne extra Wenn-Dann-Abfragen.",
"DISCLAIMER": "XPBD vs. Masse-Feder-Systeme: In der physikalischen Simulation gibt es grundlegende Architektur-Unterschiede beim Lösen der Gleichungen:",
"DISCLAIMER_1": "Klassische Masse-Feder-Systeme: Hier werden Kräfte (Hookesches Gesetz) berechnet, die zu Beschleunigungen und schließlich zu neuen Positionen führen. Es gibt zwei Wege, diese mathematisch in die Zukunft zu rechnen (Integration):",
"DISCLAIMER_2": "Explizite Löser (z.B. Forward Euler): Sie berechnen den nächsten Schritt stur aus dem aktuellen Zustand. Sie sind leicht zu programmieren, aber bei steifen Stoffen extrem instabil. Die Kräfte schaukeln sich auf und die Simulation 'explodiert', sofern man keine winzigen, sehr leistungsfressenden Zeitschritte wählt.",
"DISCLAIMER_3": "Implizite Löser (z.B. Backward Euler): Sie berechnen den nächsten Schritt basierend auf dem zukünftigen Zustand. Das ist mathematisch enorm stabil, erfordert aber das Lösen riesiger globaler Matrix-Gleichungssysteme in jedem Frame. Dies ist auf der GPU schwerer zu parallelisieren und bricht zusammen, wenn sich die Struktur ändert (z. B. durch Zerschneiden des Stoffs).",
"DISCLAIMER_4": "Der XPBD-Kompromiss: XPBD umgeht dieses komplexe Matrix-Problem völlig, indem es als lokaler Löser arbeitet. Es kombiniert die unbedingte Stabilität eines impliziten Lösers mit der enormen Geschwindigkeit, Parallelisierbarkeit und dynamischen Anpassungsfähigkeit eines expliziten Systems."
}
},
"ALGORITHM": {
"TITLE": "Algorithmen",
@@ -507,9 +526,9 @@
"DESCRIPTION": "Visualisierung einer chaotischen Doppel-Pendel-Simulation mit WebGPU."
},
"CLOTH": {
"TITLE": "Stoff-Simulation",
"TITLE": "Stoffsimulation",
"DESCRIPTION": "Simulation on Stoff mit WebGPU."
}
},
"NOTE": "HINWEIS",
"GRID_HEIGHT": "Höhe",
"GRID_WIDTH": "Beite"

View File

@@ -57,7 +57,8 @@
"K8S": "Kubernetes / k3d",
"POSTGRES": "PostgreSQL",
"MONGO": "MongoDB",
"GRAFANA": "Grafana/Prometheus"
"GRAFANA": "Grafana/Prometheus",
"DOCKER": "Docker"
},
"XP": {
"COMPANY8": {
@@ -473,7 +474,25 @@
"CLOTH": {
"TITLE": "Cloth simulation",
"WIND_ON": "Wind On",
"WIND_OFF": "Wind Off"
"WIND_OFF": "Wind Off",
"OUTLINE_ON": "Show Mesh",
"OUTLINE_OFF": "Hide Mesh",
"EXPLANATION": {
"TITLE": "Real-time Cloth Simulation on the GPU",
"CLOTH_SIMULATION_EXPLANATION_TITLE": "Cloth Simulation",
"XPBD_EXPLANATION_TITLE": "XPBD (Extended Position-Based Dynamics)",
"GPU_PARALLELIZATION_EXPLANATION_TITLE": "GPU Parallelization",
"DATA_STRUCTURES_EXPLANATION_TITLE": "Data Structures",
"CLOTH_SIMULATION_EXPLANATION": "Cloth simulations usually model textiles as a grid of mass points (vertices) held together by invisible connections. The goal is to represent physical influences like gravity, wind, and collisions in real time without the material tearing or stretching unnaturally like rubber.",
"XPBD_EXPLANATION": "XPBD (Extended Position-Based Dynamics) is a modern algorithm that manipulates point positions directly to satisfy distance conditions (constraints) instead of calculating accelerations. The 'Extended' means that true physical stiffness is simulated independently of the framerate. Advantage: Absolutely stable, does not explode, and topological changes (like cutting cloth) are trivial. Disadvantage: It is an iterative approximation method and slightly less physically accurate than complex matrix solvers.",
"GPU_PARALLELIZATION_EXPLANATION": "To calculate tens of thousands of points in parallel on the graphics card, one must prevent 'race conditions' i.e., two processing cores shifting the same node at the exact same time. The solution is called 'Independent Sets' (or Graph Coloring): The connections are divided into isolated groups (e.g., 4 phases for a 2D grid) in which not a single point overlaps. This allows the GPU to process each group blindly and at maximum speed.",
"DATA_STRUCTURES_EXPLANATION": "For maximum GPU performance, data must be memory-aligned (16-byte alignment). Instead of using many individual variables, information is cleverly packed into blocks of four (vec4). A vertex stores, for example, [X, Y, Z, Inverse_Mass]. If a point has an inverse mass of 0.0, the algorithm ignores it, and it floats motionlessly in the air an elegant trick for pinning cloth without extra if/then statements.",
"DISCLAIMER": "XPBD vs. Mass-Spring Systems: In physical simulations, there are fundamental architectural differences when solving equations:",
"DISCLAIMER_1": "Classical Mass-Spring Systems: Here, forces (Hooke's Law) are calculated, leading to accelerations and ultimately new positions. There are two ways to mathematically project these into the future (integration):",
"DISCLAIMER_2": "Explicit Solvers (e.g., Forward Euler): These rigidly calculate the next step solely from the current state. They are easy to program but extremely unstable for stiff cloths. Forces can escalate and the simulation 'explodes' unless tiny, very performance-heavy time steps are chosen.",
"DISCLAIMER_3": "Implicit Solvers (e.g., Backward Euler): These calculate the next step based on the future state. This is mathematically highly stable but requires solving massive global matrix equation systems in every frame. This is harder to parallelize on the GPU and breaks down if the structure changes (e.g., when the cloth is cut).",
"DISCLAIMER_4": "The XPBD Compromise: XPBD completely bypasses this complex matrix problem by acting as a local solver. It combines the absolute stability of an implicit solver with the enormous speed, parallelizability, and dynamic adaptability of an explicit system."
}
},
"ALGORITHM": {
"TITLE": "Algorithms",