Liquid Simulation For Corona SDK

Posted by eaguirre, Posted on October 28, 2011, Last updated October 31, 2011

2 votes

Optimization of the code

See the video at:

http://www.youtube.com/watch?v=pPkBw9fIZGU

Second test:

http://www.youtube.com/watch?v=KMYCPq2w-8s

Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
-------------------------------------------------------------------
--
--      Copyright 2011 Emilio Aguirre, All Rights Reserved.
--  www.emilioaguirre.com
-- 
-- Permission is hereby granted, free of charge, to any person obtaining a copy of 
-- this software and associated documentation files (the "Software"), to deal in the 
-- Software without restriction, including without limitation the rights to use, copy, 
-- modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 
-- and to permit persons to whom the Software is furnished to do so, subject to the 
-- following conditions:
-- 
-- The above copyright notice and this permission notice shall be included in all copies 
-- or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
-- This is a demo of a liquid simulation. 
-- Touch the screen to see the gravity changes, the liquid will go 
-- in the opposite direction.
-- 
-------------------------------------------------------------------
local physics = require("physics")
 
-- Define variables
local imgBuffer = {}            -- Image buffer
local w1= math.floor(display.contentWidth)
local h1= math.floor(display.contentHeight)
local refreshImage                      -- Flag to handle when to draw
local line={}                           -- Lines table
 
-- Start Physics
physics.start()
 
-- Hide status bar
display.setStatusBar( display.HiddenStatusBar )
 
-- Create background rect
local bg = display.newRect( 0, 0, 320, 480 )
bg:setFillColor( 0, 127, 255)           
 
-- Create the border to prevent the liquid to fall
borderCollisionFilter = { categoryBits = 1, maskBits = 6 } -- collides with (4 & 2) only
borderBodyElement = { friction=0.1, bounce=0.1, filter=borderCollisionFilter }
 
local borderTop = display.newRect( 0, 0, 320, 1 )
borderTop:setFillColor( 0, 0, 0, 0)             
physics.addBody( borderTop, "static", borderBodyElement )
 
local borderBottom = display.newRect( 0, 479, 320, 1 )
borderBottom:setFillColor( 0, 0, 0, 0)  
physics.addBody( borderBottom, "static", borderBodyElement )
 
local borderLeft = display.newRect( 0, 1, 1, 480 )
borderLeft:setFillColor( 0, 0, 0, 0)    
physics.addBody( borderLeft, "static", borderBodyElement )
 
local borderRight = display.newRect( 319, 1, 1, 480 )
borderRight:setFillColor( 0, 0, 0, 0)   
physics.addBody( borderRight, "static", borderBodyElement )
 
-- Add anoter wall in the middle 
local wall = display.newRect( 60, 350, 140, 20 )
wall:setFillColor( 255, 255, 0)
wall.rotation=45
physics.addBody( wall, "static", borderBodyElement )
 
wall = display.newRect( 140, 250, 140, 20 )
wall:setFillColor( 255, 255, 0)
wall.rotation=-45
physics.addBody( wall, "static", borderBodyElement )
-------------------------------------------------------------------
-- Create 200 balls that will serve as the liquid elements
-------------------------------------------------------------------
local balls = {}
local ballsCollisionFilter = { categoryBits = 2, maskBits = 3 } -- collides with (2 & 1) only
local ballsBody = { density=1000, friction=0.0, bounce=0.1, radius=6, filter=ballsCollisionFilter }
 
