High-Precision Flexible Bionic Fish Motion Model: Modeling Principles and OpenGL-C++ Real-Time Implementation

 

Introduction: Featuring low turbulence, low acoustic noise, and high maneuverability, bionic robotic fish underwater robots have gradually replaced traditional propeller-driven vehicles. They have become essential devices for fine-scale ocean exploration, nearshore water quality monitoring, covert underwater inspection, and narrow-water rescue missions. However, most self-developed bionic fish prototypes face a common dilemma: satisfactory offline simulation performance but degraded real-world swimming performance, including straight-path deviation, unstable steering, sharp efficiency degradation at high speeds, and rigid motion postures.

Flexible Bionic Fish Motion Model C++ OpenGL Fluid Structure Coupling Simulation

 

These performance issues stem not from inadequate PID tuning or trivial control defects, but from incomplete physical modeling, decoupling between flexible deformation and hydrodynamics, and insufficient understanding of underlying parameter mechanisms. Most public tutorials on bionic fish modeling adopt MATLAB-based numerical simulation, which prioritizes mathematical fitting while neglecting real-time rendering efficiency, physical iteration performance, and embedded system deployability. This article systematically elaborates a high-precision coupled bionic fish motion model based on a C++ and OpenGL real-time simulation framework. The content covers biological fluid mechanisms, inherent limitations of conventional models, improved flexible kinematics, CFD-calibrated hydrodynamic dynamics, parameter sensitivity analysis, and practical engineering pitfalls. This work establishes a complete logical pipeline from physical modeling and real-time algorithm iteration to graphical rendering verification, targeting robotic developers, real-time simulation engineers, and researchers engaged in bionic prototype optimization.

 

1. Inherent Defects of Traditional Bionic Motion Models (Beyond "Unrealistic Motion")

Many developers attribute poor prototype performance to mechanical precision errors or improper controller tuning. In fact, the core bottleneck lies in theoretical hypothesis deviations embedded in conventional modeling frameworks. The three mainstream modeling approaches all possess inherent limitations that restrict the performance improvement of bionic robotic fish.

1.1 Pure Kinematic Sinusoidal Fitting Model: Geometric Similarity with Physical Distortion

The standard sinusoidal fitting method is the most prevalent entry-level modeling scheme, which adopts simple harmonic functions to approximate fish body swing trajectories. It delivers concise mathematical formulations and low computational overhead for numerical iteration. Nevertheless, its core assumption — uniform swing amplitude across all body segments and complete decoupling between body motion and fluid interaction — fundamentally contradicts the physical nature of underwater swimming. The thrust of biological fish originates from fluid squeezing, flow entrainment, and vortex shedding induced by body wave deformation, rather than pure mechanical oscillation. This model completely ignores viscous drag, fluid added mass force, and unsteady vortex shedding effects. Its errors remain negligible at low swimming speeds but increase drastically at medium and high speeds, leading to severe trajectory drift, velocity mismatch, and invalid energy consumption evaluation. Furthermore, traditional MATLAB-based offline fitting fails to support real-time dynamic rendering and interactive parameter adjustment, making it incompatible with hardware-in-the-loop simulation for physical prototypes.

1.2 Multi-Rigid-Body Dynamic Model: Discrete Structure with Discontinuous Deformation

To compensate for the absence of force analysis in pure kinematic models, most engineering implementations adopt multi-rigid-body segmented modeling, dividing the fish body into discrete rigid components (head, trunk, tail, and caudal fin) and simulating swimming motion through joint rotation. Its fatal limitation is theinability to reproduce the continuous flexible deformation of biological fish. Natural carangiform fish exhibit smooth, gradient body curvature from the trunk to the tail, which delays flow separation and reduces pressure drag. In contrast, discrete rigid joints generate sharp structural inflections, triggering early flow separation, chaotic wake vortices, and substantial drag augmentation. This accounts for the common engineering problem of "large swing amplitude with low thrust and high energy consumption" in rigid-body bionic fish prototypes. In addition, discrete rigid-body solving requires intensive matrix operations, resulting in frame drops and motion stuttering in C++ real-time rendering scenarios.

1.3 Data-Driven Black-Box Model: High Fitting Accuracy but Poor Generalization

