Full text
Universidade do Minho Escola de Engenharia Departamento de Informática Carlos Peixoto Antunes de Castro Shallow Waters Simulation June 2022
Universidade do Minho Escola de Engenharia Departamento de Informática Carlos Peixoto Antunes de Castro Shallow Waters Simulation Master dissertation Integrated Master’s in Informatics Engineering Dissertation supervised by António José Borba Ramires Fernandes June 2022
COPYRIGHT AND TERMS OF USE FOR THIRD PARTY WORK This dissertation reports on academic work that can be used by third parties as long as the internationally accepted standards and good practices are respected concerning copyright and related rights. This work can thereafter be used under the terms established in the license below. Readers needing authorization conditions not provided for in the indicated licensing should contact the author through the RepositóriUM of the University of Minho. LICENSE GRANTED TO USERS OF THIS WORK: CC BY https://creativecommons.org/licenses/by/4.0/
ACKNOWLEDGEMENTS I would like to express my deepest gratitude to my supervisor António Ramires Fernandes for his continuous help and guidance throughout this work. I would also like to thank my parents for their support and encouragement during the whole process. Lastly, I extend these words of gratitude to my friends, with whom I shared the many successes and struggles. i
STATEMENT OF INTEGRITY I hereby declare having conducted this academic work with integrity. I confirm that I have not used plagiarism or any form of undue use of information or falsification of results along the process leading to its elaboration. I further declare that I have fully acknowledged the Code of Ethical Conduct of the University of Minho. ii
ABSTRACT Realistic simulation and rendering of water in real-time is a challenge within the field of computer graphics, as it is very computationally demanding. A common simulation approach is to reduce the problem from 3D to 2D by treating the water surface as a 2D heightfield. When simulating 2D fluids, the Shallow Water Equations (SWE) are often employed, which work under the assumption that the water’s horizontal scale is much greater than it’s vertical scale. There are several methods that have been developed or adapted to model the SWE, each with its own advantages and disadvantages. A common solution is to use grid-based methods where there is the classic approach of solving the equations in a grid, but also the Lattice-Boltzmann Method (LBM) which originated from the field of statistical physics. Particle based methods have also been used for modeling the SWE, namely as a variation of the popular Smoothed-Particle Hydrodynamics (SPH) method. This thesis presents an implementation for real-time simulation and rendering of a heightfield surface water volume. The water’s behavior is modeled by a grid-based SWE scheme with an efficient single kernel compute shader implementation. When it comes to visualizing the water volume created by the simulation, there are a variety of effects that can contribute to its realism and provide visual cues for its motion. In particular, When considering shallow water, there are certain features that can be highlighted, such as the refraction of the ground below and corresponding light attenuation, and the caustics patterns projected on it. Using the state produced by the simulation, a water surface mesh is rendered, where set of visual effects are explored. First, the water’s color is defined as a combination of reflected and transmitted light, while using a Cook- Torrance Bidirectional Reflectance Distribution Function (BRDF) to describe the Sun’s reflection. These results are then enhanced by data from a separate pass which provides caustics patterns and improved attenuation computations. Lastly, small-scale details are added to the surface by applying a normal map generated using noise. As part of the work, a thorough evaluation of the developed application is performed, providing a showcase of the results, insight into some of the parameters and options, and performance benchmarks. K E Y W O R D S Shallow Water Equations, Fluid Simulation, Caustics, Real time, Heightfield iii
RESUMO Simulação e renderização realista de água em tempo real é um desafio dentro do campo de computação gráfica, visto que é muito computacionalmente exigente. Uma abordagem comum de simulação é de reduzir o problema de 3D para 2D ao tratar a superfície da água como um campo de alturas 2D. Ao simular fluidos em 2D, é frequente usar as equações de águas rasas, que funcionam sobre o pressuposto de que a escala horizontal da água é muito maior que a sua escala vertical. Há vários métodos que foram desenvolvidos ou adaptados para modelar as equações de águas rasas, cada uma com as suas vantagens e desvantagens. Uma solução comum é utilizar métodos baseados em grelhas onde existe a abordagem clássica de resolver as equações numa grelha, mas também existe o método de Lattice Boltzmann que originou do campo de física estatística. Métodos baseados em partículas também já foram usados para modelar as equações de águas rasas, nomeadamente como uma variação do popular método de SPH. Esta tese apresenta uma implementação para simulação e renderização em tempo real de um volume de água com uma superfície de campo de alturas. O comportamento da água é modelado por um esquema de equações de águas rasas baseado na grelha com uma implementação eficiente de um único kernel de compute shader. No que toca a visualizar o volume de água criado pela simulação, existe uma variedade de efeitos que podem contribuir para o seu realismo e fornecer dicas visuais sobre o seu movimento. Ao considerar águas rasas, existem certas características que podem ser destacadas, como a refração do terreno por baixo e correspondente atenuação da luz, e padrões de cáusticas projetados nele. Usando o estado produzido pela simulação, uma malha da superfície da água é renderizada, onde um conjunto de efeitos visuais são explorados. Em primeiro lugar, a cor da água é definida como uma combinação de luz refletida e transmitida, sendo que uma BRDF de Cook-Torrance é usada para descrever a reflexão do Sol. Estes resultados são depois complementados com dados gerados num passo separado que fornece padrões de cáusticas e melhora as computações de atenuação. Por fim, detalhes de pequena escala são adicionados à superfície ao aplicar um mapa de normais gerado com ruído. Como parte do trabalho desenvolvido, é feita uma avaliação detalhada da aplicação desenvolvida, onde é apresentada uma demonstração dos resultados, comentários sobre alguns dos parâmetros e opções, e referências de desempenho. PA L AV R A S -C H AV E Equações de Águas Pouco Profundas, Simulação de Fluídos, Cáusticas, Tempo Real, Campo de Alturas iv
CONTENTS I INTRODUCTORY MATERIAL 1INTRODUCTION 1 1.1 Context 1 1.2 Objectives 2 1.3 Document structure 2 2S TAT E O F T H E A R T 4 2.1 The Navier-Stokes equations 4 2.1.1 The Momentum Equation 5 2.1.2 The Incompressibility Condition 5 2.2 Shallow water equations 5 2.2.1 Heightfield approximations 5 2.2.2 The shallow water equations 7 2.2.3 Other heightfield methods 8 2.3 Numerical simulation 9 2.3.1 Lagrangian and Eulerian Viewpoints 10 2.3.2 Discretizing in time 11 2.3.3 Boundary Conditions 13 2.4 Fluid solvers 14 2.4.1 Eulerian Solvers 14 2.4.2 Lattice-Boltzmann Method 15 2.4.3 Smoothed-Particle Hydrodynamics 16 2.4.4 Summary 17 2.5 Rendering 19 2.5.1 Water Surface Color 19 2.5.2 Caustics 22 2.5.3 Small-scale details 24 II CORE OF THE DISSERTATION 3SIMULATION 27 3.1 Numerical method 27 v
CONTENTS vi 3.1.1 Picard integral formulation for SWE 28 3.1.2 WENO reconstruction 28 3.1.3 Well-balanced treatment of the source term 29 3.1.4 Handling of the wetting/drying processes 30 3.2 Implementation 31 3.2.1 Timestepping 31 3.2.2 Data storage 32 3.2.3 Threading scheme 32 3.2.4 Boundary conditions 35 3.2.5 Algorithm loop 38 3.2.6 Algorithm step 38 3.2.7 Results 40 4RENDERING 42 4.1 Rendering Geometry 42 4.2 Water Surface Color 44 4.2.1 Sun reflection 44 4.2.2 Intersecting the heightfield 45 4.2.3 Environment reflection 50 4.2.4 Transmission 51 4.2.5 Overview 54 4.2.6 Results 55 4.3 Caustics 56 4.3.1 Simulation 57 4.3.2 Rendering caustics map 63 4.3.3 Applying the caustics map 64 4.3.4 Algorithm overview 65 4.3.5 Results 65 4.4 Small Scale Details 67 4.4.1 Perlin Noise 67 4.4.2 Cellular Noise 68 4.4.3 Fractal Brownian Motion 68 4.4.4 Domain Warping 69 4.4.5 Using the normal map 70 5E VA L UAT I O N 74 5.1 Overview 74 5.2 Shallow Water Equations solver 78
LIST OF TABLES Table 1 Frame time breakdown of the full application for different combinations of grid sizes and resolutions. Each cell of the table has 3 timings which from left to right correspond to: simulation, rendering and total. Timings are in milliseconds. 76 Table 2 Data about scenes with grid size 1024x1024 , resolution 1920x1080 and varying cell size. 80 Table 3 Data about the scenes depicted in Figure 55, with grid size 1024x1024 , resolution 1920x1080 and cell size 0.2x0.2.81 Table 4 Performance of the SWE solver with different work group thread configurations. Simulation grid size is 512x512.82 Table 5 Performance of the SWE solver with different grid sizes and solvers, timings in milliseconds. The wet only solver has no computations for handling wetting/drying processes. 83 Table 6 Rendering timings for different bathymetries of varied steepness (shown in Figure 58). Only the water surface and sides passes are considered. Grid size is 512x512 and resolution is 960x540.83 Table 7 Performance of the various caustics simulation passes with different caustics grid sizes. Caustics textures resolution is 1024x1024 and timings are in milliseconds. The total accounts for a complete step, which includes the compute pass and two render passes. 85 Table 8 Performance of a caustics rendering pass with different resolutions. The grid size refers to the caustics grid and the resolution to the generated caustics textures. 85 Table 9 Performance of the caustics simulation pass with different work group thread configurations. Caustics grid size is 1024x1024.86 Table 10 Performance of the details normal map generation with different resolutions and noise types (one octave), timings in milliseconds. 88 Table 11 Performance of the details normal map generation with different noise types and octaves ( 512x512 resolution). The cellular noise includes warping and an additional pass to compute the normals. Timings in milliseconds. 89 xiii
LIST OF ALGORITHMS 1 Offsetsinitialization ...................................... 37 2 Determining the exit point of a heightfield texel . . . . . . . . . . . . . . . . . . . . . . . . . 47 3 Increasing the mipmap level if necessary . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 4 Maximum mimpmap heightfield intersection . . . . . . . . . . . . . . . . . . . . . . . . . . 50 5 Watersurfaceshading..................................... 54 6 Intersectionestimation..................................... 59 7 Causticssimulation ...................................... 63 8 fBmfunction.......................................... 69 9 Noise function using fractal sums and domain warping . . . . . . . . . . . . . . . . . . . . . 70 xiv
ACRONYMS BRDF Bidirectional Reflectance Distribution Function. iii,iv,viii,19,20,44,51,52,93 CFD computation fluid dynamics. 15,16,17 CFL Courant-Friedrichs-Lewy. 12 ENO Essentially Non-Oscillatory. 107 fBm fractal Brownian motion. 68 FDM finite difference method. 14 FFT Fast Fourier Transform. 24 FVM finite volume method. 14 GSM Group Shared Memory. 31,32,38,39,60,61,62,63 LBM Lattice-Boltzmann Method. iii,15,16,17,94 NDF Normal Distribution Function. 20 NSE Navier-Stokes Equations. 1,2,4,5,7,15 PIF Picard integral formulation. 27,28 SPH Smoothed-Particle Hydrodynamics. iii,iv,16,17,27,94 SWE Shallow Water Equations. iii,viii,xii,xiii,1,2,7,8,9,13,14,15,16,17,27,28,30,78,82,83,86,93, 106 WENO Weighted Essentially Non-Oscillatory. ix,27,28,30,33,37,39,107,108,109 xv
Part I INTRODUCTORY MATERIAL
1 INTRODUCTION Simulating water behavior in real-time can be very expensive, and thus, a 2D heightfield approximation is often used. This approximation can be achieved by ignoring certain components of the simulation under the assumption that the water is shallow. This chapter provides some context into this field of study (Section 1.1), as well as the goal of this thesis within it (Section 1.2). The final section provides a brief description of the chapters that compose this document (Section 1.3). 1.1 CONTEXT Water is common element in nature, and as such, is often encountered in virtual environments. Recently, physically based effects have become more and more popular in these environments, which includes both the simulation and rendering of water. The simulation of the water’s behavior is often achieved by numerically solving the Navier-Stokes Equations (NSE) in offline applications, such as for movie special effects. In contrast, interactive systems require the simulation to be performed in real-time while achieving a frame rate of at least 60 Hz. Additionally, most applications require most of the computing budget to be used for other core features, leaving only a few milliseconds for physical simulation. Simply reducing the resolution of the methods used in offline simulations often yields blobby results and removes all the interesting details. Alternatively, many approaches have been developed in order to efficiently approximate the results obtained by those more complex methods. A common simulation approach is to reduce the problem from 3D to 2D by treating the water surface as a 2D heightfield. Some simple and quite popular methods to simulate water surfaces are based on the wave equation or the pipe model (e.g., Dagenais et al. (2018), Kellomäki (2017)). However, these methods have the drawback of not being able to correctly simulate effects that are based on horizontal motion, such as whirlpools or the flow of a river. This effects can, however, be captured by the SWE, with this approach being used in both interactive graphics (e.g. Chentanez and Mueller (2010), Parna (2020)), as well as in engineering applications (e.g., Horváth et al. (2020)). The rendering of the water surface can be divided into various parts. An essential component is the reflection of the environment, including the distinct specular glitter caused by the Sun. Considering the case of shallow water, another big component is the refraction of the bottom terrain and the caustics caused in it by the water surface (e.g., Yang and Ouyang (2021)). There are also a variety of effects that focus on addressing limitations of 1
1.2. Objectives 2 the heightfield representation, such as adding breaking waves, splashing particles, or small-scale perturbations below the simulation scale (e.g., Ojeda and Susín (2014), Fujisawa et al. (2017)). 1.2 OBJECTIVES The aim of this dissertation is to develop an application for simulating water behavior by solving the SWE, and rendering the grid it outputs as a water volume. Furthermore, the application must allow both the simulation and rendering to run in real-time on current graphics hardware. To limit the scope of this work, rendering will be limited to the water surface’s color (which includes reflections, refractions and shading), caustics, and small-scale details. This can be split into the following sub-objectives: • Study and understand the background on this field of study. • Survey the state-of-the-art for both simulation and rendering techniques. • Implement a solver for the SWE. • Implement a visualization algorithm for the simulation. • Evaluate the results and performance of the full application. 1.3 DOCUMENT STRUCTURE This dissertation is split into various chapters that roughly match the previously presented objectives, and is organized as follows: chapter 2 provides the needed background for the dissertation, starting from the NSE and introducing some simplifying assumptions used to achieve a form more feasible for real-time simulation, the SWE. This is followed by an overview of the current state-of-the-art, and a review of the more relevant fluid simulation methods. Then, a review of the state-of-art of rendering methods suitable for the simulation is presented, focusing on the previously mentioned set of effects. chapter 3 presents the implemented simulation of the water’s behavior. The chapter starts with a description of the numerical scheme, followed by the details of the GPU implementation. The next chapter (chapter 4) explores the rendering effects used to visualize the grid output by the water simulation, providing the implementation details. Both chapters end with a brief showcase of its results. A thorough review of the results is presented in the following chapter (chapter 5). Here the SWE solver implementation is analyzed, reviewing different options, and presenting performance benchmarks. Then, a similar discussion is done for the rendering, going through each of the components individually. The chapter ends with a a showcase of varied example scenes, accompanied by a performance breakdown of the full application. The final chapter (chapter 6) briefly discusses the main conclusions from the developed work and provides possible avenues of future work .
1.3. Document structure 3 In addition to the work presented here, the full source code of the developed application is provided online at https://github.com/carlosc20/shallow-waters-nau.
2 S TAT E O F T H E A R T This chapter provides an overview of the state-of-the-art in real-time simulation of shallow water. It starts by providing some background into the common ground of all fluid simulations, the NSE (Section 2.1). Then, it approaches the need of simplified solutions for real-time applications, focusing on the approximation provided by the shallow water equations (Section 2.2). This is followed by an overview of the main concepts of numerical fluid simulations (Section 2.3). Subsequently, the current methods used for developing shallow water solvers are presented and compared (Section 2.4). Finally, rendering methods used for realistic water visualization are reviewed, focusing on those adequate for a shallow water heightfield input (Section 2.5). 2.1 THE NAVIER-STOKES EQUATIONS The NSE, a reformulation of Newton’s Second Law, are often used to describe fluid flow. For incompressible and Newtonian fluids they consist in a set of partial differential equations, the momentum equation (Equation 1) and the incompressibility condition (Equation 2), as depicted in Bridson (2015) where a more in depth analysis can be found. ∂u ∂t+u·∇u+1 ρ∇p=a+ν∇·∇u(1) ∇·u=0(2) In Equations 1and 2,uis the fluid velocity vector, pis the fluid pressure, ρis the fluid density and ∇·∇ is the Laplacian operator. νis the kinematic viscosity and is equal to η/ρwhere ηis the dynamic viscosity coefficient. Acceleration due to external forces is commonly represented by gwhen only gravity is considered. However, in interactive applications other forces often need to be considered, such as those created by user input. Considering that, a more generic aterm is used to represent the acceleration due to all external body forces. 4
2.2. Shallow water equations 5 2.1.1 The Momentum Equation The momentum equation (Equation 1) describes how the fluid velocity uevolves over time. Most of the components of the momentum equation represent different accelerations caused by forces affecting the water particles: external forces a(commonly gravity, wind or user interaction), pressure gradient −1 ρ∇p, and viscosity ν∇·∇u. Since water has low viscosity, which has a minor impact in the animation of large bodies of water, the term is typically dropped. This is further supported by the fact that numerical methods used to solve the NSE often introduce errors that can be physically reinterpreted as artificial viscosity (Bridson,2015). The process of a physical quantity moving with the velocity field of the fluid is called advection. This also affects the velocity itself, in what can be called self-advection, and is modeled by the convective acceleration term u·∇u. Advection can also be represented using the material derivative operator, this notation is exemplified in Equation 3. ∂x ∂t+u·∇x≡Dx Dt (3) 2.1.2 The Incompressibility Condition The incompressibility condition (Equation 2), sometimes also called the continuity equation, ensures the conservation of mass, that is, the incompressibility of the fluid. In reality, fluids are not actually incompressible, but they are close enough to be considered as such in computer graphics. The equation states that density along the line of flow remains constant over time, therefore divergence of velocity is null all the time, i.e., water is flowing out as fast as it is flowing in from other directions. 2.2 SHALLOW WATER EQUATIO N S This section will explore a special case of water simulation that allows much faster and simpler algorithms, by making certain assumptions, namely that the water surface can be represented as an heightfield and that the horizontal scale of the simulation is much larger than the vertical scale. 2.2.1 Heightfield approximations Simulation models based on the NSE are highly realistic, since they capture the three-dimensional dynamics of fluids. The downside of such models is that, for full-scale water simulations, full 3D simulations are often too slow to achieve real-time rates.
2.2. Shallow water equations 6 A common solution is to assume the water surface can be represented as a heightfield, in other words, the surface z-coordinate is a function η(x,y), bounded from below by the bottom topography and from above by another fluid of negligible density (commonly air). This allows the simulation to take place in a 2D grid, which means that if ncells are required per dimension, the time complexity is typically lowered from O(n3)to O(n2). Another advantage is that the rendering of the simulation results can be done using common, fast rendering techniques, similar to those used for e.g. terrain rendering. Full 3D simulations usually require surface tracking (e.g. level sets (Bridson,2015)) and expensive volume rendering techniques (e.g. ray marching (Crane et al., 2007)) or mesh generating algorithms (e.g. marching cubes (Thürey,2007)). A regular 2D grid can be imagined as a group of adjacent water columns, where the water is defined by a nxm 2D array of depth values. A nxm heightfield is often visualized by creating (n−1)x(m−1)squares that are rendered as two triangles each (Figure 1). Figure 1: A 3x3 heightfield with one of the nine simulation cells drawn. The value η of each cell represents the vertical displacement in its center. The cells’ centers are connected to form triangles for visualization. This approach results in a clear limitation, behavior that breaks the water surface can not be represented, such as breaking waves, waterfalls and splashes. However, some of these effects only occur in limited areas in the simulation and can be added using, e.g., a local small-scale particle simulation, while the main body of water is simulated using 2D methods (Chentanez and Mueller,2010). In many virtual environments it is common that the terrain is also represented as a heightfield. In this cases it is therefore interesting to simulate the interaction of the water with the terrain below. Assuming that the water flows on top of an arbitrary heightfield terrain b(x,y), and can freely spread to dry areas, it can be represented by the depth h(x,y)≥0, with surface height η=b+h(as shown in Figure 2). Most simulations for this setup use the depth instead of the surface height as the main simulation variable.
2.3. Numerical simulation 13 2.3.3 Boundary Conditions SWE need boundary conditions where the water ends (in the x–y horizontal plane) or the simulation domain ends. As in heightfield simulations the free surface is automatically handled, only solid walls or open boundaries need to be addressed. A solid wall (or reflective) boundary is where the fluid is in contact with a solid (Figure 6, top row). The fluid should not be flowing into or out of the solid, therefore the normal component of velocity should be zero, as defined by Equation 13a, where ˆ nis the normal to the solid boundary. In case the solid is moving, the normal component of the fluid velocity needs to match the normal component of the solid’s velocity, as in Equation 13b. This kind of condition is also referred to as "no-stick" condition, since it only restricts the normal component of velocity, allowing the fluid to freely slip past in the tangential direction (Bridson,2015). u·ˆn=0(13a) u·ˆn=usolid ·ˆn(13b) This is correct only for a inviscid fluid. For fluids that do have viscosity, the stickiness of the solid generally influences the tangential component of the fluid’s velocity, forcing it to match. This is called the "no-slip" boundary condition and can be defined by Equation 14a, or if the solid is moving Equation 14b. For fluids with very low but nonzero viscosity this is more accurate than the "no-stick" condition only in microscopic detail, so a "no-stick" condition is often used instead (Bridson,2015). u=0(14a) u=usolid (14b) It is much more difficult dealing with the edge of the simulation domain if it is assumed that the water continues on past the edge. If waves should be entering along one edge, perhaps from a simple sinusoid model, the normal velocity and height can be further specified. However, if the waves are expected to leave through the edge, giving the effect of an open water surface, things are much trickier. This is called a absorbing (or nonreflecting) boundary condition (Figure 6, bottom row), and is a long known problem that continues as a subject of research in numerical methods Düz et al. (2017). The usual approach taken is to gradually blend away the simulated velocities and heights with a background field (such as a basic sinusoid wave, or flat water at rest), over the course of many grid cells (or particles): if the blend is smooth and gradual enough, reflections should be minimal. A commonly used method to achieve this, is the perfectly matched layer introduced by Berenger (1994), a method originally used for the absorption of electromagnetic waves and adapted for use in fluid simulation (e.g. Söderström and Museth (2009)).
2.4. Fluid solvers 14 Figure 6: A comparison between reflecting boundary conditions (top row of pictures), and absorbing ones (bottom row) (Müller et al.,2008). For boundaries where fluid should flow into or out of the domain, the two types above can be used. Inflow boundary conditions can be achieved by specifying reflecting ones, with an additional fixed normal velocity. For outflow boundary conditions, absorbing ones with free normal velocities can be used. These boundaries can then be enhanced by adding a source term to the height equation, directly adding (or subtracting) water in some regions. Such source terms are also ideal for modeling vertical sinks or sources of water (such as a drop falling from above, for instance in a particle system, or a drainage hole). 2.4 FLUID SOLVERS This section provides an overview of the methods used to model water behavior, focusing on methods that solve SWE in real-time applications. 2.4.1 Eulerian Solvers The traditional Eulerian fluid solvers are based directly on solving the underlying equations using a finite difference method (FDM) or finite volume method (FVM). Eulerian fluid simulations were first introduced to computer graphics in Foster and Metaxas (1996) which simulated a fluid surface and included a one-way water-object interaction by advecting the floating objects using the fluid velocity. A breakthrough came when the stable fluids semi-Lagrangian method was introduced in Stam (1999). It achieved significant performance improvements, ensuring the solver was unconditionally stable at larger timesteps. It should be noted, however, that the interpolation which guarantees stability, also introduces excessive dissipation, leading to a loss of small details and a less lively look. Most Eulerian simulation methods proposed afterwards use some variation of this approach. More advanced methods were also developed, such as the MacCormack method and its variants, to combat the deficiencies of this simple approach (Selle et al.,2008).
2.4. Fluid solvers 15 For shallow water, water surfaces were first simulated in Kass and Miller (1990) by solving the linearized SWE. Later, this work was in O’Brien and Hodgins (1995), modeling the flow between fluid columns with virtual pipes, coupling objects as they impacted the surface of the fluid and adding particle based splashes. The full SWE equations were first introduced in Layton and Panne (2002) to computer graphics, using the non-conservative form of the SWE. Since then the computer graphics community has continued using the non-conservative form where the governing equations are usually solved using splitting and explicit time-stepping on a staggered grid (Bridson (2015), Chentanez and Mueller (2010), Thurey et al. (2007)): first, the self advection of the velocity field is solved, then the heightfield and velocity field are integrated forward in time. The advection term (∂x ∂t+u·∇x) is commonly solved using the semi-Lagrangian method introduced in Stam (1999). An alternative with a simpler solver was proposed in Lee and O’Sullivan (2007) by ignoring the divergence term and using a uniform collocated grid. Although sacrificing unconditional stability for speed, it was shown to be sufficiently stable. In Wang et al. (2007) surface tension forces were added to the SWE to simulate water flow on arbitrary surfaces. An implicit Newmark integration scheme was used in Angst et al. (2008) to reduce numerical dissipation in the velocity advection step. In Chentanez and Mueller (2010) a modified MacCormack method (Selle et al.,2008) is used for the advection and stability is further improved by evaluating water height values in the upwind direction. SWE are also explored in the scientific community, namely in computation fluid dynamics (CFD). Here, the conservation law form of the SWE is preferred. The accuracy of the numerical solution is also prioritized over the computational efficiency, whereas in computer graphics the opposite is the norm. Methods that originated in CFD have also been used for realistic water animation. A finite volume scheme based on the formulation in Kurganov and Petrova (2007) was implemented on GPUs for real-time simulations with photorealistic rendering in Brodtkorb et al. (2012). Parna et al. (2018) demonstrated that with the power of modern era GPUs, higher order numerical techniques usually applied to CFD use cases, can be used in computer graphics for more visually compelling results. The technique presented avoids some commonly encountered issues (e.g. oscillatory solution profiles and mass conservation issues) and do not need to rely on post-simulation unphysical fixes (such as in Chentanez and Mueller (2010)). 2.4.2 Lattice-Boltzmann Method LBM is a grid-based method that originated from the field of statistical physics. Although it comes from descriptions on the molecular level, the method can still be used to compute fluids on a larger scale, and is applicable both in 3D and 2D. For simulations with LBM, the simulation region is usually represented by a Cartesian equidistant grid, where each cell only interacts with its direct neighborhood. While conventional solvers directly discretize the NSE,LBM is essentially a first order explicit discretization of the Boltzmann equation in a discrete phase-space. It has be shown that LBM approximates the NSE with good accuracy, a detailed overview of LBM and derivations of the NSE and SWE from the LBM can be found in Zhou
2.4. Fluid solvers 16 (2004). An in-depth review on the history and development of the LBM is presented in Arumuga Perumal and Dass (2015). LBM has several advantages that make it appealing for real-time applications. The LBM algorithm uses only arithmetic operations and is totally local, so it maps very well to parallel architectures such as GPUs. The method is also considered simple to understand and implement. Its shortcomings include the strict limit on the timestep to ensure stability, and large memory consumption (Ojeda Contreras,2013). It also has the same drawback of conventional SWE simulations when it comes to coupling with external dynamic objects, as it needs ad hoc processes to handle those interactions. The LBM has also proven to be an accurate and efficient alternative for solving the SWE. The first reports on this topic were conducted in Salmon (1999) and Zhou (2002). As the LBM is very suitable for parallel architectures, several publications can be found on solving the SWE with a GPU implementation (e.g. Kuznik et al. (2010), Tubbs and Tsai (2011)). Navarro-Hinojosa et al. (2018) provides a survey on GPU accelerated LBM applications. The LBM has seen some use in computer graphics, both for both 3D (Thürey et al.,2005) and shallow water (2D) simulations García Bauza et al. (2010). A series of publications by Ojeda and Susín can be highlighted, where they explore 2D versions of the method for shallow water simulations with a focus on real-time execution and GPU implementation (Ojeda Contreras (2013), Ojeda and Susín (2013), Ojeda and Susín (2014)). They also present an approach that couples the LBM for shallow waters with a particle system that adds more details, and supports breaking waves. Its performance is similar to the Eulerian alternative developed in Chentanez and Mueller (2010) (Kellomäki,2017). Recently, although the LBM for solving the SWE still sees extensive use in CFD, it has received little attention in computer graphics. A novel simplified LBM presented in Zhou (2022) could possibly be of interest as it has a reduced computational and memory cost while having similar accuracy. 2.4.3 Smoothed-Particle Hydrodynamics SPH is probably the most common of the particle-based methods. As it is a Lagrangian method, the advection term is automatically handled by the movement of the particles. All that remains is determining the various forces affecting the particles to update their velocity, and then to update the position based on the velocity. For this, the necessary fluid physical quantities and their derivatives need to be evaluated at the particle locations. SPH is a method used for interpolating these quantities as a distance-weighted sum from the values stored in the nearby particles (using kernel functions). External forces can be simply applied to each particle independently of the others. It was introduced to the computer graphics community with fire and gas simulations in Stam and Fiume (1995), with interactive simulations being demonstrated in Müller et al. (2003) with a limited particle count. There is a vast literature of variants and extensions of SPH that include, e.g., GPU implementations, different methods for enforcing incompressibility and handling boundaries, combining particles with varying sizes or timesteps, and multiphase fluids. However, most of the methods are not designed for a real-time context. A review of the theory
2.4. Fluid solvers 17 and applications of SPH in CFD and computer graphics can be found in Weaver and Xiao (2016) and Koschier et al. (2019). As was the case with grid-based methods, 3D particles methods were adapted to 2D with the goal of improving performance for interactive applications. The first case was in Lee and Han (2010), where the SPH model was applied to solve the SWE. This work was extended in Solenthaler et al. (2011) which introduces arbitrary domain boundaries and terrain slopes. They also add two-way coupling of the particle based fluid with rigid bodies, and improve the surface rendering of low density particle regions. In both cases the surface is defined as a height map, using the density to displace the vertices. Shallow water methods are naturally much faster than a full 3D solution, as they require far fewer particles, while also retaining the good rigid body coupling of SPH. However, shallow water SPH methods still have significantly worse performance than similar grid-based methods due to requiring very short timesteps (Kellomäki, 2017). Further work was done in Chladek and Durikovic (2015), which improved simulation accuracy and boundary handling. The shallow water simulation can also be coupled with a full 3D SPH simulation, although this has a considerable impact in performance. Fujisawa et al. (2017) extends the work in Solenthaler et al. (2011) by combining the 2D simulation with a 3D simulation to address missing behaviors such as splashes and breaking waves. The 3D particles are generated from 2D particles by categorizing these particles according to motion and position and deleted when they reenter the water’s surface. The 3D particles behavior is simulated using the position based fluid method (Macklin and Müller,2013) and both particle types are rendered using a screen-space rendering technique. Since then, significant work has been done in SPH, which reduces the severe time step restrictions of standard techniques (Koschier et al.,2019), however, this has still not been applied to SWE 2D simulations. 2.4.4 Summary The first and most researched solvers were of the Eulerian type. In particular, the splitting scheme and semi- Lagrangian advection combination became the most popular in computer graphics (Bridson,2015). Alternatively, recent work (Parna et al.,2018) argues that higher order numerical methods, commonly found in the scientific community, can provide a higher quality solutions and avoid unphysical modifications, with an acceptable increase in computational cost. An alternative is the LBM which has a simple and easily parallelizable algorithm. Its update step is fast but forces the use of small timesteps to ensure stability, which leads to a similar performance to other Eulerian methods (Kellomäki,2015), while having increased memory requirements (Ojeda and Susín,2014). A third counterpart is the SPH model, which provides unique advantages due to being a particle based method, such as the inherent conservation of mass and coupling with objects. Although SPH has seen significant advances recently (Koschier et al.,2019), they are yet to be applied to the SWE, where previous solvers have significantly worse performance than their grid-based counterparts (Solenthaler et al. (2011), Kellomäki (2017)).
2.4. Fluid solvers 18 This is further accentuated by the requirement of extra heightfield surface construction procedures, and needing high particle counts to avoid blobby a surface (Chladek and Durikovic (2015), Fujisawa et al. (2017)).
2.5. Rendering 19 2.5 RENDERING The previous section focused solely on the dynamics of the fluid and its interaction with the terrain. The goal of this section is to explore real-time rendering effects that can achieve a realistic representation of the developed fluid simulation, including the water color, small surface details and caustics. 2.5.1 Water Surface Color The water’s surface color is composed of reflected and transmitted/refracted light, which can be handled as two separate components. The ratio between the two is given by the Fresnel reflectance F, which specifies how much light is reflected at an interface between two different media. Consequently, the transmitted fraction is given by 1−F, resulting in a final composition as in Equation 15.Cre f l and Ctrans are the light intensities that are reflected and transmitted, respectively, before applying the Fresnel factor. C=F(θi)Cre f l + (1−F(θi))Ctrans (15) Fis often calculated using Schlick’s approximation (Schlick,1994), given in Equation 16, which takes as input the angle of incidence θiand the specular reflectance at normal incidence f0(for water, f0=0.02,Akenine- Mller et al. (2018)). F(θi,f0) = f0+ (1−f0)(1−θ)5(16) Reflection A surface’s BRDF, denoted by f(ωi,ωo,n), describes for a particular point, how much of the incoming light in a direction ωiis reflected in an outgoing direction ωo, where nis the surface normal. Considering a surface lit from a single direction, such as by a directional light, the reflected light at the surface can be given by Equation 17, where Clight is the light’s intensity and all vectors are considered to be normalized. This is illustrated in Figure 7 where the value θirepresents the angle between nand ωi. Cre f l =f(ωi,ωo,n)Clight(n·ωi)(17)
2.5. Rendering 20 Figure 7: The BRDF defines the amount of light that is reflected at a surface point p with normal n from incident direction ωiin the outgoing direction ωo. The BRDF, is typically made of two terms: a diffuse component and a specular component (Pharr and Humphreys,2018). However, when describing the surface of a transparent media such as water, only the specular component is considered, as the refracted/transmitted light is handled separately. Physically based specular BRDF terms are typically based on microfacet theory (Pharr and Humphreys,2018). The core idea is that any surface at a microscopic scale can be described by tiny perfectly reflective mirrors called microfacets. The light reflectance is then statistically modeled based on these surface variations that are present below the observation scale. One of the most commonly used models is the Cook-Torrance model (Cook and Torrance,1982), given by Equation 18. f(ωi,ωo,n) = D(h)F(ωi,h)G(ωi,ωo,h) 4(n·ωi)(n·ωo)(18) As the microfacets are considered to be perfect mirrors, for a microfacet to reflect light from ωiinto ωoits surface normal has to be oriented exactly halfway between ωiand ωo. The vector halfway between ωiand ωois called the half-vector and denoted as h.D(h)is the microgeometry Normal Distribution Function (NDF) evaluated at the half-vector hand represents the probability that a given microfacet’s normal mis oriented correctly, i.e. m=h. G(ωi,ωo,h)is the geometry function1and it represents the proportion of surface points with m=hthat are not shadowed (microfacets not being directly lit) or masked (microfacets being occluded by other microfacets from the viewing direction). Therefore, the product of D(h)and G(ωi,ωo,h)gives the concentration of active surface points, the surface points that actively participate in the reflectance by successfully reflecting light from ωiinto ωo. F(ωi,h)is the Fresnel reflectance of the active surface points as a function of the light direction ωiand the active microgeometry normal m=h. Finally, the denominator 4(n·ωi)(n·ωo)is a correction factor which accounts for the transformation of quantities between the local space of the microgeometry and that of the macro-surface. A widely adopted choice for the Dand Gterms is the GGX distribution and its matching Smith geometric function (Burley (2012), Heitz (2018), Guy and Agopian (2019)). A review of the options for these terms and 1 Can also be found in the literature with various other names, such as: geometry factor, shadowing-masking function, shadowing function, geometry term, geometric attenuation, amongst other denominations.
2.5. Rendering 21 additional information on the subject can be found in Pharr and Humphreys (2018) and Hoffman (2013). Specific models have been used in ocean rendering, however these rely on the statistical properties of ocean wind waves (Bruneton et al.,2010). To compensate for the lack of indirect lighting, which is especially noticeable with highly specular surfaces, some kind of ambient or image-based lighting is typically added (Hoffman,2013). Transmission Transmitted/refracted light is given by the reflection of the terrain below. However, this is further complicated by the fact that water acts as a participating media and therefore affects the distribution of radiance in it. Light that enters the water volume, after being refracted at its boundary, will be affected by two main processes (Pharr and Humphreys,2018): • Absorption, which causes reduction in radiance due to conversion from light to some other form of energy, such as heat. • Scattering, which causes the light direction to change due to particle collisions. As a ray of light passes through a media, it can collide with particles and be scattered in different directions, which results on the ray losing intensity. Consequently, radiance from other rays can also be scattered into the path of this ray increasing its intensity. These interactions are referred to as out-scattering and in-scattering respectively. Furthermore, single and multiple scattering can be distinguished when considering the number of times a light ray is scattered when traveling through the media (Figure 8). Figure 8: When entering a participating media, light can be scattered once (left) or multiple times (right) before exiting the media. How much scattering happens is described by the scattering coefficient σs. Similarly, how much the media absorbs light is determined by the absorption coefficient σs. Combining both coefficients results in the extinction/attenuation coefficient σt=σa+σswhich describes how much light is attenuated along its path through the media. The fraction of light that is not absorbed or scattered, while traveling a distance dthrough the media, is defined as the transmittance (given by the Beer-Lambert Law) as in Equation 19 (Pharr and Humphreys,2018). T(d) = e−σtd(19)
2.5. Rendering 22 The variance of the photon flux in a light ray traveling through the media can be visualized in Figure 9. Figure 9: Illustration of how the photon flux of a light ray is affected when in a participating media. 2.5.2 Caustics Figure 10: Visible caustics caused by perturbations in the water surface. Examples from Yuksel and Keyser (2009), Parna (2020) and Yang and Ouyang (2021), from left to right respectively. Caustics are concentrations of light in diffuse surfaces (receivers) caused by refraction or reflection of light from a highly specular surface (generator). In water rendering, caustics are interesting visual elements that enhance the quality and realism of generated images, while also providing additional cues to perceive the shape of the water surface (examples presented in Figure 10). The efficient rendering of caustics in real-time is rather difficult, as a single point may depend on light redirected from several points. In an early attempt at real-time caustics, a technique was presented in Stam (1996) which projected a precomputed texture onto the scene geometry using additive blending, animated by texture coordinate perturbation. Although this technique is extremely fast, evidently the caustics produced are not correct in relation to the water surface and receiver geometry. A method is proposed in Guardado and Sanchez-Crespo (2007) that computes caustics by tracing rays from the receiver surface to the water surface, where each receiving point is computed from a single point in the surface. The intensity is modulated based on the direction of these rays and samples a light map in the normal direction at the intersection point. The results produced by this method are not physically correct either, and
3.1. Numerical method 29 takes as input a stencil1of the 4 surrounding time-averaged fluxes ( ˜ Fand ˜ G). The subscripts denote the position in the grid and a description of the WENO3procedure can be found in Appendix B. ˆ Fi+1/2,j=WENO3(˜ Fi−1,j,˜ Fi,j,˜ Fi+1,j,˜ Fi+2,j) ˆ Gi,j+1/2 =WENO3(˜ Gi,j−1,˜ Gi,j,˜ Gi,j+1,˜ Gi,j+2)(24) The spatial derivatives ˜ Fxand ˜ Gy(in Equation 20), of ˜ Fand ˜ Grespectively, are approximated by a conservative flux difference, as in Equation 25, using the values at the cell’s edges, ˆ Fand ˆ G.∆xand ∆yare the cell’s dimensions in the xand ydirection respectively. ˜ Fx;i,j=1 ∆x(ˆ Fi+1/2,j−ˆ Fi−1/2,j) ˜ Gy;i,j=1 ∆y(ˆ Gi+1/2,j−ˆ Gi−1/2,j) (25) Inserting Equation 25 into Equation 20 gives its finite difference discretization, as in Equation 26 (Parna et al., 2018). Un+1 i,j=Un i,j−∆t ∆x(ˆ Fn i+1/2,j−ˆ Fn i−1/2,j)−∆t ∆y(ˆ Gn i,j+1/2 −ˆ Gn i,j−1/2) + ∆tSn i,j(26) 3.1.3 Well-balanced treatment of the source term Steady state solutions (e.g., a still flat water surface) in non-flat bottoms have it’s flux gradients exactly balanced by the source term S. This balance will fail to be preserved if a straightforward treatment of the source term is used. This issue is addressed by the inclusion of the method described in Xing and Shu (2005) (Parna et al., 2018). One of the requirements of the method is to modify and split the source term into two parts as in Equation 27. The central finite difference approximations used in Equation 22 must follow this splitting. S= 0 (1 2gb2)x (1 2gb2)y + 0 −(h+b)gbx −(h+b)gby (27) 1 A stencil is a set of grid points that relate to the point of interest, when using a numerical approximation routine.
3.1. Numerical method 30 The other requirement is to then approximate the split source term derivatives using the WENO reconstruction (Xing and Shu,2005), similarly to the fluxes. Therefore, the final source term S(used in Equation 26) is given by Equation 28, where s= (1 2gb2), and ˆ sand ˆ bare the values of sand bat the cells’ edges. Si,j= 0 1 ∆x(ˆ si+1/2,j−ˆ si−1/2,j)−(h+b)g1 ∆x(ˆ bi+1/2,j−ˆ bi−1/2,j) 1 ∆y(ˆ si,j+1/2 −ˆ si,j−1/2)−(h+b)g1 ∆y(ˆ bi,j+1/2 −ˆ bi,j−1/2) (28) The values at the cells’ edges, ˆ sand ˆ b, are computed using the WENO reconstruction, sharing the non-linear weights of the fluxes (as described in Appendix B). The input stencil contains the required values of band s. ˆ si+1/2,j=WENO3(si−1,j,si,j,si+1,j,si+2,j) ˆ bi,j+1/2 =WENO3(bi,j−1,bi,j,bi,j+1,bi,j+2)(29) 3.1.4 Handling of the wetting/drying processes The computation of the mass-conservation equation, given by the first line of the conservative SWE, must be made positivity preserving for the scheme to allow wetting and drying processes (Parna et al.,2018), that is, the values of hneed to remain non-negative. This is achieved by incorporating the maximum principle preserving method in Liang and Xu (2014) for the mass computation equations. The final fluxes for the mass, namely the first components of ˆ Fand ˆ G, are re-defined as a linear combination of low- and high-order fluxes, as in Equation 30. Here, the (1)superscript denotes the first entry of a vector. ˆ F(1)←θˆ F(1)+ (1−θ)˜ f ˆ G(1)←θˆ G(1)+ (1−θ)˜ g(30) The ˜ fand ˜ gare first-order positivity preserving flux approximations. These are evaluated using the Lax- Friedrichs flux (Seal et al.,2016)asinEquation 31, where αis given by Equation 61. ˜ fi+1/2,j=1 2F(1) i,j+F(1) i+1,j−αi(U(1) i+1,j−U(1) i,j) ˜ gi,j+1/2 =1 2G(1) i,j+G(1) i,j+1−αj(U(1) i,j+1−U(1) i,j)(31) The coefficients of the linear combination, θi+1/2,jand θi,j+1/2, are determined in a way that ensures the interpolation between the high and low-order fluxes is of the highest order possible, while preserving the positivity of the solution. This is achieved by solving a simple optimization problem, described in Appendix C.
3.2. Implementation 31 Wet/dry interface velocities Since finding the velocities uand vrequire divisions by h(as only the momenta hu and hv are stored in U), high velocities can develop near the wet/dry interface where his very small or even 0, which would then lead to instabilities (Parna et al.,2018). To avoid this, the method in Kurganov and Petrova (2007) is used, where uand vare recalculated using Equation 32 in regions where his smaller than a specific threshold e. The determination of eis problem specific but a value of 0.01 as used in Parna et al. (2018) was found to be suitable for the scenes used. u0=√2h(hu) ph4+max(h4,e) v0=√2h(hv) ph4+max(h4,e) (32) This is applied to Uat the start of the simulation step, which is updated with the new velocity values u0and v0, as in Equation 33. Additionally, the water depth his clamped to zero as it can become negative due to numerical round-off errors (Parna et al.,2018). U= max(h, 0) hu0 hv0 (33) 3.2 IMPLEMENTATION The implementation was tackled using GPU programming, more specifically OpenGL compute shaders. The GPU has been shown to be highly effective for this kind of simulations as it is able to handle large amounts of parallel data and maps well to the Eulerian (grid) approach (Parna et al. (2018), Dagenais et al. (2018), Horváth et al. (2020)). Additionally, storage of the simulation results on the GPU means that rendering is straightforward as there’s no need in copying data between the CPU and GPU. For the solver step, the single kernel GPU implementation of Parna et al. (2018) is followed, which aims at decreasing the costly memory read/writes at the expense of arithmetic operations. The scheme is compressed into a one pass solution by making heavy use of local group setup combined with local synchronization and abstract Group Shared Memory (GSM) usage. 3.2.1 Timestepping The first step of the simulation is determining the timestep, which is limited by the stability restrictions of the scheme. Dynamic timestepping with a maximum fixed timestep is used as it can advance the simulation in real-time, while also guaranteeing stability.
3.2. Implementation 32 For the simulation to run at real time, every frame of the animation should advance the simulation roughly the same amount forward in time as the frame’s duration. This can be approximated by using the previous frame’s duration, frameTime, as a reference for how much the simulation should advance, so ∆t=f rameTime. However, the timestep ∆thas to be restricted, in order to ensure stability, by defining an upper bound max∆t. Since no unexpected accelerations are introduced in this work, e.g. via the user’s input, this max∆tcan be determined empirically. Considering that the frame duration can be longer than the defined maximum timestep, advancing the simulation can require multiple steps, which are performed iteratively while consuming the frame time. For example, with max∆t=12ms and f rameTime =30ms, three solver steps would be performed, each with ∆t=10. 3.2.2 Data storage The three components of U(the height, and momentum terms in the xand ydirections) need to be stored in between simulation steps. This is done using two textures, where the data is read from one and written to the other, swapping after each simulation step. These have 4 channels of 32 bit floating point data, 3 for the components of U, the last being used to encode boundary information (its use is described in Section 3.2.4). As the algorithm uses a co-located grid, the mapping to a texture is straightforward, where each texel corresponds to a grid cell. A single channel texture is also used to store the bathymetry data. The height and normal of the water are also required to be stored so they can then be used when rendering the water surface (chapter 4). A 32 bit 4 channel texture is used for this, where the first 3 channels are used to store the normalized normal vector of the water surface, and the last channel is used to store the water surface height (given by the water depth plus the bathymetry). The grid that constitutes the simulation domain has dimensions of Wand Hin the xand ydirections respectively. The simulation data textures have dimensions equal to (W+B×2, H+B×2), where (W,H)is the simulation domain and Bis the number of boundary cells (see Section 3.2.3). Although not required, the bathymetry and the "normal and height" textures have the same dimensions so they can be accessed using the same coordinates. 3.2.3 Threading scheme The concurrent computation work is managed by decomposing the simulation domain into fixed size smaller groups, where each thread corresponds to a cell. Each one of these groups will require their own set of boundary cells in order to correctly process the values at the edge of the group’s domain. The scheme has a series of computations that require accessing the neighboring cells’ data, which is stored in the GSM (further information in Section 3.2.6). The computed data in a cell can be invalid if it is the result of computations that involve values outside the range of the local GSM. If other cells access this invalid data, then their computations derived from it will also become invalid. Tracking the validity of the computed data in each
3.2. Implementation 33 cell, the scheme is found to require 4 boundary cells (Parna et al.,2018), as illustrated in Figure 12. Cells where the results are valid are referred to as inner domain cells. Figure 12: Access of neighboring cells that leads invalid values (example for left boundary of the x direction, same applies for y ). Valid cells colored in green and invalid cells in white. The valid cells are determined as follows: (1) initial group domain; (2) cells where ˜ F is valid (Equation 22); (3) cells where the WENO reconstructions are valid (Equation 29); (4) cells where θ is valid (Equation 73); (5)cells where the final Un+1is valid (Equation 26) These boundary cells need to be overlapped with valid cells of other groups, so all the simulation domain is covered. This is illustrated in Figure 13 where a grid point is involved in calculations once as a boundary cell, where the results are not stored, and once as an inner domain cell, where the results are written to the textures. Figure 13: Illustration of overlapping threads between neighboring groups in a single dimension. Inner domain cells are colored in green and boundary cells in white. As some grid points are involved in calculations more than once, more threads need to be dispatched than the total number of inner domain cells. The total number of groups to be dispatched for each dimension, in order
3.2. Implementation 34 to accommodate for the boundary cells, is given by Equation 34.Kxand Kyare the number of elements in each work group for the xand ydimensions respectively. Gx=W Kx−2×B Gy=H Ky−2×B(34) Since the number of groups is rounded up (denoted by de) to encompass all the simulation domain, more threads than required can be dispatched. To account for this, global boundary cells are required in addition to the local group boundary cells (which can overlap), since a thread can be inside a group’s inner domain, but outside the simulation domain. An illustration of the simulation domain within the dispatched compute groups is presented in Figure 14. The local computation results are written to the output textures only for cells where they are valid, i.e., that are both part of the local inner domain and global inner domain. Figure 14: Illustration of the simulation domain within the dispatched compute groups, with a group highlighted. Each group is composed of its local inner domain (B) and local boundary cells (A) . Similarly, the whole simulation domain is composed of the global inner domain (C) and global boundary cells (D) . There can be threads outside the global domain (E). Indexing into the textures has to consider the boundary cells and overlapping threads. The global indices ig and jgin the xand ydirections can be found as in Equation 35, where Gdenotes the group ID, Tthe thread ID in the given group and the x/ysubscripts the dimension. ig=Gx×(Kx−2×B) + Tx jg=Gy×(Ky−2×B) + Ty (35) These indices are used only when interacting with the simulation data textures, that is, the initial read and the final write. All other intermediate computations that require accessing the neighbors data through shared memory
3.2. Implementation 35 use the local group thread ID Txand Ty. The final write to the textures is only performed if the conditions given in Equation 36 are true, which guarantee that the cell is both in the global inner domain (Cg) and local inner domain (Cl). Cg= (ig≥B)∧(ig<W+B)∧(jg≥B)∧(ig<H+B) Cl= (Tx≥B)∧(Tx<Kx−B)∧(Ty≥B)∧(Ty<Ky−B)(36) 3.2.4 Boundary conditions Reflection boundary conditions are used, in the form of "no-stick" boundaries, i.e, the velocity in the normal direction should be zero at the boundaries (Section 2.3.3). These are implemented using the global boundary cells, by making them mirror the 4 nearest inner domain cells, while changing the sign of the velocity in the normal direction to the respective boundary. At the end of each solver step, a cell writes its computation results to their position in the output texture. If the cell is in the 4 nearest to the boundary, it also writes a copy to the boundary cells that should mirror it. This copy has the sign of its velocity/momentum changed depending on which dimension the cell is mirrored, i.e., the copy is multiplied by a specific boundary vector ((1, −1, 1)Tand (1, 1, −1)Tfor xand ypropagation respectively). This process is demonstrated in Figure 15. Figure 15: One dimension view of the simulation domain near the left boundary. The 4 inner domain cells closest to the boundary write their data to the mirrored global boundary cells, denoted by the bottom arrows. The cells’ depths are represented by the blue columns, and the arrows above it denote the velocity in the displayed dimension. The signal of this directional momentum/velocity component is changed when written to the boundary cells. As a way to avoid potentially reduced performance caused by thread divergence, branching based on thread ID for boundary conditions is avoided (Parna et al.,2018). As an alternative, each cell of the inner domain that is to be mirrored in the boundary cells contains the offsets to those boundary cells. The offsets then can be added to the previously computed global indices in order to find the ID of the boundary cell. As the grid is 2D, the value of a cell can be propagated up to a maximum of two boundary cells, one in the xdirection and one in the y direction, so the offsets can be defined as a pair of values. To exemplify, if a cell at (5, 5)should copy its data to
3.2. Implementation 36 the boundary cells at (4, 5)and (5, 4), then it would contain the offsets (−1, −1). For cells that do not copy their content to boundary cells, a large offset (k) to out-of-bounds cells is assigned 2. Since offsets provided by 16bit integers are enough, both offsets can be packed into the single 4th component of the simulation data texture. Summing up, all inner domain cells write their computation results to their corresponding cell, as well as a copy multiplied by a specific boundary vector into two boundary cells, defined by the offsets. Some example scenarios are presented in Figure 16. Figure 16: Propagation of data from inner domain cells to boundary cells. Example scenario of top left corner of a group. The inner domain cells that copy their data to boundary cells are highlighted in green, the ones that do not are in yellow. The solid arrows indicate the direction of the packed offsets and the dashed-arrows indicate offsets that lead to out-of-bounds accesses. At (4, 5) the offsets are (−1, −3) , at (5, 5) are (−3, −3) , at (6, 5) are (−5, −3) , at (8, 6) are (k,−5) and at (8, 8) are (k,k) , with k being an arbitrarily large number that always leads to out-of-bounds. Initial setup The packed offsets are constant during the simulation so they only need be to set up once at the start. Only the 4 inner domain cells nearest to the boundary (highlighted in green in Figure 15 and Figure 16) are copied to boundary cells, consequently, only they require specific packed offsets. The offsets to be packed at each cell can be determined as in Algorithm 1, where nWidth and nHeight are the width and height of the inner domain, 2 Writes to out-of-bounds texels are guaranteed to do nothing by the OpenGL specification.
3.2. Implementation 37 OOB_OFFSET is a large offset that leads to out-of-bounds accesses and B=4is the number of boundary cells. Algorithm 1: Offsets initialization Input: Cell coordinates p ox ←OOB_OFFSET; oy ←OOB_OFFSET; for i←0; i<B;i←i+1do o f f set ←1+2×i; if p.x=ithen ox ← −o f f set; if p.x=nWidth −i−1then ox ←o f f set; if p.y=ithen oy ← −o f f set; if p.y=nHeight −i−1then oy ←o f f set; end return packBCData(ox,oy); Packing and unpacking As the texture initialization is done in the GPU where bit manipulation is limited, an example of the packing and unpacking of offsets is described here. When packing the offsets, the packHalf2x16 function is used to pack them into a single 32 bit integer followed by uintBitsToFloat to access the integer as a float. Subsequently, floatBitsToUint followed by unpackHalf2x16 is used to extract the packed offsets. This allows the representation of a range of values up to 65536 which is more than enough for its use. Flux boundaries The previously described boundaries apply only to the final write of the computation results to the output texture. However, when computing the WENO reconstructions (Equation 64), the stencil of time-averaged fluxes should also consider the boundary conditions (Parna et al.,2018). These intermediate flux boundaries need to be handled manually as out-of-bounds writes causes the invalidation of shared memory. Given this, the directional flux boundaries are only set if the corresponding boundary cells are inside the current group, as defined in the condition in Equation 37 for the xdirection, where Oxis the xoffset and Kxthe group dimension. This is set similarly for the ydirection. Cf= (i+Ox≥0∧i+Ox<Kx)(37)
3.2. Implementation 38 To be consistent with the reflective boundary condition applied previously, the boundary cells receive copies of their respective inner domain cell time-averaged flux values multiplied by a boundary-vector that reflects the horizontal velocity components ((−1, 1, 1)T). 3.2.5 Algorithm loop Each solver step takes as input a simulation data texture, resulting from the previous timestep’s simulation, and the bathymetry texture. During its execution, it updates the output simulation data texture, as well as the normal and height texture. The two simulation data textures are swapped out after each render step to create a loop (also called the ping-pong technique). Initially, one texture is filled with the simulations starting conditions, and then compute calls are chained that perform operations on this data, swapping out the textures in between. A diagram of the process is presented in Figure 17. Before this loop, an initial setup step is performed that fills the required textures: first input simulation data texture, bathymetry texture and height and normal texture. Figure 17: Diagram of the pipeline of the main rendering loop. 3.2.6 Algorithm step A solver step consists of a single compute shader call which implements the previously described numerical scheme (Section 3.1). Each thread computes the required values at its corresponding cell (i,j), and intermediate values at the cell’s edges at (i+1, j)and (i,j+1). The implementation of the step follows the description and use of shared memory presented in Parna et al. (2018), adding the steps required for filling the height and normal texture. An abstract approach to GSM management is used in order to minimize the total GSM block size. GSM is treated as arrays of raw memory which are used as needed by the scheme. Each element of the arrays corresponds to a thread in the group, consequently, the arrays’ length is equal to the group’s size. Four arrays are used in total: one of type float (denoted as
4.2. Water Surface Color 45 V(v,l,α) = G(v,l,α) 4(n·l)(n·v)=V1(l,α)V1(v,α) V1(v,α) = 1 n·v+pα2+ (1−α2)(n·v)2 (42) Heitz (2014) notes however that taking the height of the microfacets into account to correlate masking and shadowing leads to more accurate results. The height correlated visibility function thus becomes Equation 43, as in Guy and Agopian (2019). V(v,l,α) = 0.5 n·lpα2+ (1−α2)(n·v)2+n·vpα2+ (1−α2)(n·l)2(43) 4.2.2 Intersecting the heightfield Reflected and refracted rays need to be intersected with the environment in order to compute the light going in its direction and effects along its path. Only intersections with the terrain are considered, and therefore, only one intersection test is needed for either refractions or reflections. As the terrain is represented by a heightfield, a heightfield ray-casting approach is followed for both refractions and reflections. The maximum mipmaps technique is used as it provides a fast and scalable solution for intersecting heightfields, with negligible precomputing (Dick et al. (2009), Silvestre (2017)). The ray-casting algorithm relies on a precomputed maximum mipmap as an acceleration structure to skip empty space when advancing the ray. A limitation of this algorithm is that, due to its quadtree structure, it can only be used with heightfields in power-of-two resolutions. Maximum mipmap Texels in the maximum mipmap contain the maximum height value over a certain extent of the heightfield depending on the mipmap level. The maximum mipmap follows a quadtree structure, where a texel in given mipmap level contains four children texels in the next finer level. The finest level (0), is the original heightfield texture, and the coarser levels are associated with ascending level numbers. Each mipmap level is, therefore, computed by determining the maximum value of the four children texels in the level below and storing it in the parent texel. This process starts at the finest level, and is applied recursively on each level until the coarsest level is reached, which consists of a single texel. A visual representation of the maximum mipmap is presented in Figure 22. The mipmap is generated at the application’s start, and introduces additional GPU memory requirements of 1/3 of the memory needed to store the original heightfield.
4.2. Water Surface Color 46 Figure 22: Visualization of different levels in a maximum mipmap representing an heightfield. Each texel can be seen as a bounding box over a certain extent of the heightfield (from Tevs et al. (2008)). Ray traversal algorithm The ray-traversal method described in Dick et al. (2009) is followed, using a linear approximation for the final intersection test (Drobot,2018). Initially, the ray’s starting position and direction are converted to the heightfield’s texture size coordinates from world coordinates. After the final hit point is determined, the position is converted back to world coordinates. The following description of the algorithm applies to an example ray direction dir with dir.x≥0and dir.z≥ 0. To reduce the number of conditional branches within the ray-casting loop, the sign (≥0,<0) of each dir.x, dir.zand dir.yis tested at the beginning, and the ray-casting loop is replicated for each of the eight branches. The differences between branches are explained when relevant. The traversal algorithm steps the ray through any of the mipmap levels by recalculating the ray entry and exit points of each texel. The entry point of the current heightfield texel is denoted by texEntry and is initially equal to fragment’s position. The ray-casting loop is run while the ray does not intersect the heightfield and does not leave the domain, i.e, texEntry.x<N∧texEntry.z<N. For other branches these conditions are adjusted accordingly, for example if dir.x<0, the xboundary condition is instead texEntry.x≥0. If dir.y>0, an additional boundary is set at the highest level of the heightfield, which can be sampled from the coarsest level of the mipmap (texEntry.y≤maxHeight). Let ldenote the current level of the mipmap which is used to test for ray intersection. Initially, the second coarsest level is used, so l=maxLevel −1. At the start of each ray-casting step, the current heightfield texel is fetched from the current level. The texel’s coordinates are given by (btexEntry.x 2lc,btexEntry.z 2lc). For other branches, for example if dir.x<0, the texel’s xcoordinate would be instead dtexEntry.x 2le−1. This also applies to any other texel’s coordinates, such as in texel’s edges. The ray’s exit point texExit is then computed from that texel. For this, the ray is intersected with the texel’s edges, as illustrated in Figure 23. Of the two intersections, texExit becomes the closest one, given by the smaller ray parameter ∆t.
4.2. Water Surface Color 47 Figure 23: The exit point of a ray from a texel is determined by considering two of its edges. Of the ray’s intersection points with these edges, texExit is the one closest to texEntry , i.e., with the smaller ∆t . To avoid infinite looping due to rounding errors, the coordinates are set to the intersected texel edge, for example, if ∆t=∆tx then texExit.x=btexEntry.xc+1. The full process for determining texExit is given in Algorithm 2. Algorithm 2: Determining the exit point of a heightfield texel texEdges.xz ←(btexEntry.xz 2lc+1)×2l ∆t.xz ←texEdges.xz−texEntry.xz dir.xz ∆t←min(∆tx,∆tz) texExit ←texEntry +∆t×dir if ∆t=∆tx then texExit.x←texEdges.x else texExit.z←texEdges.z end Having determined texExit, the intersection test is performed. This test depends on the ray’s vertical direction: If the ray is going upwards (dir.y≥0) the ray intersects the texel if texEntry.y<height; if the ray is going downwards (dir.y<0) the ray intersects the texel if texExit.y<height. If an intersection is detected in the first case, the intersection point is equal to texEntry. In the second case, the intersection point is computed as in Equation 44. Both outcomes are illustrated in Figure 24. intersection =texEntry +max height −texEntry.y dir.y, 0×dir (44)
4.2. Water Surface Color 48 Figure 24: The ray’s entry and exit points at the texel are denoted by a red point, and the intersection points by a black cross. When testing for intersection, the height value is compared to either the entry or exit point, depending on whether the ray is going upwards or downwards, respectively. If the ray intersects the texel, the ray is advanced to the intersection point, so texEntry becomes texExit. Additionally, if l>0, traversal must proceed to the next finer level to test intersections more accurately on a child texel (l←l−1). Once at the lowest level (l=0), instead of a descending operation, an intersection test is performed with the heightfield. Here, the surface is approximated as a linear interpolation (Drobot,2018). The heightfield is sampled at the entry and exit positions of the cell, texEntry and texExit. Then, the final point is given as the intersection between the ray and linearly approximated curve created by the sampled points, as illustrated in Figure 25. Figure 25: At the finest level, the ray (denoted in red) is intersected with a linear approximation of the heightfield (denoted in blue). Even if the ray intersects the texel it can miss the linear intersection test (left).
4.2. Water Surface Color 49 If the ray does not intersect the heightfield within the texel, texEntry becomes texExit and the loop advances to the next step. If the texel that would be tested in the next traversal iteration has a different parent texel than the current texel, the level is increased (l←l+1). This process is given in Algorithm 3. Algorithm 3: Increasing the mipmap level if necessary if ∆t=∆tx then edge ← btexExit.x 2lc else edge ← btexExit.z 2lc end l←min(l+1−(edge (mod 2)),maxLevel −1) If it leaves the domain without intersecting the heightfield, the ray is intersected with the boundary. This is performed similarly to Algorithm 2, but intersecting the domain boundaries instead of the texel’s edge.
4.2. Water Surface Color 50 An overview of the full algorithm is given in Algorithm 4, for heightfield size N×N. The return values are a boolean which indicates if an intersection with the terrain was found, and the intersection point position. Algorithm 4: Maximum mimpmap heightfield intersection Input: Ray direction and initial position. l←maxLevel −1 texEntry ←rayOrigin while texEntry.x<N∧texEntry.z<Ndo Fetch height from current texel and level. Determine texExit (Algorithm 2). if texExit.y≤height then Advance texEntry to intersection point (Equation 44). if l>0then Descend one level. else Check intersection with heightfield (Figure 25). if intersects heightfield then return true and hit position. else Advance texEntry to texExit. Ascend one level if needed (Algorithm 3). end end else Advance texEntry to texExit. Ascend one level if needed (Algorithm 3). end end Compute accurate intersection with domain boundaries. return false and hit position. 4.2.3 Environment reflection In addition to the Sun’s reflection, the environment’s reflection is also considered. These include the parts of the terrain that are above the water surface, and the far-away environment, namely the sky. A simplified approach is used where the water surface is assumed as perfectly specular, so only one direction needs to be sampled
4.2. Water Surface Color 51 to obtain the reflection color. This value is then multiplied by the Fresnel reflectance about the surface normal, resulting in Equation 45. Cenv =F(v·n)Cenv (45) The reflection color Cenv is determined by casting a ray to intersect the terrain, using the previously described method. If it intersects the terrain, its color and normal are fetched from the respective textures and its lighting is computed using a perfectly diffuse BRDF. For rays that do not intersect the terrain, a color is fetched from a cubemap that depicts the far-away environment. Both outcomes are exemplified in Figure 26. Figure 26: A reflected ray can intersect the terrain (right), or sample from an environment map (left). 4.2.4 Transmission The transmitted color Ctrans is composed of light reflected on the bottom Cbottom and scattered light (due to inscattering) Cscatter, while subject to attenuation. Light that is not attenuated is determined by the transmittance T(d), as given by Equation 19, where dis the distance that light traveled while inside the medium. This is under the assumption that the water volume is homogeneous, i.e. it has the same extinction coefficient in all its volume. Scattering is simply approximated as an added constant diffuse color, Cscatter. An additional intensity modifier Icis fetched from a caustics map texture and multiplied by the bottom color. The caustics map generation process is described in the following section (Section 4.3). The final transmission color computation is given by Equation 46. Ctrans = (1−F(v·n)) ×(IcCbottomT(d) + Cscatter)×Csun (46) Refracted ray The bottom reflection color Cbottom and transmission distance dvare determined by intersecting a refracted ray with the bottom terrain. Most water bodies are bounded by terrain, such as lakes and rivers, so a ray that enters the water is expected to hit the ground further on. This, however, is not true for transparent enclosing surfaces, such as in an aquarium, or terrain sections with invisible boundaries. When hitting one of these surfaces, the ray
4.2. Water Surface Color 52 can then be refracted again and used to fetch a color from an environment map (as used for reflections). Both cases can be visualized in Figure 27. Figure 27: A refracted ray can intersect the terrain (left), or a bounding box where it is refracted again and samples from an environment map (right). As with the reflections, the bottom color and normal are fetched from the corresponding textures using the intersection point’s position. Similarly, a perfectly diffuse BRDF is used for the lighting computation. Light Path When computing the transmittance of the refracted ray during the light’s path inside the water volume, the whole path should be considered, that is, both before and after the light is reflected at the bottom. The former is given by the intersection algorithm, while the latter can be approximated as coming from a flat surface at the same height as the entry point. The total distance is given by Equation 47 and is illustrated in Figure 28, where dvis the distance determined during ray intersection and cos θ=n·lr. The water height his given by the difference between the height of the current fragment and of the intersection point. d=dv+h cos θ(47) Figure 28: Path traveled by the light inside the water body before it reaches the viewer, represented by the solid vectors vrand lr.
4.2. Water Surface Color 53 A more accurate estimate for this distance can also be retrieved from a texture. This distance is computed during the caustics simulation and stored in the texture in a previous pass, as is described in the following section (Section 4.3). The previous approximation has the worst results when the light ray enters and leaves the water surface at considerably different heights. As such, when using the more accurate path obtained from the caustics simulation, the difference in results will be visible where these heights most differ. This difference is exemplified in the comparison presented in Figure 29, where lris the approximated light path, and lrc the one determined during caustics simulation. Figure 29: Comparison between an approximated light path, lr , and a more accurate path computed during caustics simulation, lrc. A comparison of results is presented in Figure 30. The difference is particularly noticeable if the water has low transmittance, as the distance traveled by the light inside the water volume will have a greater impact on its final color. Figure 30: Comparison between an approximated light path (left) and a more accurate path computed during caustics simulation (right). A high absorption coefficient is used, and the caustics’ intensity is not considered for better clarity.
4.2. Water Surface Color 54 4.2.5 Overview The water’s final color is defined as a mix of reflected and transmitted light (Equation 48) where the Fresnel term is computed using Schlick’s approximation (Equation 16). To be noted that CSun already includes the Fresnel term in its computation. C=CSun +F(θi)Cenv + (1−F(θi))Ctrans (48) An overview of the full color computation is presented in Algorithm 5, which is implemented in a fragment shader. All calculations are done in world space, with the appropriate conversions to texture space performed when needed. Only the inner domain is considered when accessing simulation data textures. A normal map can also be applied to the water surface, which is discussed in Section 4.4. Algorithm 5: Water surface shading Input: eye, normal, light normal ←applyNormalMap(normal) re f lectDir ←re f lect(eye,normal) hit ←intersectTerrain(re f lectDir) if hit then Cbottom,tNormal ←Sample terrain color and normal from textures Cenv ←di f f use(Cbottom,tNormal) else Cenv ←Sample environment map color from texture end re f ractDir ←re f ract(eye,normal) hit,pathLength ←intersectTerrain(re f ractDir) if hit then Cbottom,tNormal ←Sample terrain color and normal from textures Cre f r ←di f f use(Cbottom,tNormal) causticsIntensity,causticsPathLength ←Sample caustics data from textures Cre f r ←Cre f r ×causticsIntensity pathLength ←pathLength +causticsPathLength else Cre f r ←Sample environment map color from texture end fresnel ←f resnelSchlick(eye,normal) Csun ←cookTorranceSpecular(normal,eye,lightDir)×normal ·lightDir Cenv ←Cenv ×fresnel ×normal ·lightDir Ctrans ←(1−fresnel)×Cre f r ×(transmittance(pathLength) + Cscatter) return Csun +Cenv +Ctrans
4.3. Caustics 61 and areau(i,j)and areal(i,j)are functions that read from GSM the area of the upper and lower associated triangles of vertex (i,j). The use of GSM is further explained below. a1=areau(i−1, j) a2=areal(i−1, j) a3=areau(i,j) a5=areal(i−1, j−1) a5=areau(i,j−1) a6=areal(i,j−1) at=a1+a2+a3+a4+a5+a6 (54) Figure 35: Neighborhood of triangles around vertex (2, 2) on a 4×4caustics grid. Simulation overview An overview of the steps of the caustics simulation is provided in Figure 36. Starting at step (1), the intersection point of the refracted ray with the bottom terrain is estimated. At step (2), the vertex’s associated triangles areas and intensities are computed. Step (3)takes the previously computed results of the vertex’s triangle neighborhood, and adds them. Finally at step (4), a ratio of the neighborhood sums is computed by dividing the pre-refraction area by the post-refraction area, resulting in the final caustics intensity. Both the hit point position computed at step (1)and the caustics intensity at step (4)are stored in a buffer to be later used to render the caustics map.
4.3. Caustics 62 Figure 36: Steps of the caustics simulation performed at each thread. During this compute shader pass, GSM is used to avoid doing redundant processing and texture accesses. The initial vertex height (1 float) and hit point position (3 floats) are stored in GSM so they can be later accessed for area calculations. Then, pre- and post-refraction triangle areas are also stored in GSM for triangle neighborhood accesses (4 floats in total). As only 4 floats need to be stored at the same time, a single GSM vec4 array is used. An overview of the caustics simulation process where the order of execution and use of GSM can be seen is in Algorithm 7. Memory barriers with thread synchronizations are denoted as barrier and used between reads
4.3. Caustics 63 and writes in the GSM to guarantee a correct order of execution. The input resources to this pass are the heights and normals texture, bathymetry texture and normal map. Algorithm 7: Caustics simulation // Compute and sample initial data Compute global indices (Equation 35). Sample height and normal from simulation data texture. Sample and apply normal map to perturb normal. Compute new grid spacing and vertex position waterPos (Equation 49 and Equation 50). // Find hit point re f ractDir ←normalize(refract(lightDir,normal,eta)) Estimate intersection point (hitPoint) with receiver using waterPos,re f ractDir and bathymetry texture (Algorithm 6). pathLength ←distance(waterPos,hitPoint) Store height and hitPoint in GSM. barrier // Compute associated triangle areas and intensities Read heights and hitPoints of vertices in associated triangles from GSM. Compute normals for pre- and post-refraction associated triangles using heights and hitPoints. Compute triangle areas and intensities for the required triangles using their normals (Equation 53). barrier Store triangle areas in GSM. barrier // Read and sum values from triangle neighborhood (Equation 54) Read vertex triangle neighborhood intensities from GSM,preAreas and posAreas for pre- and post-refraction areas respectively. totalPre ←∑x∈preAreas x totalPos ←∑x∈posAreas x intensity ←totalPre totalPos // Write results to buffer if this vertex is in inner local and global domains (Equation 36)then Write intensity,pathLength and hitPoint x and zcomponents to buffer. 4.3.2 Rendering caustics map The previous pass filled the caustics vertex buffer with the positions and intensity data, which will now be used to render the caustics map texture. There are two main rendering methods: splatting based (Shah et al.,2007) and triangle based (Ernst et al., 2005). Both methods output a caustics map texture that is then projected onto the caustics receiver. Parna
4.3. Caustics 64 (2020) compared the methods, suggesting the use of caustics triangle rendering as it provided significantly sharper results while also being slightly faster to render and not requiring additional parameter tuning. As such, it is the method implemented in this work. The caustics map texture is obtained by rendering the triangles of the caustics grid and using the fragment shader to smoothly interpolate the vertex intensities across the rasterized pixels. Since triangles can end up overlapping or have a reversed winding order due to refraction (Figure 37), the rendering pass is performed with both culling and depth-testing disabled and additive blending enabled. Figure 37: Example scenario that leads to overlapping triangles and reversed winding order (highlighted in red). The path length requires different blending, so an additional texture is rendered in the same way, but using the path length as the color and minimum blending instead of additive. Parna (2020) rendered the caustics map from camera’s view which required an additional pass to render the depth so it can be later used to avoid incorrect caustics when the viewing ray crosses the caustics mesh more than once. As in this work only heightfields are to be rendered underwater, a top-down camera was chosen instead, therefore guaranteeing that the mesh is intersected only once and avoiding the previously described problem. Additionally, only the xand zcoordinates of the hit point are needed in the caustics buffer and the projection of the caustics map to the receiver is trivial. 4.3.3 Applying the caustics map When rendering the water surface, the intersection point between the viewing ray and the bottom terrain is computed (Section 4.2.2). The xand zcoordinates of this point are converted to texture space and used to access the caustics map and path length textures. The intensity modifier sampled from the caustics map texture is then multiplied by the refracted color which is used in the remainder color computations. The path length replaces the approximate path length when computing the transmittance as described in the previous section.
4.3. Caustics 65 4.3.4 Algorithm overview An high level overview of the rendering pipeline is provided in Figure 38. Since the algorithm runs entirely on the GPU, it is presented in terms of render passes performed. Figure 38: Overview of the caustics algorithm. Render passes are represented by gray boxes, and the resources used and produced by these passes are represented as orange (buffers) and blue (textures/images) boxes. The texture’s colors are scaled for better visualization. 4.3.5 Results Some example scenarios with caustics are provided in Figure 39 and Figure 40. In both examples the caustics distinctive brighter zones are clearly visible due to the convergence of light rays.
4.3. Caustics 66 Figure 39: Caustics created by multiple waves on the water surface. Figure 40: Caustics created by a normal map (Section 4.4) applied on a flat water surface pierced by the bottom terrain. A limitation of the method used is that only light incoming from the water surface is considered, as if the scene was contained inside a box, which produces shadows near the borders (Figure 41). This could be fixed by simply extending the caustics generating grid to outside the domain of the simulation as necessary.
4.4. Small Scale Details 67 Figure 41: Shadowed borders produced by the caustics algorithm, since it only considers incoming light from the water surface. 4.4 SMALL SCALE DETAILS A procedurally generated normal map is used to provide higher frequency details for surface rendering. Procedural noise functions are widely used in Computer Graphics (Lagae et al.,2010) and for a diverse range of purposes including varied natural scenery, water being one of them. This section explores the use of Perlin and cellular noise as a way of adding detail to the water surface and the caustics it produces. Although only a 2D texture is needed to generate the normal map, the 3D version of the noise functions are used to animate the texture. By fixing two coordinates and moving through the other one (simulating time), as if a plane was slicing a 3D volume, a smooth animation can be achieved. 4.4.1 Perlin Noise Perlin noise (Perlin,2002) is probably the most famous noise algorithm and is commonly used to generate patterns and shapes found in nature. It is an implementation of gradient noise, which consists in the creation of a lattice of random gradients at integer locations, interpolated to obtain values between the lattices. The version used here is Perlin simplex noise, an improved version of classic Perlin noise (Perlin,2002), but will be referred to simply as Perlin noise. The GLSL implementation presented in Gustavson and McEwan (2022) is used for the noise generating function. The normal map is obtained from the analytical derivatives of the noise function.
4.4. Small Scale Details 68 Figure 42: Perlin noise, height map values on the left, normal map on the right. 4.4.2 Cellular Noise Cellular noise, also known as Worley noise (Worley,1996), was explored with the goal of producing more convincing and diversified caustics patterns. Cellular Noise is based on distance fields, more specifically, of the distance to the closest point in a set of feature points. The space is subdivided into tiles, each one containing a feature point in a random position. At each pixel, the distance between the point in their own tile and the points in the surrounding tiles is checked and the shorter distance is stored. The result is a distance field as in Figure 43. The open source GLSL implementation in Gustavson (2021) is used for the noise generating function. The normal map is computed from the noise in an additional pass, using a finite difference approximation of the derivatives. Figure 43: Cellular noise, height map values on the left, normal map on the right. 4.4.3 Fractal Brownian Motion To obtain a finer granularity in the noise and get more fine detail, a technique called fractal Brownian motion (fBm) can be used (Vivo and Lowe,2021), also referred to simply as fractal noise. This consists in adding different iterations of noise (octaves), where the frequencies are successively incremented in regular steps (lacunarity) and the amplitude decreased (gain). The derivatives/gradient are accumulated in the same way as the noise,
4.4. Small Scale Details 69 added and multiplied by the amplitude at each iteration. A fractal noise function is provided in Algorithm 8, and example generated textures in Figure 44. Algorithm 8: fBm function Input: 2D coordinates p frequency ←1 amplitude ←1 total ←0 for i←0; i<octaves;i←i+1do total ←total +amplitude ×noise(frequency ×p) frequency ←frequency ×lacunarity amplitude ←amplitude ×gain end return total Figure 44: Perlin (left) and cellular (right) 3 octaves fractal noise normal maps. 4.4.4 Domain Warping With cellular noise, the edges of the cells create sharp peaks and lead to the typical cell shaped caustics. However, the cell’s straight lines give it a unnatural appearance which needs further tweaking. Domain warping can be used to add some distortion to the generated noise. With a image defined as a function of space, as is the case of the noise function used so far, warping simply means distorting the domain with another function, i.e, replacing f(p)with f(g(p)). As the goal is only to slightly distort the image, the domain warping function g(p)can be defined as a small arbitrary distortion h(p), or in other words, g(p) = p+h(p). The final noise function will therefore be computed as f(p+h(p)), where h(p)can be another noise function (example of use in Algorithm 9). The final noise is generated using a cellular noise fractal sum and an additional Perlin noise fractal sum used for domain warping. Examples of generated noise using this configuration are presented in Figure 45.
4.4. Small Scale Details 70 Figure 45: Cellular fractal noise normal maps, on the right with domain warping, and on the left without. Algorithm 9: Noise function using fractal sums and domain warping Input: 2D coordinates p q=f Bm(p) return f Bm(p+0.1 ×(q,q)) 4.4.5 Using the normal map When rendering the water surface, the normal map is applied as usual by distorting the water surface normals. When the generated normal map is accessed it can also optionally be stretched and slid over the surface over time to simulate small wind waves. Examples of scenes with noise generated normal maps can be seen in Figure 46,Figure 47 and Figure 48. The first example has clear water and clearly visible caustics patterns. In this case only a small number of octaves are used, but domain warping is required in order to distort the straight lines of cellular noise. The second example has turbid water where the bottom terrain barely contributes to the water’s color and the sun’s specular highlights are visible. Here 4 octaves are used as the finer detail results in the distinct sparkling look created by the water’s specular reflections. The final example shows small directional waves, resulting from stretching the normal map in one direction. In this example the normal map would also be slid over the surface over time, in the direction perpendicular to which it was stretched.
5.1. Overview 77 Figure 51: Frame time breakdown of the full application for different grid sizes, and resolution 1920x1080 . Both axes are scaled logarithmically. Values in Table 1. Figure 52: Rendering time for different resolutions, and grid size 1024x1024 . The time is also displayed without the caustics and noise passes, that is, only the water surface and sides drawing passes. Both axes are scaled logarithmically. Values in Table 1. As seen on Figure 51, frame time scales linearly with the grid size. The rendering time also scales linearly with the resolution when considering only the surface and and sides rendering passes (Figure 52), since in these examples the caustics and noise texture sizes were defined based on the grid size, and therefore are equal for all resolutions.
5.2. Shallow Water Equations solver 78 Figure 53: Frame breakdown with all components for some combinations of resolution and grid size. Values in Table 1. Rendering takes the bulk of computation time, this difference being accentuated when a small grid size is used with a larger resolution, e.g, in Figure 53 comparing the two middle examples. However, the examples given had only one solver step per frame, while due to stability restrictions more can be required, an option that is reviewed at Section 5.2.1. From within the different rendering components, drawing the water surface takes the most time. Even when the texture resolution used for caustics and noise is larger than the final rendering resolution, rendering the water surface takes more than half of the rendering time (second example from the right in Figure 53), with noise generation taking the least. 5.2 SHALLOW WATER EQUATIO N S S O LV E R This section presents a review of the SWE solver for different scenarios. Initially, the impact of the grid and cells size is evaluated for different scenarios, providing a visual showcase of the water behavior modeled by the solver. Then, different possible work group configurations for the compute shader are evaluated. Finally, the option of adjusting the solver for fully water covered scenes is analyzed. 5.2.1 Grid and cell size comparison The simulation has two main parameters that define the physical domain it models, the grid size and the cell size. While keeping the total physical dimension constant, increasing the grid size and reducing the cell size will increase the simulations detail level, while doing the opposite decreases the detail level. For a scene with the same physical dimensions and initial conditions, several combinations of grid and cell sizes are tested with rendered results shown in Figure 54.
5.2. Shallow Water Equations solver 79 Figure 54: Scenes with the same physical dimensions ( ≈200m ) but different combinations of grid and cell sizes. From top to bottom the scenes have increasingly smaller cells and larger grids. As seen in Figure 54, lowering the cell size and increasing the grid size accordingly leads to a more detailed simulation, with sharper features and more complex waves and caustics patterns. As all cells are treated the same in the solver, and as confirmed during testing, the state of the scene (e.g., the wet to dry cell ratio) has no impact in the performance of the solver. That leaves the size of the simulated grid as the performance defining parameter. Increasing the detail level implies increasing the grid size, which will in consequence affect performance. However, due to stability requirements (Section 3.2.1), more than one solver step can be required per frame since there is a limit on the timestep size. Stability will mostly depend on the velocity of the water flow, and on the dimension of the cells relative to that velocity: the smaller the cell size, or the higher the velocities are, the smaller the maximum timestep allowed will be. So for a certain grid size, reducing the cell size might require additional solver steps in order to ensure stability. For a grid size of 1024x1024, the same scenario was tested with different cell sizes, and consequently, different total physical domains. The timings for the tested scenesas well as the maximum timesteps (determined
5.2. Shallow Water Equations solver 80 as to ensure stability in the simulation) and number of solver steps are provided in Table 2. The maximum timestep (Max Delta t) was determined through trial and error as the lowest value that would allow for a stable simulation. Cell size (m) 0.4 x 0.4 0.2 x 0.2 0.1 x 0.1 Max ∆t (ms) 20 10 5 Solver steps per frame 1 2 4 Render time (ms) 9.09 10.59 11.95 Solver time (ms) 1.25 2.49 4.98 Total (ms) 10.34 13.98 16.93 Table 2: Data about scenes with grid size 1024x1024, resolution 1920x1080 and varying cell size. As seen in Table 2, decreasing the cell’s size to a quarter resulted in requiring to halve the maximum timestep in order to ensure stability. This leads to more solver steps being needed per frame, increasing its contribution to frame time in relation to rendering. Similarly, increasing the velocities in the scene, for example by increasing the water depth which causes the waves to travel faster, will lead to more strict stability requirements, in the form of a lower maximum timestep. Two scenarios with the same parameters but different water depths were tested, with the results shown in Table 3. The scenes tested are depicted in Figure 55. Figure 55: Scenes with different starting conditions but all other parameters equal. The scene on the right (B) has a higher average depth which results in faster waves.
5.2. Shallow Water Equations solver 81 Scene A B Max ∆t (ms) 10 7 Solver steps per frame 2 3 Render time (ms) 10.76 11.31 Solver time (ms) 2.49 3.75 Total (ms) 13.25 15.06 Table 3: Data about the scenes depicted in Figure 55, with grid size 1024x1024 , resolution 1920x1080 and cell size 0.2x0.2. As seen in Table 3, a lower maximum timestep required to ensure stability will lead to a larger number of solver steps per frame. Although depending on several different parameters, the simulation proved viable (when aiming for around 60 frames per second, or 0.017 ms per frame) for the examples provided for a resolution of 1920x1080, grid of size 1024x1024 and cell size 0.2x0.2m, which accounts for a total physical domain of ≈200m(Table 2,Table 3). Covering larger domains can be achieved by increasing the cells’ size, having the drawback of lower detail. For scenes with higher rendering or stability requirements, other parameters would have to be adjusted accordingly, such as lowering the grid resolution or increasing the cells’ size. 5.2.2 Limitations A limitation of the heightfield representation is that when creating a larger/faster wave, if the wave were to break, an unnatural wall-like wave is formed instead. An example of this is shown in Figure 56. Figure 56: Several frames of a wave in a simulation, advancing from left to right. Shallow waters can not model breaking waves, so instead a unnatural wall-like wave can be formed. 5.2.3 Computation work group sizes As there are various different conflicting optimization parameters, which make finding the optimal work group size a difficult task (Brodtkorb et al.,2012), a set of different possible configurations is tested. Still, there are some aspects that can be considered. Firstly, there are some restrictions set by OpenGL, namely, for each work group there is a maximum number of threads of 1536, and a maximum size of the shared memory of 49152 Bytes.
5.2. Shallow Water Equations solver 82 The compute kernel uses 10 floats per thread, therefore requiring 40 bytes in total. Considering the limit of 49152B, a maximum number of threads per work group of 49152/40 ≈1229 would be expected. However, when compiling the shader, the shared memory limit was reached at a lower value of 928 threads, possibly due to how OpenGL internally handles the memory. Another aspect to consider is that having a bigger and square work group maximizes the ratio of internal valid cells to boundary cells (see Figure 14). Finally, since the warp size is 32, it is a common practice to keep the number of threads to an integer multiple of it (Brodtkorb et al.,2012). During testing, only the configurations with either 16 or 32 threads on the xdimension produced correct results, possibly due to synchronization issues. Due to the shared memory limit, that makes the maximum work group sizes to be 32x29 or 16x58. Considering these guidelines and restrictions, a variety of possible thread configurations were tested. A selection of the computation times of these configurations are shown in Table 4 and Figure 57. More configurations than those shown were tested, which followed a similar distribution to the one presented in Figure 57. Smaller groups than those shown had increasingly worse results. Threads (XxY) 16x16 16x20 16x24 16x28 16x32 16x36 16x40 16x44 16x48 Timings (ms) 0.54 0.44 0.40 0.42 0.38 0.38 0.37 0.46 0.46 Threads (XxY) 32x12 32x14 32x16 32x18 32x20 32x22 32x24 32x26 32x28 Timings (ms) 052 0.45 0.39 0.36 0.33 0.42 0.41 0.38 0.38 Table 4: Performance of the SWE solver with different work group thread configurations. Simulation grid size is 512x512. Figure 57: Performance of the SWE solver with different work group thread configurations. Values in Table 4. As expected, the smallest configurations had the worst results, probably due to the low ratio of inner to boundary cells, which then requires more groups to be dispatched to cover the whole domain. However, increasing the size of the group only yields better results up until a certain point, with the largest groups having worse results. The best configuration can be seen as a "dip" in both charts (Figure 57), which corresponds to a size of 640 =32x20 =16x40 threads. Within this size, the configuration of 32x20 had the best results, so it is used for all other tests.
5.3. Water rendering 83 5.2.4 Wet only solver Since the solver has specific computations to handle wetting/drying processes (Section 3.1.4), an alternative version of the solver without these computation was also tested, which will be referred to as the wet only solver. This solver could be used in scenes where it is guaranteed that every cell is covered in water, as a way to improve performance. The computation times for both solvers are presented in Table 5 for varying grid sizes. Grid size 128 x 128 256 x 256 512 x 512 1024 x 1024 2048 x 2048 Standard 0.03 0.09 0.33 1.33 5.42 Wet only 0.03 0.11 0.26 1.26 5.29 Table 5: Performance of the SWE solver with different grid sizes and solvers, timings in milliseconds. The wet only solver has no computations for handling wetting/drying processes. The wet only solver provides a slight increase in performance which can justify its use in scenes that allow it. Still, since the solver usually amounts for a small part of total computation time, it may only be noticeable in scenes that rely on multiple solver passes. 5.3 WATER RENDERING This section presents a more in-depth review of some parameters and options of the rendering components, as well as additional performance benchmarks. 5.3.1 Terrain intersection As part of the water color computations, when determining the intersection of the refracted/reflected viewing ray with the terrain, a heightfield intersection algorithm is used. This algorithm is tested with bathymetries of varying steepness and its computation times are shown in Table 6. The scenes tested and heatmaps of the number of iterations required for intersection are provided in Figure 58. Bathymetry type A B C Timings (ms) 2.95 2.30 1.99 Table 6: Rendering timings for different bathymetries of varied steepness (shown in Figure 58). Only the water surface and sides passes are considered. Grid size is 512x512 and resolution is 960x540.
5.3. Water rendering 84 Figure 58: Scenes with different bathymetries of decreasing steepness from left to right. The bottom row depicts a heatmap of iterations of the intersection algorithm, corresponding to the scenes in the top row. Timings in Table 6. As seen in Table 6 and Figure 58, the number of iterations required o intersect the terrain depends on its steepness, with steeper terrain requiring more iterations. This is due to the high variation in heights of the steep terrain causing the ray to descend levels too quickly, which then requires more iterations to advance through the lower levels (as seen in the red hotspots in Figure 58). On the other hand, on flatter terrain, the ray is more likely to only descend levels when actually getting near the intersection point. 5.3.2 Caustics The caustics generation step (yellow outline in Figure 49) consists of three passes, the first one being a compute shader that creates a vertex buffer filled with the caustics data. Then, there are two rendering passes that utilize the generated vertex buffer to create textures, one drawing the caustics intensity values, and the other drawing the incident light path length. Performance results for the caustics map generation with varying grid sizes are given in Table 7 and Figure 59, and with varying resolutions in Table 8. Both rendering passes have similar performance so a single value is displayed for both. The total includes the three passes, namely the initial compute pass and the following two rendering passes.
5.3. Water rendering 85 Caustics grid size 256 x 256 512 x 512 1024 x 1024 2048 x 2048 Computer vertex buffer 0.07 0.16 0.52 1.97 Render textures 0.26 0.38 1.44 6.80 Total 0.33 0.54 1.96 8.77 Table 7: Performance of the various caustics simulation passes with different caustics grid sizes. Caustics textures resolution is 1024x1024 and timings are in milliseconds. The total accounts for a complete step, which includes the compute pass and two render passes. Figure 59: Performance of the various caustics simulation passes with different caustics grid sizes. Both axes are scaled logarithmically. Values in Table 7. The total accounts for a complete step, which includes the compute pass and two render passes. Grid size Resolution 256 x 256 512 x 512 1024 x 1024 2048 x 2048 4096 x 4096 256 x 256 0.05 0.05 0.08 0.28 0.98 512 x 512 0.20 0.18 0.18 0.52 1.17 1024 x 1024 0.88 0.86 0.72 0.76 1.47 2048 x 2048 3.58 3.54 3.40 2.90 3.03 Table 8: Performance of a caustics rendering pass with different resolutions. The grid size refers to the caustics grid and the resolution to the generated caustics textures. As shown in Table 7 and Figure 59, the bulk of the computation time is spent drawing the caustics textures and not computing the vertex buffer that they are drawn from. Since computing the path length for the attenuation is only useful in certain scenes, it can be omitted to improve performance. Reducing the resolution to below the
5.3. Water rendering 86 grid size resulted in similar or worse timings, as shown in Table 8, so this should be avoided (considerably worse results are also produced, as later seen in Section 5.3.2). Caustics work group size Similarly to the SWE solver (Section 5.2.3), the caustics simulation is tested with various work group sizes. Since the compute kernel uses only 4 floats per thread (16 bytes) of shared memory, a maximum number of threads per work group of 49152/16 ≈3072 would be expected to reach the limit. The upper bound for work group size is instead set by the maximum number of threads, 1536. A selection of computation times of this pass with some different possible work group configurations are presented in Table 9 and Figure 60, with a caustics grid of size 1024x1024. Threads (XxY) 4x4 8x8 12x12 16x16 20x20 24x24 28x28 32x32 36x36 Timings (ms) 1.90 0.93 0.52 0.72 0.52 0.77 0.58 0.87 0.62 Table 9: Performance of the caustics simulation pass with different work group thread configurations. Caustics grid size is 1024x1024. Figure 60: Performance of the caustics vertex buffer compute pass with different work group thread configurations. Values in Table 9. Similarly to the results obtained in Section 5.2.3, a trend can be seen where the smallest sized groups performed the worst, but increasing the size will only provide improved results up until a certain point, where a "dip" in the chart can be seen (Figure 60). The major difference here is that further increasing the group’s size results in an oscillating increase in the timings rather than a steady one. Looking at the previously mentioned "dip", one of the work group configurations that yielded the best results is 12x12, and therefore, was used for all other tests.
6 CONCLUSIONS AND FUTURE WORK The domain of application for fluid simulation is vast, and there are numerous specializations based on the requirements. When the goal is water simulation on real-time applications, certain aspects have to be ignored in order to meet the performance constraints. Shallow water simulations are a commonly used approximation for applications with real-time requirements as they allow for both faster simulation and rendering. A framework for water simulation in real-time using the SWE and a heightfield surface representation was presented in this work. The water’s behavior was simulated by using an Eulerian SWE solver which computes a grid of values at each frame in an efficient GPU implementation. The grid generated by the simulation is then used to render a mesh of the water surface. The color of the water surface is determined by a combination of reflected and transmitted light, using a physically based BRDF to describe the Sun’s reflection. The terrain’s contribution is obtained by intersecting a reflected and a refracted ray. Transmitted light also takes into consideration the water’s attenuation and simplified scattering. This result is then enhanced by a separate pass which generates caustics and improves the attenuation computations. Finally, small-scale details were added to the surface as a normal map to account for the limit in resolution and scope of the simulation, as well as aiding in creating interesting caustics patterns. The developed application was tested and performance benchmarks as well as insights into some parameters and options were provided. The resulting simulation accurately captures the intended shallow water wave behaviors and interaction with terrain, and its rendering provides the essential identifiable features of a water surface. The full system was shown to be able to achieve a desirable 60 frames per second on consumer hardware. 6.1 FUTURE WOR K There are several areas where the developed work can be improved, either by addressing the existing limitations, adding new functionality or simply improving on the various components. A few options are proposed here. Starting with the inherent limitations of shallow water simulations, since the surface is represented by an heightfield, behavior such as breaking waves, splashing and waterfalls can not be modeled. To address this, the system could be combined with a particle system (e.g., Ojeda and Susín (2014)) or volumetric techniques (e.g., Parna (2020)). Similarly, in order to support a larger area and deep ocean regions where the water is no longer "shallow", the system could be combined with a procedural simulation. 93
6.1. Future work 94 Another approach could be to add rigid-body coupling, to add a higher degree of interactivity with the scene. When considering the simulation, since dry regions are treated just as wet regions (Section 5.2.1), a clear option would be to have a sparse simulation where dry regions are not computed. Another option would be to explore other methods of simulation, some mentioned in Section 2.4, such as LBM and 2D SPH, and do a comparison in the context of computer graphics as this appears to be lacking recent data. As for rendering, since hardware supported ray-tracing is getting increasingly better and widespread, it would make sense to explore a ray-tracing solution for reflections, refractions and caustics generation. One more option would be to explore underwater visualization, which also pairs well with an improvement of the scattering computations, including the addition of volumetric caustics.
BIBLIOGRAPHY Tomas Akenine-Mller, Eric Haines, and Naty Hoffman. Real-Time Rendering, Fourth Edition. A. K. Peters, Ltd., USA, 4th edition, 2018. ISBN 0134997832. R. Angst, N. Thürey, M. Botsch, and M. Gross. Robust and efficient wave simulations on deforming meshes. Computer Graphics Forum, 27, 2008. D. Arumuga Perumal and Anoop K. Dass. A review on the development of lattice boltzmann computation of macro fluid flows and heat transfer. Alexandria Engineering Journal, 54(4):955–971, 2015. ISSN 1110- 0168. doi: https://doi.org/10.1016/j.aej.2015.07.015 . URL http://www.sciencedirect.com/ science/article/pii/S1110016815001362. Jean-Pierre Berenger. A perfectly matched layer for the absorption of electromagnetic waves. Journal of Computational Physics, 114(2):185–200, 1994. ISSN 0021-9991. doi: https://doi.org/10.1006/ jcph.1994.1159. URL http://www.sciencedirect.com/science/article/pii/ S0021999184711594. Robert Bridson. Fluid simulation for computer graphics. A K Peters/CRC Press, 2nd edition, 2015. ISBN 9781351968843. André R. Brodtkorb, Martin L. Sætra, and Mustafa Altinakar. Efficient shallow water simulations on gpus: Implementation, visualization, verification, and validation. Computers & Fluids, 55:1–12, 2012. ISSN 0045-7930. doi: https://doi.org/10.1016/j.compfluid.2011.10.012. Eric Bruneton, Fabrice Neyret, Nicolas Holzschuch, Eric Bruneton, Fabrice Neyret, Nicolas Holzschuch, Real time Realistic, Ocean Lighting, Hal Id Inria, Eric Bruneton, Fabrice Neyret, and Nicolas Holzschuch. Realtime realistic ocean lighting using seamless transitions from geometry to brdf. Comput. Graph. Forum, pages 487–496, 2010. Brent Burley. Physically based shading at disney. In ACM SIGGRAPH 2012 Courses, 2012. J. C. Butcher. The Numerical Analysis of Ordinary Differential Equations: Runge-Kutta and General Linear Methods. Wiley-Interscience, USA, 1987. ISBN 0471910465. Nuttapong Chentanez and Matthias Mueller. Real-time Simulation of Large Bodies of Water with Small Scale Details. In MZoran Popovic and Miguel Otaduy, editors, Eurographics/ ACM SIGGRAPH Symposium on Computer Animation. The Eurographics Association, 2010. ISBN 978-3-905674-27-9. doi: 10.2312/SCA/ SCA10/197-206. 95
BIBLIOGRAPHY 96 Wang Chi-Shu. Essentially non-oscillatory and weighted essentially non-oscillatory schemes for hyperbolic conservation laws. Technical report, Institute for Computer Applications in Science and Engineering (ICASE), 1997. Michal Chladek and Roman Durikovic. Particle-based shallow water simulation for irregular and sparse simulation domains. Computers & Graphics, 53:170–176, 2015. ISSN 0097-8493. doi: https://doi.org/10.1016/j.cag. 2015.04.002. Andrew J. Christlieb, Yaman Güçlü, and David C. Seal. The picard integral formulation of weighted essentially nonoscillatory schemes. SIAM Journal on Numerical Analysis, 53(4):1833–1856, 2015. doi: 10.1137/140959936. R. L. Cook and K. E. Torrance. A reflectance model for computer graphics. ACM Trans. Graph., 1(1):7–24, jan 1982. ISSN 0730-0301. doi: 10.1145/357290.357293. R. Courant, K. Friedrichs, and H. Lewy. Über die partiellen differenzengleichungen der mathematischen physik. Mathematische Annalen, 100(1):32–74, Dec 1928. ISSN 1432-1807. doi: 10.1007/BF01448839. URL https://doi.org/10.1007/BF01448839. Keenan Crane, Ignacio Llamas, and Sarah Tariq. Real Time Simulation and Rendering of 3D Fluids, chapter 30. Addison-Wesley, 2007. I. Cravero and M. Semplice. On the accuracy of weno and cweno reconstructions of third order on nonuniform meshes. Journal of Scientific Computing, 67(3):1219–1246, Jun 2016. ISSN 1573-7691. doi: 10.1007/ s10915-015-0123-3. URL https://doi.org/10.1007/s10915-015-0123-3. F. Dagenais, J. Guzmán, V. Vervondel, A. Hay, S. Delorme, D. Mould, and E. Paquette. Real-time virtual pipes simulation and modeling for small-scale shallow water. In Proceedings of the 14th Workshop on Virtual Reality Interactions and Physical Simulations, VRIPHYS ’18, page 45–54, Goslar, DEU, 2018. Eurographics Association. Christian Dick, Jens Krüger, and Rüdiger Westermann. GPU Ray-Casting for Scalable Terrain Rendering. In D. Ebert and J. Krüger, editors, Eurographics 2009 - Areas Papers. The Eurographics Association, 2009. doi: 10.2312/ega.20091007. Michał Drobot. Quadtree Displacement Mapping with Height Blending, chapter 1. Taylor & Francis, 2018. B. Düz, M.J.A. Borsboom, A.E.P. Veldman, P.R. Wellens, and R.H.M. Huijsmans. An absorbing boundary condition for free surface water waves. Computers & Fluids, 156:562–578, 2017. ISSN 0045-7930. doi: https://doi.org/10.1016/j.compfluid.2017.05.018. URL https://www.sciencedirect.com/ science/article/pii/S0045793017301871. Ninth International Conference on Computational Fluid Dynamics (ICCFD9).
BIBLIOGRAPHY 97 Manfred Ernst, Tomas Akenine-Möller, and Henrik Wann Jensen. Interactive rendering of caustics using interpolated warped volumes. In Proceedings of Graphics Interface 2005, GI ’05, page 87–96, Waterloo, CAN, 2005. Canadian Human-Computer Communications Society. ISBN 1568812655. Nick Foster and Dimitris Metaxas. Realistic animation of liquids. CVGIP: Graphical Model and Image Processing, 58:471–483, 01 1996. Makoto Fujisawa, Takuya Nakada, and Masahiko Mikawa. Particle-based shallow water simulation with splashes and breaking waves. Journal of Information Processing, 25:486–493, 07 2017. doi: 10.2197/ipsjjip.25.486. Cristian García Bauza, Juan D’Amato, Gustavo Boroni, Marcelo Vénere, and Alejandro Clausse. Real-time interactive animations of liquid surfaces with lattice-boltzmann engines. Australian Journal of Basic and Applied Sciences, 08 2010. Holger Gruen. Ray-Guided Volumetric Water Caustics in Single Scattering Media with DXR, pages 183–201. Apress, Berkeley, CA, 2019. ISBN 978-1-4842-4427-2. doi: 10.1007/978-1-4842-4427-2_14. URL https://doi.org/10.1007/978-1-4842-4427-2_14. Branislav Grujic and Cristian Cutocheras. Water Rendering in FarCry 5. https://www.gdcvault. com/play/1025555/Advanced-Graphics-Techniques-Tutorial-Water, 2018. [Online; accessed 28-June-2022]. Juan Guardado and Daniel Sanchez-Crespo. Rendering water caustics, chapter 2. Addison-Wesley, 2007. Stefan Gustavson. Noise for glsl 1.20. https://github.com/stegu/webgl-noise, 2021. [Online; accessed 28-June-2022]. Stefan Gustavson and Ian McEwan. Tiling simplex noise and flow noise in two and three dimensions. Journal of Computer Graphics Techniques (JCGT), 11(1):17–33, February 2022. ISSN 2331-7418. URL http: //jcgt.org/published/0011/01/02/. Romain Guy and Mathias Agopian. Physically based rendering in filament. https://www. gamedeveloper.com/programming/deep-water-animation-and-rendering, 2019. Eric Heitz. Understanding the masking-shadowing function in microfacet-based brdfs. Journal of Computer Graphics Techniques (JCGT), 3(2):48–107, June 2014. ISSN 2331-7418. URL http://jcgt.org/ published/0003/02/03/. Eric Heitz. Sampling the ggx distribution of visible normals. Journal of Computer Graphics Techniques (JCGT), 7(4):1–13, November 2018. ISSN 2331-7418. URL http://jcgt.org/published/0007/04/ 01/. Naty Hoffman. Background: Physics and math of shading, 2013.
BIBLIOGRAPHY 98 Zsolt Horváth, Andreas Buttinger-Kreuzhuber, Artem Konev, Daniel Cornel, Jürgen Komma, Günter Blöschl, Sebastian Noelle, and Jürgen Waser. Comparison of fast shallow-water schemes on real-world floods. Journal of Hydraulic Engineering, 146(1):05019005, 2020. doi: 10.1061/(ASCE)HY.1943-7900.0001657. Wei Hu and Kaihuai Qin. Interactive approximate rendering of reflections, refractions, and caustics. IEEE Transactions on Visualization and Computer Graphics, 13(1):46–57, 2007. doi: 10.1109/TVCG.2007.14. Stefan Jeschke and Chris Wojtan. Water wave packets. ACM Trans. Graph., 36(4), jul 2017. ISSN 0730-0301. doi: 10.1145/3072959.3073678. URL https://doi.org/10.1145/3072959.3073678. Stefan Jeschke, Tomáš Skˇ rivan, Matthias Müller-Fischer, Nuttapong Chentanez, Miles Macklin, and Chris Wojtan. Water surface wavelets. ACM Trans. Graph., 37(4), jul 2018. ISSN 0730-0301. doi: 10.1145/3197517. 3201336. URL https://doi.org/10.1145/3197517.3201336. Michael Kass and Gavin Miller. Rapid, stable fluid dynamics for computer graphics. SIGGRAPH Comput. Graph., 24(4):49–57, September 1990. ISSN 0097-8930. doi: 10.1145/97880.97884. URL https://doi. org/10.1145/97880.97884. Timo Kellomäki. Large-Scale Water Simulation in Games. PhD thesis, Tampere University of Technology, 2015. Timo Kellomäki. Fast water simulation methods for games. Computers in Entertainment, 16(1), 2017. doi: 10.1145/2700533. URL https://doi.org/10.1145/2700533. Timo Kellomäki and Timo Saari. A User Study: Is the Advection Step in Shallow Water Equations Really Necessary? In Eric Galin and Michael Wand, editors, Eurographics 2014 - Short Papers. The Eurographics Association, 2014. doi: 10.2312/egsh.20141010. Dan Koschier, Jan Bender, Barbara Solenthaler, and Matthias Teschner. Smoothed particle hydrodynamics for physically-based simulation of fluids and solids. In EUROGRAPHICS 2019 Tutorials. Eurographics Association, 2019. Alexander Kurganov and Guergana Petrova. A Second-Order Well-Balanced Positivity Preserving Central- Upwind Scheme for the Saint-Venant System. Communications in Mathematical Sciences, 5(1):133–160, 2007. doi: cms/1175797625. Frédéric Kuznik, Christian Obrecht, Gilles Rusaouen, and Jean-Jacques Roux. Lbm based flow simulation using gpu computing processor. Computers & Mathematics with Applications, 59(7):2380–2392, 2010. ISSN 0898- 1221. doi: https://doi.org/10.1016/j.camwa.2009.08.052. URL https://www.sciencedirect. com/science/article/pii/S0898122109006361. Mesoscopic Methods in Engineering and Science. A. Lagae, S. Lefebvre, R. Cook, T. DeRose, G. Drettakis, D.S. Ebert, J.P. Lewis, K. Perlin, and M. Zwicker. A survey of procedural noise functions. Computer Graphics Forum, 29(8):2579–2600, 2010. doi: https: //doi.org/10.1111/j.1467-8659.2010.01827.x.
BIBLIOGRAPHY 99 Anita Layton and Michiel Panne. A numerically efficient and stable algorithm for animating water waves. The Visual Computer, 18:41–53, 02 2002. doi: 10.1007/s003710100131. Hyokwang Lee and Soonhung Han. Solving the shallow water equations using 2d sph particles for interactive applications. The Visual Computer, 26:865–872, 06 2010. doi: 10.1007/s00371-010-0439-9. Richard Lee and Carol O’Sullivan. A fast and compact solver for the shallow water equations. In Vriphys: Workshop on Virtual Reality Interactions and Physical Simulations, pages 51–57, Postfach 8043, 38621 Goslar, Germany, 2007. The Eurographics Association;. ISBN 978-3-905673-65-4. doi: 10.2312/PE/vriphys/ vriphys07/051-057. Randall J LeVeque et al. Finite volume methods for hyperbolic problems, volume 31. Cambridge university press, 2002. ISBN 9780511791253. Chao Liang and Zhengfu Xu. Parametrized maximum principle preserving flux limiters for high order schemes solving multi-dimensional scalar hyperbolic conservation laws. Journal of Scientific Computing, 58(1):41– 60, Jan 2014. ISSN 1573-7691. doi: 10.1007/s10915-013-9724-x. URL https://doi.org/10. 1007/s10915-013-9724-x. Gabor Liktor and Carsten Dachsbacher. Real-time volumetric caustics with projected light beams. In Fifth Hungarian conference on computer graphics and geometry, 2010. Gábor Liktor and Carsten Dachsbacher. Real-time volume caustics with adaptive beam tracing. In Symposium on Interactive 3D Graphics and Games, I3D ’11, page 47–54, New York, NY, USA, 2011. Association for Computing Machinery. ISBN 9781450305655. doi: 10.1145/1944745.1944753. URL https://doi. org/10.1145/1944745.1944753. Chunyong Ma, Shu Xu, Hongsong Wang, Fenglin Tian, and Ge Chen. A real-time photo-realistic rendering algorithm of ocean color based on bio-optical model. Journal of Ocean University of China, 15(6):996–1006, Dec 2016. ISSN 1993-5021. doi: 10.1007/s11802-016-3037-2. URL https://doi.org/10.1007/ s11802-016-3037-2. Miles Macklin and Matthias Müller. Position based fluids. ACM Trans. Graph., 32(4), jul 2013. ISSN 0730-0301. doi: 10.1145/2461912.2461984. URL https://doi.org/10.1145/2461912.2461984. N Max and B Becker. Flow visualization using moving textures. In ICASEILaRC Symposium on Visualizing Time Vary Data, 1995. Matthias Müller, David Charypar, and Markus Gross. Particle-based fluid simulation for interactive applications. In Proceedings of the 2003 ACM SIGGRAPH/Eurographics Symposium on Computer Animation, SCA ’03, page 154–159, Goslar, DEU, 2003. Eurographics Association. ISBN 1581136595. Matthias Müller, Jos Stam, Doug James, and Nils Thürey. Real time physics: Class notes. In ACM SIGGRAPH 2008 Classes, SIGGRAPH ’08, New York, NY, USA, 2008. Association for Computing Machinery.
BIBLIOGRAPHY 100 ISBN 9781450378451. doi: 10.1145/1401132.1401245. URL https://doi.org/10.1145/ 1401132.1401245. Octavio Navarro-Hinojosa, Sergio Ruiz-Loza, and Moises Alencastre-Miranda. Physically based visual simulation of the lattice boltzmann method on the gpu: a survey. The Journal of Supercomputing, 74, 07 2018. doi: 10.1007/s11227-018-2392-8. Fabrice Neyret. Advected Textures. In D. Breen and M. Lin, editors, ACM SIGGRAPH / Eurographics Symposium on Computer Animation, pages 147–153, San diego, United States, July 2003. Eurographics Association. URL https://hal.inria.fr/inria-00537472. J.F. O’Brien and J.K. Hodgins. Dynamic simulation of splashing fluids. In Proceedings Computer Animation’95, pages 198–205, 1995. doi: 10.1109/CA.1995.393532. J. Ojeda and A. Susín. Enhanced lattice boltzmann shallow waters for real-time fluid simulations. In Eurographics, 2013. Jesus Ojeda and Antonio Susín. Real-time lattice boltzmann shallow waters method for breaking wave simulations. In Sebastiano Battiato, Sabine Coquillart, Robert S. Laramee, Andreas Kerren, and José Braz, editors, Computer Vision, Imaging and Computer Graphics – Theory and Applications, pages 3–18, Berlin, Heidelberg, 2014. Springer Berlin Heidelberg. ISBN 978-3-662-44911-0. Jesús Ojeda Contreras. Efficient algorithms for the realistic simulation of fluids. PhD thesis, Universitat Politècnica de Catalunya, 2013. Charilaos Papadopoulos and Georgios Papaioannou. Realistic real-time underwater caustics and godrays. 19th International Conference on Computer Graphics and Vision, GraphiCon’2009 - Conference Proceedings, 08 2010. P. Parna, K. Meyer, and R. Falconer. Gpu driven finite difference weno scheme for real time solution of the shallow water equations. Computers & Fluids, 161:107–120, 2018. ISSN 0045-7930. doi: https://doi.org/ 10.1016/j.compfluid.2017.11.012. Peeter Parna. Shallow water equations in real-time computer graphics. PhD thesis, Abertay University, 2020. Ken Perlin. Improving noise. ACM Trans. Graph., 21(3):681–682, July 2002. ISSN 0730-0301. doi: 10.1145/ 566654.566636. URL https://doi.org/10.1145/566654.566636. M. Pharr and G. Humphreys. Physically based rendering: from theory to implementation. https://www. pbr-book.org/3ed-2018/contents, 2018. R. Salmon. The lattice boltzmann method as a basis for ocean circulation modeling. Journal of Marine Research, 57:503–535, 1999.
BIBLIOGRAPHY 101 Christophe Schlick. An inexpensive brdf model for physically-based rendering. Computer Graphics Forum, 13 (3):233–246, 1994. doi: https://doi.org/10.1111/1467-8659.1330233. David C. Seal, Qi Tang, Zhengfu Xu, and Andrew J. Christlieb. An explicit high-order single-stage single-step positivity-preserving finite difference weno method for the compressible euler equations. Journal of Scientific Computing, 68(1):171–190, Jul 2016. ISSN 1573-7691. doi: 10.1007/s10915-015-0134-0. URL https: //doi.org/10.1007/s10915-015-0134-0. Andrew Selle, Ronald Fedkiw, ByungMoon Kim, Yingjie Liu, and Jarek Rossignac. An unconditionally stable maccormack method. J. Sci. Comput., 35:350–371, 06 2008. doi: 10.1007/s10915-007-9166-4. Musawir A. Shah, Jaakko Konttinen, and Sumanta Pattanaik. Caustics mapping: An image-space technique for real-time caustics. IEEE Transactions on Visualization and Computer Graphics, 13(2):272–280, 2007. doi: 10.1109/TVCG.2007.32. André Silvestre. A real-time terrain ray-tracing engine. Master’s thesis, Instituto Superior Técnico da Universidade de Lisboa, 2017. Andreas Söderström and Ken Museth. Non-reflective boundary conditions for incompressible free surface fluids. In SIGGRAPH 2009: Talks, SIGGRAPH ’09, New York, NY, USA, 2009. Association for Computing Machinery. ISBN 9781605588346. doi: 10.1145/1597990.1597994. URL https://doi.org/10.1145/ 1597990.1597994. Barbara Solenthaler, Peter Bucher, Nuttapong Chentanez, Matthias Müller, and Markus Gross. SPH Based Shallow Water Simulation. In Jan Bender, Kenny Erleben, and Eric Galin, editors, Workshop in Virtual Reality Interactions and Physical Simulation "VRIPHYS" (2011). The Eurographics Association, 2011. ISBN 978-3- 905673-87-6. doi: 10.2312/PE/vriphys/vriphys11/039-046. Jos Stam. Random caustics: Natural textures and wave theory revisited. In ACM SIGGRAPH 96 Visual Proceedings: The Art and Interdisciplinary Programs of SIGGRAPH ’96, SIGGRAPH ’96, page 150, New York, NY, USA, 1996. Association for Computing Machinery. ISBN 0897917847. doi: 10.1145/253607.253883. URL https://doi.org/10.1145/253607.253883. Jos Stam. Stable fluids. In Proceedings of the 26th Annual Conference on Computer Graphics and Interactive Techniques, SIGGRAPH ’99, page 121–128, USA, 1999. ACM Press/Addison-Wesley Publishing Co. ISBN 0201485605. doi: 10.1145/311535.311548. URL https://doi.org/10.1145/311535. 311548. Jos Stam and Eugene Fiume. Depicting fire and other gaseous phenomena using diffusion processes. In Proceedings of the 22nd Annual Conference on Computer Graphics and Interactive Techniques, SIGGRAPH ’95, page 129–136, New York, NY, USA, 1995. Association for Computing Machinery. ISBN 0897917014. doi: 10.1145/218380.218430. URL https://doi.org/10.1145/218380.218430. Jerry Tessendorf. Simulating ocean water. SIGGRAPH 2001 Course Notes, 2001.
BIBLIOGRAPHY 102 Art Tevs, Ivo Ihrke, and Hans-Peter Seidel. Maximum mipmaps for fast, accurate, and scalable dynamic height field rendering. In Proceedings of the 2008 Symposium on Interactive 3D Graphics and Games, I3D ’08, page 183–190, New York, NY, USA, 2008. Association for Computing Machinery. ISBN 9781595939838. doi: 10.1145/1342250.1342279. URL https://doi.org/10.1145/1342250.1342279. N. Thurey, M. Muller-Fischer, S. Schirm, and M. Gross. Real-time breaking waves for shallow water simulations. In 15th Pacific Conference on Computer Graphics and Applications (PG’07), pages 39–46, 2007. doi: 10. 1109/PG.2007.33. Nils Thürey. Physically based animation of free surface flows with the Lattice Boltzmann method. PhD thesis, University of Erlangen-Nuremberg, 2007. Nils Thürey, Ulrich Rüde, and Carolin Körner. Interactive free surface fluids with the lattice boltzmann method. Technical report, University of Erlangen-Nuremberg, 2005. Eleuterio F. Toro. Some Properties of the Euler Equations, pages 87–114. Springer Berlin Heidelberg, Berlin, Heidelberg, 2009. ISBN 978-3-540-49834-6. doi: 10.1007/b79761_3. URL https://doi.org/10. 1007/b79761_3. Kevin R. Tubbs and Frank T.-C. Tsai. Gpu accelerated lattice boltzmann model for shallow water flow and mass transport. International Journal for Numerical Methods in Engineering, 86(3):316–334, 2011. doi: https://doi.org/10.1002/nme.3066. Patricio Gonzalez Vivo and Jen Lowe. Fractal brownian motion. https://thebookofshaders.com/ 13/, 2021. [Online; accessed 28-June-2022]. Alex Vlachos. Water flow in Portal 2. https://advances.realtimerendering.com/s2010/, 2010. [Online; accessed 28-June-2022]. Bruce Walter, Stephen R. Marschner, Hongsong Li, and Kenneth E. Torrance. Microfacet Models for Refraction through Rough Surfaces. In Jan Kautz and Sumanta Pattanaik, editors, Rendering Techniques. The Eurographics Association, 2007. ISBN 978-3-905673-52-4. doi: 10.2312/EGWR/EGSR07/195-206. Huamin Wang, Gavin Miller, and Greg Turk. Solving general shallow wave equations on surfaces. In Proceedings of the 2007 ACM SIGGRAPH/Eurographics Symposium on Computer Animation, SCA ’07, page 229–238, Goslar, DEU, 2007. Eurographics Association. ISBN 9781595936240. T. Weaver and Z. Xiao. Fluid simulation by the smoothed particle hydrodynamics method: A survey. In Proceedings of the 11th Joint Conference on Computer Vision, Imaging and Computer Graphics Theory and Applications: Volume 1: GRAPP, GRAPP 2016, page 215–225, Setubal, PRT, 2016. SCITEPRESS - Science and Technology Publications, Lda. ISBN 9789897581755. doi: 10.5220/0005673702130223. URL https://doi.org/10.5220/0005673702130223.
109 B.0.3 WENO step A single third order WENO reconstruction step for a value vis described here (as in Parna et al. (2018)). The xdirection is used as an example (jsubscript dropped for simplicity), where the procedure is denoted by the functions WENO3±in Equation 66. The ±superscript denotes which bias the stencil uses. v+ i+1/2 =WENO3+(v+ i−1,j,v+ i,j,v+ i+1,j) v− i+1/2 =WENO3−(v− i,j,v− i+1,j,v− i+2,j)(66) The steps of the procedure are as follows: 1. Find the approximations on two different stencils (Equation 67). f+ 0=1 2v+ i+1 2v+ i+1 f+ 1=−1 2v+ i−1+3 2v+ i f− 0=1 2v− i+1+1 2v− i f− 1=−1 2v− i+2+3 2v− i+1 (67) 2. Find the smoothness indicators (Equation 68). β+ 0= (v+ i+1−v+ i)2 β+ 1= (v+ i−v+ i−1)2 β− 0= (v− i+1−v− i)2 β− 1= (v− i+2−v− i+1)2(68) 3. Find the non-linear weights (Equation 69, where n∈ {0, 1}, and the linear weights are d0=2 3and d1=1 3). ω± n=ζ± n ζ± 0+ζ± 1 ζ± n=dn (e+β± n)2(69) While ewas originally chosen in order to avoid the denominator becoming zero, it has been shown that it actually should relate to the grid-spacing, so it is set as e= (∆x)2(Cravero and Semplice,2016). 4. Find the third order accurate approximation (Equation 70) by combining the two approximations with the non-linear weights. v± i+1/2 =ω± 0f± 0+ω± 1f± 1(70) When applying the WENO reconstruction to the source term derivatives (Section 3.1.3), the first source term derivative, s= (1 2gb2), can simply be absorbed into the computations of the relevant flux to save cost (Xing
110 and Shu,2005), e.g., for direction xas given in Equation 71. Consequently, when computing the final source term SEquation 28, the first term is ignored, as it is already included in the flux. f±←f±−1 2 0 s 0 (71) The second term, b, goes through the usual reconstruction procedure but uses the same smoothness indicators as in the flux reconstruction. That is, for example, after computing the reconstruction of a split flux, ˆ f+, when computing the reconstruction of corresponding ˆ b+, the same smoothness indicators β+are used (Equation 68).
C HIGH AND LOW-ORDER FLUX INTERPOLATION COEFFICIENTS When interpolating the low- and high-order fluxes, the coefficients of the linear combination θi+1/2,jand θi,j+1/2 need to be determined in a way that ensures the interpolation is of the highest order possible, while preserving the positivity of the solution. This is achieved by solving the following optimization problem. Given Λvalues that bound θ(with Λ∈[0, 1]), as in Equation 72, the θparameters are then given by the minimum case of the bounding values (Seal et al.,2016), as in Equation 73. θi−1/2,j∈[0, ΛL] θi+1/2,j∈[0, ΛR] θi,j−1/2 ∈[0, ΛD] θi,j+1/2 ∈[0, ΛU](72) θi+1/2,j=min(ΛR,i,j,ΛL,i+1,j) θi,j+1/2 =min(ΛU,i,j,ΛD,i,j+1)(73) The minimal case method proposed in Parna et al. (2018) is used to determine the bounding values Λ, while ensuring that hn+1 i,j≥0, whose steps are as follows: 1. Determine Γand the Fvalues (Equation 75 and Equation 76). These are defined by applying Equation 30 to the first line of Equation 26, which becomes as in Equation 74 (which is being solved so that hn+1 i,j≥0). hn+1 i,j=−Γi,j+θi+1/2,jFi+1/2,j+θi−1/2,jFi−1/2,j+θi,j+1/2Fi,j+1/2 +θi,j−1/2Fi,j−1/2 (74) Γi,j=−h−∆t ∆x(˜ fi+1/2,j−˜ fi−1/2,j)−∆t ∆y(˜ gi,j+1/2 −˜ gi,j−1/2)(75) 111
112 Fi+1/2,j=−∆t ∆x(ˆ F(1) i+1/2,j−˜ fi+1/2,j) Fi,j+1/2 =−∆t ∆y(ˆ G(1) i,j+1/2 −˜ gi,j+1/2) Fi−1/2,j=∆t ∆x(ˆ F(1) i−1/2,j−˜ fi−1/2,j) Fi,j−1/2 =∆t ∆y(ˆ G(1) i,j−1/2 −˜ gi,j−1/2) (76) 2. Determine Q(Equation 77) and α,β,γ,δ(Equation 781, which are functions of the signs of the values in Equation 76). Q=min Γi,j αFi+1/2,j+βFi−1/2,j+γFi,j+1/2 +δFi,j−1/2 (77) α= 1, if Fi+1/2,j<0 0, otherwise γ= 1, if Fi,j+1/2 <0 0, otherwise β= 1, if Fi−1/2,j<0 0, otherwise δ= 1, if Fi,j−1/2 <0 0, otherwise (78) 3. Determine the Λbounding values (Equation 79). ΛR= (1−α) + αQ ΛU= (1−γ) + γQ ΛL= (1−β) + βQ ΛD= (1−δ) + δQ(79) 1 Note that the branching in Equation 78 can be avoided by directly utilizing the return value of a conditional expression.