1. Uwe Fechner
  2. FreeKiteSim

Source

FreeKiteSim / 3D_Viewer / FreeKiteViewer.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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
"""
* This file is part of FreeKiteSim.
*
* FreeKiteSim -- A kite-power system power simulation software.
* Copyright (C) 2013 by Uwe Fechner, Delft University
* of Technology, The Netherlands. All rights reserved.
*
* SystemOptimizer is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SystemOptimizer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with SystemOptimizer; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
"""
""" 3D viewer for kite-power systems. Displays: The tether (any number of sgements), the kite (3D with
lights and shading, but as a riged body and a coordinate system. Additionally the virtual tether axis,
the projected trajectory and the local kite reference frame can be displayed.

Input: Google Procol Buffer encoded messages, sent from the ZeroMQ port: tcp://localhost:5575

Message format:

// the state of the particle system (tether, kite, later perhaps also the winch)
// only the information needed for 3D visualization
message ParticleSystem {
  required double time          =  1; // relative simulation time in seconds
  required double counter       =  2; // package counter (to detect package losses)
  repeated PositionEG positions =  3; // list of particle positions in EG reference frame
  optional double v_reel_out    =  4; // reel-out velocity                [m/s]
  optional double l_tether      =  5; // tether length                    [m/s]
  optional double force         =  6; // tether force                     [N]
  optional double v_wind_ground =  7; // ground wind speed                [m/s]
  optional double height        =  8; // height of the kite               [m]
  optional double v_wind_height =  9; // wind speed at height of the kite [m/s]
  optional double v_app_x       = 10; // apparent wind speed at the kite,  x direction (east)  [m/s]
  optional double v_app_y       = 11; // wind speed at height of the kite, y direction (north) [m/s]
  optional double v_app_z       = 12; // wind speed at height of the kite, z direction (up)    [m/s]
  optional double rel_steering  = 13; // relative steering        (-1.0 .. 1.0)
  optional double rel_depower   = 14; // relative depower         ( 0.0 .. 1.0)
  optional double azimuth       = 15; // azimuth
  optional double elevation     = 16; // elevation
  repeated Velocity_EG velocities = 17; // list of particle velocities in EG reference frame
  repeated PositionEG pos_predicted = 18; // list of predicted particle positions in EG reference frame
}

"""
from cgkit.all import vec3, mat3, Globals, TargetCamera, GLPointLight, GLMaterial, CCylinder, drawText, \
               Sphere, Scene, drawClear, getScene, load, KEY_ESCAPE, KEY_PRESS, eventManager, STEP_FRAME
import OpenGL.GLUT as glut
from math import pi, sqrt
import zmq, sys
from os.path import expanduser
sys.path.append(expanduser("~") + '/00PythonSoftware/FreeKiteSim')
import asset.system_pb2 as system
from Settings import SCALE, KITE_SCALE, REL_SPEED, SEGMENTS, SPRINGS

TEST = 0                           # 0: dynamic operation; 1,2,3: static (stand alone) test casses
if 'ufechner' in expanduser('~'):
    PREDICT = True                 # True: draw the predicted trajectory for the next 4 seconds
else:
    PREDICT = False

PARTICLES  = []
VELOCITIES = []
POS_PREDICTED = []
TIME = 0.0
LAST_TIME = -0.05
V_app = vec3(5, 20, 2)
Force, L_tether, V_reel_out = 0.0, 0.0, 0.0
Azimuth, Elevation = 0.0, 0.0