In recent years, machine learning and neural network methods have been introduced to bionic fish modeling, achieving high-precision trajectory fitting based on massive experimental datasets. However, such mechanism-free black-box models only fit predefined operating conditions without physical extrapolation capability. Once the swimming frequency, amplitude, water depth, or flow velocity varies, model accuracy declines sharply. Moreover, these models cannot explain the internal correlation between parameter variation and swimming performance, making them incapable of guiding structural optimization and adaptive parameter tuning. Since data-driven methods rely heavily on third-party computing platforms, they are difficult to transplant into lightweight C++ real-time simulation systems, which severely limits their engineering applicability.

To address the above limitations, this paper proposes a mechanism-driven flexible body wave-hydrodynamic coupling model implemented via C++ and OpenGL. The model balances geometric deformation authenticity, fluid physical accuracy, and real-time computational efficiency, fundamentally resolving the simulation-to-reality gap and the offline computing drawbacks of traditional methods.

 

2. Core Biological Fluid Mechanics Mechanism of High-Efficiency Carangiform Swimming

High-fidelity bionic modeling requires in-depth interpretation of biological physical advantages rather than superficial geometric and kinematic imitation. Among three typical fish propulsion modes, carangiform swimming achieves the optimal dynamic balance between deformation loss, fluid resistance, and propulsion thrust, rendering it the most suitable biological prototype for small-and-medium-sized bionic underwater robots and real-time simulation verification.

-Anguilliform mode: Full-body undulation with substantial deformation loss and invalid fluid disturbance, only applicable to low-speed and high-maneuverability scenarios with low propulsion efficiency.

- Thunniform mode: Pure caudal fin propulsion with a rigid trunk structure, featuring low drag but single-dimensional torque output and insufficient steering flexibility, which limits its adaptability to complex flow environments.

- Carangiform mode: Characterized byforebody flow stabilization, rear-body flexible undulation, and caudal fin vortex capture, this mode represents the optimal propulsion configuration formed by natural evolution and matches well with OpenGL mesh-based real-time deformation rendering.

The classic body wave characteristics — progressively increasing amplitude, phase lag propagation, and constant oscillation period — conform to rigorous fluid mechanics principles. The nearly stationary head forms a stable flow rectification region and reduces incoming pressure drag. Gradually amplified undulation from the trunk to the tail squeezes ambient fluid to form directional jet flow. Cooperated caudal fin oscillation locks the wake vortex structure and generates continuous positive thrust via the Karman vortex street shedding effect, which serves as the core physical principle of high-efficiency bionic propulsion neglected by most shallow modeling schemes.

Furthermore, continuous flexible deformation maximizes surface fluid adhesion, delays boundary layer separation, and significantly reduces viscous drag and vortex energy loss. These inherent advantages of biological flexible structures, which cannot be replicated by rigid segmented models, are accurately restored through C++ frame-level iterative computation and OpenGL dynamic mesh updating.

 

3. Improved Flexible Kinematic Model: Eliminating Geometric Distortion in Traditional Body Wave Modeling

As the fundamental trajectory module of the entire bionic system, the kinematic model aims to accurately reproduce the spatiotemporal distribution of biological body waves. It provides high-precision vertex motion parameters for OpenGL mesh rendering and real-time iterative boundary conditions for C++ physical computation, thereby reducing simulation errors from the source.

3.1 Attitude Solving Based on Dual Coordinate System Coupling

Different from conventional single-coordinate offline modeling, this work adopts coupled global-inertial and body-fixed coordinate systems to eliminate coupling interference between local body oscillation and global displacement. The global inertial coordinate system describes the absolute swimming trajectory and heading angle, while the body-fixed coordinate system characterizes local structural deformation and swing angles. Based on C++ real-time matrix operation logic, frame-by-frame coordinate transformation and attitude decoupling are implemented to thoroughly separate local attitude disturbances from global motion displacement. This mechanism eliminates heading and velocity solving errors induced by tiny body wave oscillations and matches the OpenGL rendering pipeline to realize high-precision real-time trajectory visualization.

3.2 Gradient Amplitude Body Wave Equation: Restoring Biological Deformation Field

The uniform amplitude assumption of traditional standard sinusoidal equations fails to simulate the typical "small head swing and amplified tail swing" gradient deformation feature of carangiform fish. This paper introduces a position-coupled amplitude growth function to construct a spatiotemporally correlated two-dimensional body wave model that precisely depicts the continuous deformation field of the fish body. The lightweight mathematical formulation is fully compatible with high-frequency C++ iterative computation and OpenGL dynamic vertex updating:

