`*** Cloth Physics by Ric ***
 
sync on
sync rate 40
autocam off
position camera 0,0,-150
hide mouse
color backdrop rgb(0,0,255)
 
`red texture
ink rgb(255,0,0),0
box 0,0,1,1
get image 1,0,0,1,1
`white texture
ink rgb(255,255,255),0
box 0,0,1,1
get image 2,0,0,1,1
`make flag
make object box 1,100,15,1
texture object 1,1
make object box 2,15,100,1
texture object 2,1
make object box 3,100,25,1
position object 3,0,0,.1
texture object 3,2
make object box 4,25,100,1
position object 4,0,0,.1
texture object 4,2
make object box 5,150,15,1
zrotate object 5,-45
position object 5,0,0,1
texture object 5,2
make object box 6,150,15,1
zrotate object 6,45
position object 6,0,0,1
texture object 6,2
make object box 7,150,5,1
zrotate object 7,45
position object 7,0,0,.5
texture object 7,1
make object box 8,150,5,1
zrotate object 8,-45
position object 8,0,0,.5
texture object 8,1
for ob=1 to 8
set object light ob,0
next ob
sync
`grab flag image
get image 3,screen width()/2-130,screen height()/2-130,screen width()/2+130,screen height()/2+130
`tidy up
for ob=1 to 8
delete object ob
next ob
 
`set initial physics variables
omega#=8
amp#=2.0
rows=50
columns=50
elasticity#=0.2
a=5
b=5
damping#=0.7
 
`set camera and lighting
position camera 70,55,0
point camera rows/2,0,columns/2
hide light 0
set ambient light 0
make light 1
position light 1,10,10,10
color backdrop 0
 
 
num=rows*columns
dim obnum(rows+1,columns+1)
dim v#(rows,columns) `set velocity array
 
`make matrix
make matrix 1,rows,columns,rows,columns
 
`give every matrix tile an x,z coordinate
for x=1 to rows
for z=1 to columns
obnum(x,z)=ob
ob=ob+1
next z
next x
 
`texture matrix
prepare matrix texture 1,3,rows,columns
tile=1
for x=rows-1 to 0 step -1
for z=0 to columns-1
set matrix tile 1,z,x,tile
inc tile
next z
next x
 
do
 
`oscillate wave generator point
y#=amp#*sin(theta#)
theta#=theta#+omega#
set matrix height 1,rows-a,b,y#
 
`apply spring physics to neighbouring matrix tiles
for x=0 to rows
for z=5 to columns
if x<rows
distxp1#=get matrix height(1,x+1,z)-get matrix height (1,x,z)
endif
if x>1
distxm1#=get matrix height(1,x-1,z)-get matrix height (1,x,z)
endif
if z<columns
distzp1#=get matrix height(1,x,z+1)-get matrix height (1,x,z)
endif
if z>1
distzm1#=get matrix height(1,x,z-1)-get matrix height (1,x,z)
endif
vectorsum#=distxp1#+distxm1#+distzp1#+distzm1#
a#=vectorsum#*elasticity#
v#(obnum(x,z))=v#(obnum(x,z))+a#
v#(obnum(x,z))=v#(obnum(x,z))*damping#
 
set matrix height 1,x,z,get matrix height(1,x,z)+v#(obnum(x,z))
`limit maximum amplitude
if get matrix height(1,x,z)>amp#*2 then set matrix height 1,x,z,amp#*2
if get matrix height(1,x,z)<-amp#*2 then set matrix height 1,x,z,-amp#*2
next z
next x
update matrix 1
 
`apply self regulating damping
if get matrix height (1,rows/4,columns/4)>amp#/2 or get matrix height (1,rows/4,columns/4)<-amp#/2
 if damping#>0.6 then dec damping#,0.0008
else
 if damping#<0.72 then inc damping#,0.0005
endif
text 0,40,"damping: "+str$(damping#)
 
sync
loop