# pylint: disable=E1101
class Receiver(object):
    """Receiver for ZeroMQ messages. Is listening on port 5575. """
    def __init__(self):
        self._stop = False
        self.context = zmq.Context()
        self.receiver = self.context.socket(zmq.SUB)
        self.receiver.connect("tcp://localhost:5575")
        self.receiver.setsockopt (zmq.SUBSCRIBE, chr(system.mtParticleSystem))
        self.poller = zmq.Poller()
        self.poller.register(self.receiver, zmq.POLLIN)
        self.sys = system.ParticleSystem()
        print "Listening on port 5575! Press <ESC> to terminate."

    def queryData(self):
        """ Wait until a message is received. Than store the message content in the defined global
        variables and return. """
        global TIME, PARTICLES, VELOCITIES, POS_PREDICTED, V_reel_out, L_tether, Force, Azimuth, Elevation
        socks = dict(self.poller.poll(200))
        if socks:
            if socks.get(self.receiver) == zmq.POLLIN:
                data = self.receiver.recv()
                messagetype = ord(data[0])
                if messagetype ==system.mtParticleSystem:
                    # print "mtParticleSystem received!"
                    self.sys.ParseFromString(data[1:len(data)])
                    PARTICLES  = []
                    VELOCITIES = []
                    POS_PREDICTED = []
                    TIME = self.sys.time
                    for position in self.sys.positions:
                        particle = vec3(position.pos_east, position.pos_north, position.height)
                        PARTICLES.append(particle)
                    for position in self.sys.pos_predicted:
                        particle = vec3(position.pos_east, position.pos_north, position.height)
                        POS_PREDICTED.append(particle)
                    for velocity in self.sys.velocities:
                        vel = vec3(velocity.v_east, velocity.v_north, velocity.v_up)
                        VELOCITIES.append(vel)
                    V_reel_out = self.sys.v_reel_out
                    L_tether   = self.sys.l_tether
                    Force      = self.sys.force
                    Azimuth    = self.sys.azimuth
                    Elevation  = self.sys.elevation
                    V_app[0], V_app[1], V_app[2] = self.sys.v_app_x, self.sys.v_app_y, self.sys.v_app_z

    def stop(self):
        """ Stop the viewer program. """
        self._stop = True

    def stopped(self):
        """ Check, if the signal stop was received. """
        return self._stop

    def close(self):
        """ Close the background thread, that is receiving messages. """
        self.receiver.close()
        self.context.term()

    def closed(self):
        """ Check, if the background thread of the receiver was closed. """
        return self.receiver.closed

RECEIVER = Receiver()

Globals(
    background = (0.7, 0.8, 1.0),
    resolution = (694, 694),
    fps = 20.0 * REL_SPEED
)

TargetCamera(
    #pos    = (30/1.06 * SCALE, 15*1.5/1.06 * SCALE, 20*1.5/1.06 * SCALE) , # default view
    pos    = (20/1.06 * SCALE, 15/1.06 * SCALE, 15/1.06 * SCALE) , # default view
    #pos    = (0, 15 * SCALE, 0),    # Frontview
    target = (0 * SCALE, 0 * SCALE, 5 * SCALE)
)

GLPointLight(
    pos       = (3 * SCALE, -1 * SCALE, 2 * SCALE),
    diffuse   = (0.7, 0.7, 0.7)
)

GLPointLight(
    pos       = (20 * SCALE, 15 * SCALE, 15 * SCALE),
    diffuse   = (0.7, 0.7, 0.7)
)

GLPointLight(
    pos       = (-5 * SCALE, 3 * SCALE, 0 * SCALE),
    diffuse   = (0.7, 0.7, 0.7)
    #diffuse   = (0.2, 0.2, 0.5),
)

# First, some useful functions
def rx(ang):
    return mat3(1).rotate(ang, (1, 0, 0))
def ry(ang):
    return mat3(1).rotate(ang, (0, 1, 0))
def rz(ang):
    return mat3(1).rotate(ang, (0, 0, 1))

def rot2d(a, b):
    """
    Calculate the rotation of a so that it matches b.
    a, b must be of type cgkit.cgtypes.vec3.
    """
    x = (a.cross(b)).normalize()
    v = (a * b) / a.length() / b.length()
    A = mat3(0,   -x[2], x[1],
             x[2], 0,   -x[0],
            -x[1], x[0],   0)
    return  mat3(1.0) + sqrt(1 - v * v ) * A + (1 - v) * A * A

def rot3d(ax, ay, az, bx, by, bz):
    """
    Calculate the rotation of reference frame (ax, ay, az) so that it matches the reference frame
    (bx, by, bz).
    All parameters must be of type cgkit.cgtypes.vec3. Both refrence frames must be orthogonal,
    all vectors must already be normalized.
    Source: http://en.wikipedia.org/wiki/User:Snietfeld/TRIAD_Algorithm
    """
    R_ai = mat3(ax, az, ay) # from reference frame a to intermedia reference frame
    R_bi = mat3(bx, bz, by) # from reference frame b to intermedia reference frame
    return R_bi * R_ai.transpose()