$$h(x,t)=A(x)\sin\left(\frac{2\pi}{\lambda}x-\omega t+\varphi\right)$$

$$A(x)=A_0\left(\frac{x}{L}\right)^k$$

Compared with traditional models, the core innovation lies in the spatial coupling between oscillation amplitude and body position, rather than globally uniform amplitude distribution. The growth coefficient k acts as a core correction parameter adaptable to bionic fish with different body lengths and flexible materials. Specifically, k approaches 1.0 for highly flexible structures and ranges from 1.1 to 1.2 for relatively rigid bodies, ensuring broad prototype compatibility and convenient parameter configuration via C++ global variables.

Physical interpretation of key parameters: A₀ defines the maximum tail oscillation amplitude to guarantee sufficient propulsion thrust; body length L constrains the effective wave propagation range to avoid invalid deformation energy loss; angular frequency ω and wavelength λ jointly determine body wave propagation velocity and overall swimming speed. All parameters are encapsulated in C++ class functions to support real-time dynamic adjustment and synchronous OpenGL rendering linkage.

Maneuver-oriented optimization is implemented for complex motion scenarios. During straight navigation, bilateral body waves maintain symmetric phase and amplitude to counteract lateral forces and ensure heading stability. A phase-asymmetric disturbance coefficient is introduced during steering motion to precisely adjust bilateral thrust differences and generate stable steering torque, eliminating the steering stuttering, attitude jitter, and heading deviation observed in traditional models. The asymmetric phase iteration algorithm is optimized for C++ frame circulation to guarantee smooth steering animation without frame rate degradation.

3.3 Caudal Fin Phase Coupling Mechanism: Realizing Optimal Propulsion Efficiency

The caudal fin is not an independent motion component but an end energy extension carrier of trunk body wave propagation. The phase matching degree between trunk undulation and caudal fin oscillation directly determines wake vortex stability and overall propulsion efficiency. Sufficient simulation results verify that phase mismatch or uncoupled motion leads to disordered wake vortices and severe thrust attenuation.

This paper establishes a cooperative swing equation to realize strong kinematic coupling between trunk body waves and caudal fin motion, which is synchronously iterated and rendered within the C++-OpenGL framework:

$$\theta(t)=\theta_0\sin(\omega t+\varphi_0)$$

Core conclusion: A phase difference ranging from $$\pi/4$$ to $$\pi/3$$ enables the caudal fin to efficiently capture and propagate trunk wave energy, forming stable directional vortex shedding and maximizing fluid momentum utilization. Excessively large or small phase deviations induce vortex structural distortion and reverse flow disturbance, drastically reducing propulsion efficiency. This conclusion provides a rigorous physical basis for gait parameter optimization, and the optimal phase parameters can be solidified into C++ algorithm logic to support autonomous high-efficiency gait execution.

 

4. Fluid-Structure Coupled Dynamic Model: From Geometric Simulation to Physical Authenticity

Pure kinematic models only describe geometric motion trajectories without reflecting the force-motion coupling mechanism of underwater locomotion. Bionic fish swimming is a typical nonlinear fluid-structure interaction (FSI) problem: flexible structural deformation disturbs the ambient flow field, and hydrodynamic loads conversely constrain structural motion. Different from offline MATLAB numerical simulation, this study lightweights the Lagrangian dynamic formulation and CFD-calibrated hydrodynamic correction algorithm, realizing synchronous simulation of C++ real-time physical iteration and OpenGL visual rendering with balanced physical accuracy and real-time performance.

4.1 Core Advantages and Basic Logic of Lagrangian Modeling in C++ Implementation

Compared with classical Newtonian mechanics, the Lagrangian energy method avoids solving complex internal joint forces and structural stress distributions, making it highly suitable for dynamic solving of continuous flexible structures. All energy balance calculations are optimized via lightweight C++ matrix operations, removing redundant iterative computations inherent in commercial simulation software. System dynamic responses are accurately solved based on energy balance among kinetic energy, potential energy, and external hydrodynamic loads, effectively reducing computational complexity and ensuring that physical calculation frequency matches the 60 FPS rendering rate of OpenGL.

4.2 Refined Decomposition of Nonlinear Hydrodynamics (Core Technical Depth)

