/
hair physics.py
305 lines (240 loc) · 10.5 KB
/
hair physics.py
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import pandas as pd
import sys
import csv
import numpy as np
import math
import Box2D
from Box2D.b2 import (chainShape, contactListener, pi, world, vec2, fixtureDef, polygonShape, circleShape, staticBody, dynamicBody)
import pygame
from pygame.locals import (QUIT)
import random
CHAIN_MULTIPLIER = 4
def load_chain(world, data, dynamic):
chain = []
for ind in range(len(data)):
row = data[ind]
circle = circleShape(pos=(0,0), radius=0.001)
if dynamic:
new_body = world.CreateDynamicBody(position=row, userData=ind)
new_body.CreateFixture(fixtureDef(shape=circle, density=1, friction=0.3))
# if ind > 0:
# world.CreateDistanceJoint(bodyA=chain[ind-1], bodyB=new_body, anchorA=chain[ind-1].worldCenter, anchorB=new_body.worldCenter)
else:
new_body = world.CreateStaticBody(position=row, shapes=[circle])
chain.append(new_body)
return chain
def update_body(body, force_magnitude, frame_num, stroke_num, poly):
if poly:
next_data = pd.read_csv("frame"+str(frame_num + 1)+"stroke" +str(stroke_num)+ ".csv", delimiter = ",", header = None)
next_vecs = data_to_vecs_poly(next_data)
shape = body.fixtures[0].shape
set_lin_vel(next_vecs, body, shape, force_magnitude, poly=True)
def update_chain(chain, force_magnitude, frame_num, stroke_num):
next_data = pd.read_csv("frame"+str(frame_num + 1)+"stroke" +str(stroke_num)+ ".csv", delimiter = ",", header = None)
next_vecs = data_to_vecs(next_data)[::CHAIN_MULTIPLIER]
print(len(next_vecs), len(chain))
for ind in range(len(chain)):
body = chain[ind]
shape = body.fixtures[0].shape
vel = tuple(map(lambda i, j: (1 - force_magnitude) * TARGET_FPS * (i - j), next_vecs[ind], body.transform * shape.pos))
body.linearVelocity = (vel)
def output_chain(chain, frame_num, stroke_num):
output = []
for ind in range(len(chain)):
body = chain[ind]
shape = body.fixtures[0].shape
if ind < len(chain) - 1:
next_body_transform = chain[ind + 1].transform
else:
next_body_transform = body.transform
for mult_ind in range(CHAIN_MULTIPLIER):
factor = mult_ind / CHAIN_MULTIPLIER
screen_pos = body.transform.position * (1 - factor) + shape.pos + next_body_transform.position * (factor)
output.append(screen_pos)
with open("/Users/ilenee/Documents/2020-2021/Thesis/3_16/hair/output_frame"+str(frame_num)+"stroke"+str(stroke_num)+".csv", "w") as f:
writer = csv.writer(f)
writer.writerows(output)
def output_body(body, start_frame, frame_num, stroke_num):
data = pd.read_csv("frame"+str(start_frame)+"stroke" +str(stroke_num)+ ".csv", delimiter = ",", header = None)
vecs = data_to_vecs(data)
# multiplier = math.floor(len(next_data) / len(next_vecs))
# shape = body.fixtures[0].shape
output = []
for ind in range(len(vecs)):
vert = vecs[ind]
screen_coords = body.transform * vert
# if ind % multiplier == 0:
# output.append()
# vert = shape.vertices[int(ind / multiplier)]
# # translate
# screen_coords = body.transform * vert
# else:
# prev_ind = math.floor(ind / multiplier)
# next_ind = prev_ind + 1
# # check for overflow
# if next_ind * multiplier > len(next_data) - 1:
# vert = shape.next_data[ind]
# screen_coords = body.transform * vert
# output.append()
# for mult_ind in range(1, multiplier):
# if ind == len(shape.vertices) - 1:
# output.append(screen_coords)
# else:
# next_screen_coords = body.transform * shape.vertices[ind + 1]
# output.append(mult_ind / multiplier * next_screen_coords + (1 - mult_ind / multiplier) * screen_coords)
output.append(screen_coords)
with open("/Users/ilenee/Documents/2020-2021/Thesis/3:9/output_frame"+str(frame_num)+"stroke"+str(stroke_num)+".csv", "w") as f:
writer = csv.writer(f)
writer.writerows(output)
def data_to_vecs(data):
output = []
for _, row in data.iterrows():
output.append((row[0], row[1]))
return output
def data_to_vecs_poly(data):
output = []
for ind, row in data.iterrows():
if ind % math.ceil(len(data) / 16) == 0:
output.append((row[0], row[1]))
return output
def set_lin_vel(next_data, body, shape, force_magnitude, poly):
next_avg = np.average(next_data, axis=0)
curr_avg = [0,0]
for vertex in shape.vertices:
curr_avg = np.add(curr_avg, body.transform * vertex)
curr_avg = curr_avg / len(shape.vertices)
vel = tuple(map(lambda i, j: (1 - force_magnitude) * TARGET_FPS * (i - j), next_avg, curr_avg))
body.linearVelocity = (vel)
# constant
SNOWBALL_RADIUS = 0.001
PPM = 600.0 # pixels per meter
TARGET_FPS = 60
TIME_STEP = 1.0 / TARGET_FPS
SCREEN_WIDTH, SCREEN_HEIGHT = 640, 480
H_OFFSET = 320
V_OFFSET = 240
# setup
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32)
pygame.display.set_caption('Animation')
clock = pygame.time.Clock()
start_frame = int(sys.argv[1])
end_frame = int(sys.argv[2])
# construct world
world = world(gravity=(0,0), doSleep=True)
# load strokes
chains = []
static_chains = []
dynamic_chains = []
for ind in range(0, 5):
print(ind)
data = pd.read_csv("frame"+str(start_frame)+"stroke"+str(ind)+".csv", delimiter = ",", header = None)
data = data_to_vecs(data)[::CHAIN_MULTIPLIER]
if ind < 3:
chain = load_chain(world, data, dynamic=False)
static_chains.append(chain)
else:
chain = load_chain(world, data, dynamic=True)
dynamic_chains.append(chain)
# world.CreateRevoluteJoint(bodyA=chains[0][0], bodyB=chain[0], anchor=chain[0].worldCenter)
chains.append(chain)
print('loaded strokes')
# add borders (for debugging)
border_shape_h = polygonShape(vertices = [(-0.75, 0), (-0.75, 0.01), (0.75, 0.01), (0.75, 0)])
border_shape_v = polygonShape(vertices = [(0, -0.6), (0.01, -0.6), (0.01, 0.6), (0, 0.6)])
# border_body1 = world.CreateStaticBody(position=(0,0.39), shapes=border_shape_h)
# border_body2 = world.CreateStaticBody(position=(0,-0.4), shapes=border_shape_h)
# border_body3 = world.CreateStaticBody(position=(0.59,0), shapes=border_shape_v)
# border_body4 = world.CreateStaticBody(position=(-0.6,0), shapes=border_shape_v)
# env = [env_body, border_body1, border_body2, border_body3, border_body4]
# env = [env_body]
# env = []
force_magnitude = 1
force_decrement = force_magnitude / (end_frame - start_frame - 1)
# force_decrement = 0
force_vec = vec2(0.0001, 0.00005)
# main game loop
running = True
frame = start_frame
PERIOD = 20
period_counter = 0
rand = [random.random(), random.random()]
while running:
print("running", frame)
# Check the event queue
for event in pygame.event.get():
if event.type == QUIT:
# The user closed the window
running = False
screen.fill((0, 0, 0, 0))
# if int(frame * 8 / (end_frame - start_frame)) % 2 == 1:
# force_vec += vec2(0.00001, 0.00001)
# print("*")
# else:
# force_vec += vec2(-0.000005, -0.000005)
print(frame, force_vec)
print("screen filled")
for chain in chains:
for index in range(len(chain)):
link = chain[index]
for fixture in link.fixtures:
shape = fixture.shape
draw_pos = (link.transform * shape.pos) * PPM
draw_pos = (draw_pos[0] + H_OFFSET, SCREEN_HEIGHT - (draw_pos[1] + V_OFFSET))
pygame.draw.circle(screen, (255, 255, 255, 255), (int(draw_pos[0]), int(draw_pos[1])), int(shape.radius * PPM))
print("chains drawn")
# output_body(balloon1_body, start_frame, frame, 0)
# output_body(balloon1_knot_body, start_frame, frame, 1)
# output_chain(chain1, frame, 2)
# output_body(balloon2_body, start_frame, frame, 3)
# output_body(balloon2_knot_body, start_frame, frame, 4)
# output_chain(chain2, frame, 5)
for ind in range(len(chains)):
chain = chains[ind]
output_chain(chain, frame, ind)
# Make Box2D simulate the physics of our world for one step.
# Instruct the world to perform a single step of simulation. It is
# generally best to keep the time step and iterations fixed.
# See the manual (Section "Simulating the World") for further discussion
# on these parameters and their implications.
world.Step(TIME_STEP, 10, 10)
world.ClearForces()
print("time stepped")
# Flip the screen and try to keep at the target FPS
pygame.display.flip()
clock.tick(TARGET_FPS)
if frame == end_frame:
break
if period_counter == PERIOD:
PERIOD = math.ceil(random.random()*5+20)
period_counter = 0
rand = [random.random(), random.random()]
for ind in range(len(dynamic_chains)):
chain = dynamic_chains[ind]
ran = rand[ind]
for ind in range(len(chain)):
body = chain[ind]
# if int(ind * 6 / len(dynamic_chains[0])) % 2 == 1:
body.ApplyForce(ran * force_vec * force_magnitude * (math.sin(frame * 2 * math.pi / PERIOD) + 1) / 2 * abs(frame) / PERIOD * math.pow(ind, 2) / len(chain) / len(chain), body.position, True)
# else:
# body.ApplyForce(force_vec * force_magnitude * (ind / len(dynamic_chains[0])), body.position, True)
# for ind in range(len(dynamic_chains[1])):
# body = dynamic_chains[1][ind]
# # if int(ind * 4 / len(dynamic_chains[1])) % 2 == 1:
# if ind > len(dynamic_chains[1])/2:
# print("*")
# body.ApplyForce(force_vec * force_magnitude * (ind - len(dynamic_chains[1])/2) / len(dynamic_chains[1]), body.position, True)
# # else:
# # body.ApplyForce(force_vec * force_magnitude * ind / len(dynamic_chains[1]), body.position, True)
print("forces applied")
force_magnitude = max(0, force_magnitude - force_decrement)
# calculate and set linear velocities of balloons
# update_body(balloon1_body, force_magnitude, frame, 0, True)
# update_body(balloon1_knot_body, force_magnitude, frame, 1, True)
# update_body(balloon2_body, force_magnitude, frame, 3, True)
# update_body(balloon2_knot_body, force_magnitude, frame, 4, True)
update_chain(dynamic_chains[0], force_magnitude, frame, 3)
update_chain(dynamic_chains[1], force_magnitude, frame, 4)
print("chains updated")
frame = frame + 1
pygame.quit()
print('Done!')