# Define materials
matRed     = GLMaterial(name="Red",     diffuse=(1,     0, 0))
matGreen   = GLMaterial(name="Green",   diffuse=(0,     1, 0))
matBlue    = GLMaterial(name="Blue",    diffuse=(0.2, 0.2, 1))
matCyan    = GLMaterial(name="Cyan",    diffuse=(0,     1, 1))
matMagenta = GLMaterial(name="Magenta", diffuse=(1,     0, 1))
matYellow  = GLMaterial(name="Yellow",  diffuse=(1,     1, 0))
matWhite   = GLMaterial(name="White",   diffuse=(1,     1, 1))
matGray    = GLMaterial(name="Gray",    diffuse=(0.7, 0.7, 0.7))
matBlack   = GLMaterial(name="Black",   diffuse=(0,     0, 0))

def drawC(segments1, a, rot, mat=matBlack, length = 1.0, text = '', text_offset = vec3(0, 0, 0)):
    """
    Draw a cylinder from point a into the direction of rot with an arrow and a text-string at the end.
    rot must be a rotation matrix of type mat3.
    """
    delta = rot * vec3(0, 0, 1)
    segments1.append(CCylinder(radius = 0.018 * SCALE, length = length * SCALE,
                               pos = a +  0.5 * length * SCALE * delta, rot = rot,  material = mat))
    drawText((a +  (0.35 + length) * SCALE * delta + text_offset), text,
             font = glut.GLUT_BITMAP_HELVETICA_18, color=(0, 0, 0))
    # create arrow at the top
    for i in range(10):
        CCylinder(length = 0.07 * SCALE / 3.0, radius = 0.018 * (10 - i) * SCALE / 3.0,
                  scale = (1, 1, 0.5 + i / 18.0),
                  pos = a +  (length + 0.025 * i) * SCALE * delta,
                  rot = rot, material  = mat)

def drawAxis(y_k):
    """ Draw the axis around the kite is turning on a spiral. This is used by the kinematic kite model,
    needed from the kite-state estimator. An empty list has to be passed to the parameter axis. One or
    more cylinders are added to this list to represent the axis.
    pos_kite: position of the kite in the ENU reference frame
    y_k     : y axis of the kite reference frame"""

    if len(axis) == 0:
        axis.append(CCylinder(radius = 0.02 * SCALE, material = matCyan))
    axis[0].length = 10.0 * SCALE
    axis[0].pos    = vec3(0, 0, 0)
    axis[0].rot    = rot2d(vec3(0, 0, 1), y_k)

def drawPrediction():
    """ Draw the spiral of the predicted kite path, assuming that the kite is flying into the direction
    of v_orto with the tangential kite speed v_t,
    the reel-out speed v_ro and given time_horizon [s]. """

    cylinder_count = len(POS_PREDICTED) - 1
    for i in range (cylinder_count):
        delta = POS_PREDICTED[i+1] - POS_PREDICTED[i]
        if len(axis) < cylinder_count + 1:
            axis.append(CCylinder(radius = 0.02 * SCALE, material = matCyan))
        axis[i+1].length = delta.length()
        axis[i+1].pos    = (POS_PREDICTED[i+1] + POS_PREDICTED[i]) / 2.0
        axis[i+1].rot    = rot2d(vec3(0, 0, 1), delta)