Traditional dynamic models adopt oversimplified thrust and drag calculations while ignoring hydrodynamic nonlinearity under variable dynamic conditions. This paper refines three core hydrodynamic load components, discretizes the physical formulations, and optimizes computational logic for C++ real-time iteration, compensating for high-speed modeling defects of conventional methods:

(1) Dynamic propulsion thrust: Thrust is not a constant value but varies nonlinearly with oscillation frequency, amplitude, and relative flow velocity. It originates from pressure differentials induced by body wave fluid squeezing and momentum exchange from wake vortex shedding. The discretized thrust formula is embedded into the C++ frame loop for real-time thrust updating. Higher frequency and larger amplitude generate higher instantaneous thrust peaks but are accompanied by drastic drag augmentation, forming a distinct optimal working interval.

(2) Coupled viscous and pressure drag: Low-speed swimming is dominated by viscous friction drag, while high-speed locomotion is mainly governed by pressure drag and vortex-induced drag. C++ conditional judgment logic is adopted to realize dynamic switching of dominant drag components, achieving full-speed-range accurate drag calculation and eliminating the precision imbalance of traditional single-term drag models.

(3) Fluid added inertial force: This is the most critical missing parameter in conventional modeling. Accelerated flexible oscillation of the bionic fish drives surrounding attached fluid to generate additional inertial loads, which are negligible at low speeds but account for 15% to 20% of total hydrodynamic loads under medium and high-speed conditions. Real-time quantitative calculation of this term is integrated into the C++ dynamic iteration loop to eliminate high-speed dynamic response distortion.

4.3 Global Dynamic Equations and Physical Interpretation

By integrating energy balance equations and nonlinear hydrodynamic load terms, high-precision planar dynamic equations covering translational and rotational responses are derived and discretized for C++ real-time iterative solving:

$$(m+m_a)\ddot{x}=F_T-F_D-F_f$$

$$I\ddot{\theta}=M_T-M_D$$

In-depth physical interpretation: The fluid added mass$$m_a$$ corrects inertial solving errors by distinguishing structural inherent mass and additional fluid inertial loads. Separate computation of dynamic thrust, viscous drag, and frictional drag ensures accurate adaptation to variable velocity conditions. The torque balance equation characterizes the dynamic game between steering thrust torque and fluid damping torque, perfectly reproducing the full dynamic procedure of acceleration, deceleration, stable steering, and attitude convergence. All physical quantities are synchronously updated with OpenGL mesh vertex coordinates to achieve integrated physical computation and visual rendering.

 

5. Simulation Framework and Multi-Condition Verification (C++ + OpenGL)

Different from traditional offline MATLAB numerical simulation, this work constructs a full-process real-time simulation framework based on C++ underlying algorithm iteration and OpenGL 3D dynamic rendering. A 0.8-meter bionic fish prototype is discretized into uniform mesh vertices, and multi-condition performance tests and parameter sensitivity analysis are completed via frame-by-frame real-time physical iteration.

5.1 Trajectory Accuracy Comparison and Mechanism Analysis

- Traditional sinusoidal model (offline simulation): Uniform-amplitude oscillation without gradient deformation, incapable of suppressing head flow disturbance, with a trajectory error of 8.6% and severe high-speed drift, and lacking real-time visual verification capability.

- Proposed C++-OpenGL flexible coupling model: Gradient deformation realizes forebody flow stabilization and tail propulsion enhancement, achieving biologically consistent motion attitudes with a stable trajectory error of only 3.2% across all velocity conditions. Dynamic mesh rendering intuitively restores the real flexible deformation procedure of biological fish bodies.

Under steering conditions, asymmetric phase torque adjustment enables 0~360° smooth steering with a minimum turning radius of 0.45 meters and zero attitude jitter or heading offset. The core mechanism lies in the real-time fluid damping torque compensation implemented by C++ iterative torque solving, which achieves dynamic torque balance and high-smoothness OpenGL steering animation.

5.2 Optimal Parameter Intervals and Physical Mechanism

Single-variable real-time traversal tests based on the C++ framework reveal the physical essence of optimal parameters for engineering guidance:

