-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathgeometry.py
450 lines (349 loc) · 12 KB
/
geometry.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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
from __future__ import absolute_import, division, print_function
import sys
import base64
import uuid
if sys.version_info >= (3, 0):
unicode = str
import umsgpack
import numpy as np
from . import transformations as tf
class SceneElement(object):
def __init__(self):
self.uuid = unicode(uuid.uuid1())
class ReferenceSceneElement(SceneElement):
def lower_in_object(self, object_data):
object_data.setdefault(self.field, []).append(self.lower(object_data))
return self.uuid
class Geometry(ReferenceSceneElement):
field = "geometries"
def intrinsic_transform(self):
return tf.identity_matrix()
class Material(ReferenceSceneElement):
field = "materials"
class Texture(ReferenceSceneElement):
field = "textures"
class Image(ReferenceSceneElement):
field = "images"
class Box(Geometry):
def __init__(self, lengths):
super(Box, self).__init__()
self.lengths = lengths
def lower(self, object_data):
return {
u"uuid": self.uuid,
u"type": u"BoxGeometry",
u"width": self.lengths[0],
u"height": self.lengths[1],
u"depth": self.lengths[2]
}
class Sphere(Geometry):
def __init__(self, radius):
super(Sphere, self).__init__()
self.radius = radius
def lower(self, object_data):
return {
u"uuid": self.uuid,
u"type": u"SphereGeometry",
u"radius": self.radius,
u"widthSegments" : 20,
u"heightSegments" : 20
}
class Ellipsoid(Sphere):
"""
An Ellipsoid is treated as a Sphere of unit radius, with an affine
transformation applied to distort it into the ellipsoidal shape
"""
def __init__(self, radii):
super(Ellipsoid, self).__init__(1.0)
self.radii = radii
def intrinsic_transform(self):
return np.diag(np.hstack((self.radii, 1.0)))
class Plane(Geometry):
def __init__(self, width=1, height=1, widthSegments=1, heightSegments=1):
super(Plane, self).__init__()
self.width = width
self.height = height
self.widthSegments = widthSegments
self.heightSegments = heightSegments
def lower(self, object_data):
return {
u"uuid": self.uuid,
u"type": u"PlaneGeometry",
u"width": self.width,
u"height": self.height,
u"widthSegments": self.widthSegments,
u"heightSegments": self.heightSegments,
}
"""
A cylinder of the given height and radius. By Three.js convention, the axis of
rotational symmetry is aligned with the y-axis.
"""
class Cylinder(Geometry):
def __init__(self, height, radius=1.0, radiusTop=None, radiusBottom=None):
super(Cylinder, self).__init__()
if radiusTop is not None and radiusBottom is not None:
self.radiusTop = radiusTop
self.radiusBottom = radiusBottom
else:
self.radiusTop = radius
self.radiusBottom = radius
self.height = height
self.radialSegments = 50
def lower(self, object_data):
return {
u"uuid": self.uuid,
u"type": u"CylinderGeometry",
u"radiusTop": self.radiusTop,
u"radiusBottom": self.radiusBottom,
u"height": self.height,
u"radialSegments": self.radialSegments
}
class MeshMaterial(Material):
def __init__(self, color=0xffffff, reflectivity=0.5, map=None,
side = 2, transparent = None, opacity = 1.0, **kwargs):
super(MeshMaterial, self).__init__()
self.color = color
self.reflectivity = reflectivity
self.map = map
self.properties = kwargs
self.side = side
self.transparent = transparent
self.opacity = opacity
def lower(self, object_data):
# Three.js allows a material to have an opacity which is != 1,
# but to still be non-transparent, in which case the opacity only
# serves to desaturate the material's color. That's a pretty odd
# combination of things to want, so by default we juse use the
# opacity value to decide whether to set transparent to True or
# False.
if self.transparent is None:
transparent = self.opacity != 1
else:
transparent = self.transparent
data = {
u"uuid": self.uuid,
u"type": self._type,
u"color": self.color,
u"reflectivity": self.reflectivity,
u"side": self.side,
u"transparent": transparent,
u"opacity": self.opacity
}
data.update(self.properties)
if self.map is not None:
data[u"map"] = self.map.lower_in_object(object_data)
return data
class MeshBasicMaterial(MeshMaterial):
_type=u"MeshBasicMaterial"
class MeshPhongMaterial(MeshMaterial):
_type=u"MeshPhongMaterial"
class MeshLambertMaterial(MeshMaterial):
_type=u"MeshLambertMaterial"
class MeshToonMaterial(MeshMaterial):
_type=u"MeshToonMaterial"
class PngImage(Image):
def __init__(self, data):
super(PngImage, self).__init__()
self.data = data
@staticmethod
def from_file(fname):
with open(fname, "rb") as f:
return PngImage(f.read())
def lower(self, object_data):
return {
u"uuid": self.uuid,
u"url": unicode("data:image/png;base64," + base64.b64encode(self.data).decode('ascii'))
}
class TextTexture(Texture):
def __init__(self, text, font_size=100, font_face='sans-serif',
width=200, height=100, position=[10, 10]):
super(TextTexture, self).__init__()
self.text = text
# font_size will be passed to the JS side as is; however if the
# text width exceeds canvas width, font_size will be reduced.
self.font_size = font_size
self.font_face = font_face
def lower(self, object_data):
return {
u"uuid": self.uuid,
u"type": u"_text",
u"text": unicode(self.text),
u"font_size": self.font_size,
u"font_face": self.font_face,
}
class GenericTexture(Texture):
def __init__(self, properties):
super(GenericTexture, self).__init__()
self.properties = properties
def lower(self, object_data):
data = {u"uuid": self.uuid}
data.update(self.properties)
if u"image" in data:
image = data[u"image"]
data[u"image"] = image.lower_in_object(object_data)
return data
class ImageTexture(Texture):
def __init__(self, image, wrap=[1001, 1001], repeat=[1, 1], **kwargs):
super(ImageTexture, self).__init__()
self.image = image
self.wrap = wrap
self.repeat = repeat
self.properties = kwargs
def lower(self, object_data):
data = {
u"uuid": self.uuid,
u"wrap": self.wrap,
u"repeat": self.repeat,
u"image": self.image.lower_in_object(object_data)
}
data.update(self.properties)
return data
class GenericMaterial(Material):
def __init__(self, properties):
self.properties = properties
self.uuid = str(uuid.uuid1())
def lower(self, object_data):
data = {u"uuid": self.uuid}
data.update(self.properties)
if u"map" in data:
texture = data[u"map"]
data[u"map"] = texture.lower_in_object(object_data)
return data
class Object(SceneElement):
def __init__(self, geometry, material=MeshPhongMaterial()):
super(Object, self).__init__()
self.geometry = geometry
self.material = material
def lower(self):
data = {
u"metadata": {
u"version": 4.5,
u"type": u"Object",
},
u"geometries": [],
u"materials": [],
u"object": {
u"uuid": self.uuid,
u"type": self._type,
u"geometry": self.geometry.uuid,
u"material": self.material.uuid,
u"matrix": list(self.geometry.intrinsic_transform().flatten())
}
}
self.geometry.lower_in_object(data)
self.material.lower_in_object(data)
return data
class Mesh(Object):
_type = u"Mesh"
def item_size(array):
if array.ndim == 1:
return 1
elif array.ndim == 2:
return array.shape[0]
else:
raise ValueError("I can only pack 1- or 2-dimensional numpy arrays, but this one has {:d} dimensions".format(array.ndim))
def threejs_type(dtype):
if dtype == np.uint8:
return u"Uint8Array", 0x12
elif dtype == np.int32:
return u"Int32Array", 0x15
elif dtype == np.uint32:
return u"Uint32Array", 0x16
elif dtype == np.float32:
return u"Float32Array", 0x17
else:
raise ValueError("Unsupported datatype: " + str(dtype))
def pack_numpy_array(x):
if x.dtype == np.float64:
x = x.astype(np.float32)
typename, extcode = threejs_type(x.dtype)
return {
u"itemSize": item_size(x),
u"type": typename,
u"array": umsgpack.Ext(extcode, x.tobytes('F')),
u"normalized": False
}
class MeshGeometry(Geometry):
def __init__(self, contents, mesh_format):
super(MeshGeometry, self).__init__()
self.contents = contents
self.mesh_format = mesh_format
def lower(self, object_data):
return {
u"type": u"_meshfile",
u"uuid": self.uuid,
u"format": self.mesh_format,
u"data": self.contents
}
class ObjMeshGeometry(MeshGeometry):
def __init__(self, contents):
super(ObjMeshGeometry, self, contents, u"obj").__init__()
@staticmethod
def from_file(fname):
with open(fname, "r") as f:
return MeshGeometry(f.read(), u"obj")
class DaeMeshGeometry(MeshGeometry):
def __init__(self, contents):
super(DaeMeshGeometry, self, contents, u"dae").__init__()
@staticmethod
def from_file(fname):
with open(fname, "r") as f:
return MeshGeometry(f.read(), u"dae")
class StlMeshGeometry(MeshGeometry):
def __init__(self, contents):
super(StlMeshGeometry, self, contents, u"stl").__init__()
@staticmethod
def from_file(fname):
with open(fname, "rb") as f:
arr = np.frombuffer(f.read(), dtype=np.uint8)
_, extcode = threejs_type(np.uint8)
encoded = umsgpack.Ext(extcode, arr.tobytes())
return MeshGeometry(encoded, u"stl")
class PointsGeometry(Geometry):
def __init__(self, position, color=None):
super(PointsGeometry, self).__init__()
self.position = position
self.color = color
def lower(self, object_data):
attrs = {u"position": pack_numpy_array(self.position)}
if self.color is not None:
attrs[u"color"] = pack_numpy_array(self.color)
return {
u"uuid": self.uuid,
u"type": u"BufferGeometry",
u"data": {
u"attributes": attrs
}
}
class PointsMaterial(Material):
def __init__(self, size=0.001, color=0xffffff):
super(PointsMaterial, self).__init__()
self.size = size
self.color = color
def lower(self, object_data):
return {
u"uuid": self.uuid,
u"type": u"PointsMaterial",
u"color": self.color,
u"size": self.size,
u"vertexColors": 2
}
class Points(Object):
_type = u"Points"
def PointCloud(position, color, **kwargs):
return Points(
PointsGeometry(position, color),
PointsMaterial(**kwargs)
)
def SceneText(text, width=10, height=10, **kwargs):
return Mesh(
Plane(width=width,height=height),
MeshPhongMaterial(map=TextTexture(text,**kwargs),transparent=True,
needsUpdate=True)
)
class Line(Object):
_type = u"Line"
class LineSegments(Object):
_type = u"LineSegments"
class LineLoop(Object):
_type = u"LineLoop"