## The tether is made of balls and segments
balls, segments, axis = [], [], []
def drawParticles(kite_frame = False):
    """ Draw the tether (the global list PARTICLES) and optionally the kite reference frame."""
    if RECEIVER.closed():
        return
    RECEIVER.queryData()
    # Create 'n' balls and cyclinders
    last_particle, delta = None, None
    i = 0
    for particle in PARTICLES:
        if len(balls) < len(PARTICLES):
            if i < SEGMENTS + 1:
                # particles of the main tether
                balls.append(Sphere(radius = 0.07 * SCALE, material = matYellow))
            else:
                # particles of the bridle
                balls.append(Sphere(radius = 0.025 * SCALE, material = matYellow))
        balls[i].pos = particle
        last_particle = particle
        i += 1
    i = 0
    for spring in SPRINGS:
        if last_particle is not None:
            particle1 = PARTICLES[int(spring[1])]
            particle2 = PARTICLES[int(spring[0])]
            delta = particle1 - particle2
            length = delta.length()
            pos = 0.5 * (particle1 + particle2)
            if len(segments) < len(SPRINGS):
                # if True:
                if i < SEGMENTS:
                    # tether segments of the main tether
                    segments.append(CCylinder(radius = 0.02 * SCALE, material = matYellow))
                else:
                    # tether segments of the bridle
                    segments.append(CCylinder(radius = 0.01 * SCALE, material = matYellow))
            segments[i].length = length
            segments[i].pos    = pos
            segments[i].rot    = rot2d(vec3(0, 0, 1), delta)
            i += 1

    if delta is not None and KITE_SCALE is not None:
        delta = PARTICLES[SEGMENTS] - PARTICLES[SEGMENTS - 1]
        c = -delta
        z = c.normalize()
        y = (V_app.cross(c)).normalize()
        x = (y.cross(c)).normalize()
        drawAxis(y)
        if len(VELOCITIES) > 0:
            # print 'v_kite', VELOCITIES[0]
            if PREDICT:
                drawPrediction()
        if kite_frame:
            particle = last_particle
            # draw the orthogonal coordinate system within the kite reference frame
            drawC(segments, particle, rot2d(vec3(0, 0, 1), c), length = 1.4, text = 'c', \
                  text_offset = vec3(3, 0, 0))
            drawC(segments, particle, rot2d(vec3(0, 0, 1), v_a.normalize()), text = 'v_a')
            drawC(segments, particle, rot2d(vec3(0, 0, 1), z), text = 'z', text_offset = vec3(3, 0, 0))
            drawC(segments, particle, rot2d(vec3(0, 0, 1), y), text = 'y')
            drawC(segments, particle, rot2d(vec3(0, 0, 1), x), text = 'x')
        kite.pos = PARTICLES[SEGMENTS]
        kite.rot = rot3d(vec3(0, -1, 0), vec3(1, 0, 0), vec3(0, 0, -1), x, y, z)
    drawClear()
    drawText((-8.4 * SCALE, 2.0 * SCALE, 0), 'azimuth:    ' + '%7.2f' % (Azimuth * 180.0 / pi), color=(0, 0, 0))
    drawText((-8.8 * SCALE, 1.5 * SCALE, 0), 'elevation:  ' + '%7.2f' % (Elevation * 180.0 / pi), color=(0, 0, 0))
    drawText((-9.2 * SCALE, SCALE, 0), 'v_reel_out: ' + '%7.2f' % V_reel_out, color=(0, 0, 0))
    drawText((-9.6 * SCALE, 0.5 * SCALE, 0), 'l_tether  : ' + '%7.2f' % L_tether, color=(0, 0, 0))
    drawText((-10 * SCALE, 0, 0), 'force [N] : ' + '%7.2f' % Force, color=(0, 0, 0))
    # write the name of the axis
    drawText((0, 0.12 * SCALE, 12 * SCALE), "z", font = glut.GLUT_BITMAP_HELVETICA_18, color=(0, 0, 0))
    drawText((0, 11.7 * SCALE, - 0.25 * SCALE), "y", font = glut.GLUT_BITMAP_HELVETICA_18, color=(0, 0, 0))
    drawText((14.25 * SCALE, 0, 0), "x", font = glut.GLUT_BITMAP_HELVETICA_18, color=(0, 0, 0))
    if RECEIVER.stopped():
        print "Stopped."
        RECEIVER.close()