(1) Oscillation frequency: 1.0~1.5 Hz (optimal). In the low-frequency range, propulsion thrust increases linearly with frequency with minor fluid disturbance and high motion stability. When the frequency exceeds 1.5 Hz, body wave propagation velocity surpasses fluid boundary layer attachment speed, triggering massive boundary layer separation, chaotic wake vortices, and nonlinear drag surge, which leads to sharp propulsion efficiency degradation.

(2) Tail amplitude: 15% of body length (optimal). Insufficient amplitude results in inadequate fluid squeezing and thrust deficiency. Excessively large amplitude exceeds the effective fluid attachment boundary, generating invalid wake eddies, increasing deformation energy loss and drag, and reducing overall energy efficiency.

(3) Phase matching: π/4 (optimal). This optimal phase realizes lag-free and loss-free energy transfer between trunk undulation and wake vortex evolution with the most stable vortex structure and highest momentum exchange efficiency, improving the overall propulsion efficiency by 18.7% compared with uncoupled disordered motion.

5.3 Core Advantages of C++-OpenGL Real-Time Modeling Framework

1. Dual fidelity of geometry and physics: Reproduces biological flexible deformation characteristics via OpenGL dynamic mesh rendering, and couples real nonlinear hydrodynamic loads through C++ real-time iteration, fundamentally solving the simulation-to-reality deviation of offline simulation schemes.

2. Full-condition real-time adaptability: Equipped with added mass force and variable drag coefficient correction to maintain high precision across high/low speed, straight-navigation, and steering scenarios, supporting real-time parameter adjustment and dynamic response observation.

3. Lightweight and highly deployable: Eliminates dependence on bulky commercial simulation software, relying entirely on underlying C++ algorithms and OpenGL rendering. The framework features low computational overhead, supports embedded system transplantation and hardware-in-the-loop simulation, and exhibits superior engineering practicability compared with traditional MATLAB simulation.

 

6. Engineering Pitfalls and Advanced Optimization Directions

6.1 Common Developer Pitfalls in C++-OpenGL Modeling

Two widespread misunderstandings in engineering development are summarized based on underlying framework development experience. First, larger swing amplitude and higher oscillation frequency do not equate to faster swimming speed; excessive oscillation induces flow instability and efficiency collapse, which cannot be detected by pure mathematical fitting and require real-time flow field rendering verification. Second, offline mathematical fitting results cannot be directly transplanted into C++ frameworks; unoptimized loop iteration and vertex updating logic cause frame rate drops and motion stuttering, leading to inconsistency between simulation visualization and physical model characteristics.

6.2 Advanced Model Optimization Directions

1. Complex-environment FSI upgrading: Introduce ambient flow velocity, turbulence intensity, and near-wall interference parameters, embed disturbance adaptive logic into the C++ iteration loop, and realize real-time simulation of bionic fish motion in complex ocean and river flow environments.

2. Intelligent adaptive parameter optimization: Integrate reinforcement learning algorithms with the C++ underlying framework, take propulsion efficiency and motion stability as reward functions, and realize real-time adaptive adjustment of oscillation frequency, amplitude, and phase for variable operating conditions.

3. Digital twin interactive optimization: Construct a closed-loop system integrating C++ physical computation, OpenGL visual rendering, and physical prototype data feedback. Hydrodynamic coefficients and deformation parameters are corrected via sensor data to achieve full synchronization between virtual simulation and physical motion, supporting high-precision motion control algorithm development.

 

7. Conclusion

High-precision bionic fish motion modeling relies on the deep integration of biological kinematic mechanisms, fluid dynamics principles, and underlying programming rendering technology, rather than simple formula stacking and offline numerical fitting. Starting from the inherent limitations of traditional modeling methods, this paper analyzes the fluid mechanics essence of high-efficiency carangiform swimming, reconstructs biological deformation fields via an improved flexible body wave kinematic model, and restores authentic underwater force characteristics through a fluid-structure coupled dynamic model. Based on the lightweight C++ algorithm framework and OpenGL real-time 3D rendering technology, comprehensive multi-condition simulation verification and parameter mechanism analysis are completed.

 

The proposed model eliminates the simulation distortion of shallow offline modeling and avoids the high computational cost and poor deployability of professional numerical simulation software. It can be directly applied to bionic fish structural design, real-time gait parameter optimization, underlying motion control algorithm development, and 3D simulation platform construction, providing a complete low-level modeling and real-time verification scheme for high-precision underwater bionic robot research and engineering implementation.