local function spawn()
        ballsBody.radius=math.random(3,6)
        balls[#balls+1] = display.newCircle(160, 200,ballsBody.radius)
        balls[#balls]:setFillColor(0,0,100,200) -- To make the balls transparent add 0 as the fourth element.
        balls[#balls].myName = "ball"
        physics.addBody( balls[#balls], ballsBody )
end
local tm =  timer.performWithDelay(40, spawn,200)
 
-------------------------------------------------------------------
-- Draw a set of lines (like flood fill) depending if the pixel in
-- the image buffer is greater than a threshold. 
-------------------------------------------------------------------
function fill(img,w,h,y1,y2)
        local threshold = 22    -- Threshold (best results from 18 to 30)
        local st = 0                    -- Flag to indicate if a start has being found
        local x1,y1                     -- Start line
        local x2,y2                     -- End line
        local step = 1                  -- Step greater than 1 will lead to fast rendering
        local yw 
        local idx
        local startY, endY
        startY = y1 or 0
        endY = y2 or (h - 1)
        -- Traverse the rows of the image buffer
        for y=startY,endY,step do
                st = 0
                yw = y*w
                -- Traverse the columns of the image buffer
            for x=0,w-1,step do
                        idx = yw+x+1
                -- if item exist and is greater than threshold
                if img[idx] and img[idx]>threshold then
                                -- There is no start yet                                
                                if st == 0 then
                                        st = 1
                                        -- Now we have a start
                                        x1,y1 = x,y
                                        x2,y2 = x,y
                                else
                                        -- Grow then end of line with the current pixel
                                        x1,y1 = x,y
                                end             
                        else
                                -- Do we have a line?
                                if st == 1 then
                                        -- Yes draw it.
                                        line[#line+1] = display.newLine(x1,y1,x2,y2)
                                        line[#line].width = step 
                                        line[#line]:setColor( 0, 0, 100, 127 ) -- semi-transparent
                                        -- Clear the flag
                                        st = 0
                                end
                        end                
            end
            -- Check if a missing line needs to be drawn
            if st == 1 then
                        line[#line+1] = display.newLine(x1,y1,x2,y2)
                        line[#line].width = step 
                        line[#line]:setColor( 0, 0, 100, 127 ) -- semi-transparent
                end
        end
end             
 
-------------------------------------------------------------------
-- Draw a circle mask inside a image buffer
-------------------------------------------------------------------
local mask = {
0,0,0,0,0,0,0,1,2,2,2,2,1,0,0,0,0,0,0,0,
0,0,0,0,0,2,4,6,7,8,8,7,6,4,2,0,0,0,0,0,
0,0,0,0,4,6,9,11,12,13,13,12,11,9,6,4,0,0,0,0,
0,0,0,4,8,11,13,16,17,18,18,17,16,13,11,8,4,0,0,0,
0,0,4,8,11,15,18,20,22,23,23,22,20,18,15,11,8,4,0,0,
0,2,6,11,15,19,22,25,27,28,28,27,25,22,19,15,11,6,2,0,
0,4,9,13,18,22,26,29,32,33,33,32,29,26,22,18,13,9,4,0,
1,6,11,16,20,25,29,33,36,38,38,36,33,29,25,20,16,11,6,1,
2,7,12,17,22,27,32,36,40,43,43,40,36,32,27,22,17,12,7,2,
2,8,13,18,23,28,33,38,43,47,47,43,38,33,28,23,18,13,8,2,
2,8,13,18,23,28,33,38,43,47,47,43,38,33,28,23,18,13,8,2,
2,7,12,17,22,27,32,36,40,43,43,40,36,32,27,22,17,12,7,2,
1,6,11,16,20,25,29,33,36,38,38,36,33,29,25,20,16,11,6,1,
0,4,9,13,18,22,26,29,32,33,33,32,29,26,22,18,13,9,4,0,
0,2,6,11,15,19,22,25,27,28,28,27,25,22,19,15,11,6,2,0,
0,0,4,8,11,15,18,20,22,23,23,22,20,18,15,11,8,4,0,0,
0,0,0,4,8,11,13,16,17,18,18,17,16,13,11,8,4,0,0,0,
0,0,0,0,4,6,9,11,12,13,13,12,11,9,6,4,0,0,0,0,
0,0,0,0,0,2,4,6,7,8,8,7,6,4,2,0,0,0,0,0,
0,0,0,0,0,0,0,1,2,2,2,2,1,0,0,0,0,0,0,0
}
-------------------------------------------------------------------
-- Draw a mask circle over the image buffer
--
-- pix  - image buffer
-- w    - width of the image buffer 
-- h    - height of the image buffer
-------------------------------------------------------------------
function drawCircle(pix,w,h)
        local y,x,ny,nx,index,maskIdx,y9,nyw
        local ox        -- x of the physical object
        local oy        -- y of the physical object
        local floor = math.floor
        local minY=h
        local maxY=0
        for i = 1,#balls do
                ox = floor(balls[i].x)
                oy = floor(balls[i].y)
                if oy+10>maxY then maxY = oy+10 end
                if oy-9<minY then minY = oy-9 end
                for y=-9,10 do
                        y9 =(y+9)*20
                        ny = y+oy
                        nyw = ny*w
                        for x=-9,10 do
                                nx = x+ox
                                if (nx>0 and nx<=w and ny>0 and ny<=h) then
                                        index   = nyw+nx+1
                                        maskIdx = y9+x+10
                                        if pix[index] then
                                                pix[index] = (pix[index] + mask[maskIdx])
                                        else
                                                pix[index] = mask[maskIdx]
                                        end
                                end
                        end
                end
        end
        -- Just draw lines from range [minY,maxY], so in worst case it
        -- will draw all screen.
        return math.max(0,minY),math.min(maxY,h)
end
 
-------------------------------------------------------------------
-- Callback to frame 
-------------------------------------------------------------------
local onFrameUpdate = function( event )
 
        -- Redraw only if a collision has been detected
        if refreshImage == 1 then
                -- Clear the buffer image
                imgBuffer={}
                -- Remove all lines from display
                for _,v in pairs(line) do
                        v.parent:remove( v )
                end
                line={}
                -- Draw in the buffer some dots corresponding to the same position
                -- of the physical objects 
                local y1,y2 = drawCircle(imgBuffer,w1,h1)
        
                -- Fill the objects in the display according to the objects in the 
                -- image buffer.
                fill(imgBuffer,w1,h1,y1,y2)
                
                -- Reset the flag 
                refreshImage = 0
        end
end
 
-------------------------------------------------------------------
-- Callback to global collision 
-------------------------------------------------------------------
local function onGlobalCollision( event )
 
        if (event.object1.myName~=nil and event.object2.myName~=nil) then
                -- A collision ended let's refresh the images
                if ( event.phase == "ended") then
                        -- Only refresh if at least we have a collision 
                        refreshImage = 1
                end
        end
        
end
-------------------------------------------------------------------
-- Callback to global accelerometer 
-------------------------------------------------------------------
local function onTilt( event )
        physics.setGravity( 10 * event.xGravity, -10 * event.yGravity )
end
 
-------------------------------------------------------------------
-- Callback to frame 
-------------------------------------------------------------------
local onTouchCallback = function( event )
        physics.setGravity( 0.05 * (event.x - 180), 0.05 * (event.y-240))
end
-------------------------------------------------------------------
-- Create event listeners
-------------------------------------------------------------------
Runtime:addEventListener( "enterFrame", onFrameUpdate )
Runtime:addEventListener( "collision", onGlobalCollision )
Runtime:addEventListener( "accelerometer", onTilt )
Runtime:addEventListener( "touch", onTouchCallback )


Replies

canupa.com's picture
canupa.com
User offline. Last seen 21 hours 4 min ago. Offline
Joined: 20 Jun 2011

wow! that really looks awesome!
thanks, dude!

AlenB's picture
AlenB
User offline. Last seen 4 days 3 hours ago. Offline
Joined: 29 Sep 2010

Whohooo !!
Thx so much! Looks really cool!!

carlos m. icaza's picture
carlos m. icaza
User offline. Last seen 6 weeks 5 days ago. Offline
Alumni
Joined: 22 Jun 2009

+1

Naomi's picture
Naomi
User is online Online
Joined: 6 Jun 2011

Super cool!

underwaterdiver's picture
underwaterdiver
User offline. Last seen 8 weeks 3 hours ago. Offline
Joined: 28 Oct 2011

Pretty hip!

liongera
User offline. Last seen 2 weeks 4 days ago. Offline
Joined: 4 May 2011

OMG awesome!

underwaterdiver's picture
underwaterdiver
User offline. Last seen 8 weeks 3 hours ago. Offline
Joined: 28 Oct 2011

FYI, I woke up this morning, not too much sleep, but I was thinking WOW, wouldn't this be a neat thing to have as another item in an app. Kind of like a:
"Play with this while you're waiting!"

cheers.
Richard

juliusbangert's picture
juliusbangert
User offline. Last seen 2 weeks 3 days ago. Offline
Joined: 19 May 2011

Firstly.. this is excellent, thanks for sharing this!
Can you think of a good way in which this can be made into a module? I have tried and it works well if I call a function to create liquid. But if I try to call multiple instances of it, it slows right down. I guess this is because I shouldn't really have multiple runtime listeners. Any ideas?

eaguirre's picture
eaguirre
User offline. Last seen 5 weeks 2 days ago. Offline
Joined: 12 Oct 2010

Thanks Julius,

Unfortunately this code as it is, runs slooowwww on a device. Because of the time it takes adding display lines to simulate the fill of the water. Also having to much objects inside the physics world slows down performance.
Carlos was suggesting adding a function inside the corona sdk to fill polygons, http://developer.anscamobile.com/forum/2011/11/01/add-displaynewmetaball
hope that will came out soon.

juliusbangert's picture
juliusbangert
User offline. Last seen 2 weeks 3 days ago. Offline
Joined: 19 May 2011

Yes! I think this would be a very useful feature. What can be done to push this?
I don't 100% understand your code, for example I'm not sure whats happening with mask coordinates table, I need to have a proper look.. but anyway do you think it could be possible to use a bezier curve to speed things up? (http://developer.anscamobile.com/code/bezier-curves-corona) I wouldn't know where to start with this but would that put less strain on the enterframe processing?

eaguirre's picture
eaguirre
User offline. Last seen 5 weeks 2 days ago. Offline
Joined: 12 Oct 2010

Let me explain you how it works:

First I throw a bunch of circle physical objects on the screen. Each is like a drop of water. And the interactions between them will result in the liquid simulation.
But to see the effect we will need to find a way to fill the spaces between each circle (drop of water) that is in contact with another circle to give this feeling of a one entity ( the water).

Must of the algorithms that simulates water work like this:
- Draw the bunch of balls
- Take a screen snapshot (image) and blur it (the blur effect will increase the size of each ball to fill the space between the drops of water).
- Take the blur image and apply a threshold. All pixels greater than a threshold T will be replaced by a full color and the rest will be 0.
- This threshold will convert the image into a nice looking blob of connecting balls ( the liquid).

Unfortunately Corona SDK does not provide a way to implement this algorithm.

So my code does almost the same but in a different way:

- I set a bunch of physical balls in the app. with NO drawing (see how each ball has a transparent color in the spawn function).
- Because Corona does not let me to access to image pixels, I decided to create my own image buffer.
- This image buffer is a table of size width x height of the screen like IMG = {0,0,0,0,....0,0,0}
- Instead of drawing all balls in the screen and then make a blur, I created a blur image of 1 (ONE) ball and call it a the MASK. This mask is a 20x20 icon where value 0 is transparent and value of 255 is color white.
- Then for each physical ball object I spawned, I look at it's position X,Y on the physical screen, and I "draw" (more like adding the values) the circular 20x20 MASK to my internal image buffer IMG. This "draw" is very simple for each value of the mask I add that value to the existing value of the IMG buffer, if this value is greater than 255 I clamped to 255.
- When finished, the IMG buffer will have a representation of the liquid.
- But how I create an image and copy to the screen with this buffer in Corona SDK? well we can't.
- So that's where the last piece of code is all about the FILL function. This function is simple traverse line by line (from 0 to height) and create a display.newLine (horizontal line) object for the "pixels" in my IMG buffer that are greater than a threshold.
So the end result is like having a stack of pancakes (white lines) that all together form the liquid.

If you understand how it's working, now you will see that a Bezier curve will not help to my algorithm.

The two ways to speed this thing will:
- Having a function to access the pixels of an image in native Corona.
- Or having a function to draw and fill blobs of arbitrary polygons (concave or convex) in native Corona.
I will prefer the former, but don't think this is a priority in the roadmap,

Cheers,