def createCoordinateSystem(points = 10, length = 10):
    """ Draw an coordinate system with x, y and z axis. The z axis is pointing upwards. """
    # create origin
    Sphere(radius = 0.1 * SCALE, pos = (0, 0, 0),  material  = matGray)
    # create x-axes in red
    points += 2
    if points > 0:
        for x in range(points + 2):
            if x - 1 > 0:
                Sphere(radius = 0.1 * SCALE, pos = ((x - 1) * SCALE, 0, 0),  material  = matRed)
    if points == 0:
        points = length
    CCylinder(length = (points + 2.0) * SCALE, radius = 0.05 * SCALE,
              rot = ry(pi / 2.0),
              pos = vec3((points / 2.0) * SCALE, 0, 0),
              material  = matRed  )
    # create arrow at the top
    for i in range(10):
        CCylinder(length = 0.07 * SCALE, radius = 0.018 * (10 - i) * SCALE, scale = (1, 1, 0.5 + i / 18.0),
                  pos = vec3((points + 1 + 0.07 * i) * SCALE, 0, 0),
                  rot = ry(pi / 2.0), material  = matRed  )
    glut.glutInit()
    #create y-axes in green
    points -= 3
    if points > 0:
        for y in range(2 * points + 1):
            if y - points != 0:
                Sphere(radius = 0.1 * SCALE, pos = (0, (y - points) * SCALE, 0),  material  = matGreen)
    if points == 0:
        points = length
    CCylinder(length = (2 * points + 2.0) * SCALE, radius = 0.05 * SCALE, rot=rx(pi/2.0), material = matGreen)
    # create arrow at the top
    for i in range(10):
        CCylinder(length = 0.07 * SCALE, radius = 0.018 * (10 - i) * SCALE, scale = (1, 1, 0.5 + i / 18.0),
                  pos = vec3(0, (points + 1 + 0.07 * i) * SCALE, 0),
                  rot = rx(pi / 2.0), material  = matGreen)
    points += 1
    # create z-axes in blue
    if points > 0:
        for z in range(points + 2):
            if z - 1 > 0:
                Sphere(radius = 0.1 * SCALE, pos = (0, 0, (z - 1) * SCALE),  material  = matBlue)
    if points == 0:
        points = length
    CCylinder(length = (points + 2.0) * SCALE, radius = 0.05 * SCALE,
              pos = vec3(0, 0, (points / 2.0) * SCALE),
              rot = rz(pi / 2.0), material  = matBlue)
    # create arrow at the top
    for i in range(10):
        CCylinder(length = 0.07 * SCALE, radius = 0.018 * (10 - i) * SCALE, scale = (1, 1, 0.5 + i / 18.0),
                  pos = vec3(0, 0, (points + 1 + 0.07 * i) * SCALE), material  = matBlue)


if KITE_SCALE is not None:
    kite = Sphere(radius = 0.01 * SCALE, scale = (KITE_SCALE, KITE_SCALE, KITE_SCALE), material  = matGray)

createCoordinateSystem(10)

scene = getScene()
Scene.worldRoot(scene).rot = rz(pi)

# create default tether
if TEST == 1:
    v_a = vec3(5, 20, 2)
    PARTICLES.append(vec3(0, 0, 0))
    PARTICLES.append(vec3(3, 0, 1.0) * SCALE)
    PARTICLES.append(vec3(6, 0, 2.5) * SCALE)
    PARTICLES.append(vec3(9, 0, 6.0) * SCALE)
elif TEST == 2:
    v_a = vec3(20, 5, 2)
    PARTICLES.append(vec3(0, 0, 0))
    PARTICLES.append(vec3(0, 1, 1) * SCALE)
    PARTICLES.append(vec3(0, 2, 2) * SCALE)
    PARTICLES.append(vec3(0, 3, 3) * SCALE)
elif TEST == 3:
    v_a = vec3(5, 20, 2)
    PARTICLES.append(vec3(0, 0, 0))
    PARTICLES.append(vec3(3, 1, 1) * SCALE)
    PARTICLES.append(vec3(6, 2, 2) * SCALE)
    PARTICLES.append(vec3(9, 3, 3) * SCALE)

if KITE_SCALE is not None:
    load("finalekite.3ds", parent = kite)

def escape(key):
    """ Handler for handling the event, that the escape key was pressed or the window was closed. """
    if key.keycode == KEY_ESCAPE:
        RECEIVER.stop()
        return True

if TEST == 0:
    EVENT_MANAGER = eventManager()
    EVENT_MANAGER.connect(STEP_FRAME, drawParticles)
    EVENT_MANAGER.connect(KEY_PRESS, escape)
else:
    drawParticles()