This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
base.pyx
2882 lines (2351 loc) · 97.6 KB
/
base.pyx
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
r"""
Base Classes for 3D Graphics Objects and Plotting
AUTHORS:
- Robert Bradshaw (2007-02): initial version
- Robert Bradshaw (2007-08): Cythonization, much optimization
- William Stein (2008)
- Paul Masson (2016): Three.js support
.. TODO::
finish integrating tachyon -- good default lights, camera
"""
#*****************************************************************************
# Copyright (C) 2007 Robert Bradshaw <robertwb@math.washington.edu>
#
# Distributed under the terms of the GNU General Public License (GPL)
#
# This code 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
# General Public License for more details.
#
# The full text of the GPL is available at:
#
# http://www.gnu.org/licenses/
#*****************************************************************************
from __future__ import print_function, absolute_import
from cpython.list cimport *
from cpython.object cimport PyObject
import os
from functools import reduce
from random import randint
import zipfile
from six.moves import cStringIO as StringIO
from sage.misc.misc import sage_makedirs
from sage.env import SAGE_LOCAL
from sage.doctest import DOCTEST_MODE
from sage.misc.fast_methods cimport hash_by_id
from sage.modules.free_module_element import vector
from sage.rings.real_double import RDF
from sage.misc.temporary_file import tmp_filename
from .texture import Texture, is_Texture
from .transform cimport Transformation, point_c, face_c
include "point_c.pxi"
from sage.interfaces.tachyon import tachyon_rt
from libc.math cimport INFINITY
default_texture = Texture()
pi = RDF.pi()
cdef class Graphics3d(SageObject):
"""
This is the baseclass for all 3d graphics objects.
.. automethod:: __add__
.. automethod:: _rich_repr_
"""
def __cinit__(self):
"""
The Cython constructor
EXAMPLES::
sage: gfx = sage.plot.plot3d.base.Graphics3d()
sage: gfx._extra_kwds
{}
"""
self._extra_kwds = dict()
def __hash__(self):
r"""
TESTS::
sage: from sage.plot.plot3d.base import Graphics3d
sage: hash(Graphics3d()) # random
140658972348064
"""
return hash_by_id(<void *> self)
def _repr_(self):
"""
Return a string representation.
OUTPUT:
String.
EXAMPLES::
sage: S = sphere((0, 0, 0), 1)
sage: print(S)
Graphics3d Object
"""
return str(self)
def _rich_repr_(self, display_manager, **kwds):
"""
Rich Output Magic Method
See :mod:`sage.repl.rich_output` for details.
EXAMPLES::
sage: from sage.repl.rich_output import get_display_manager
sage: dm = get_display_manager()
sage: g = sphere()
sage: g._rich_repr_(dm)
OutputSceneJmol container
"""
### First, figure out the best graphics format
types = display_manager.types
can_view_jmol = (types.OutputSceneJmol in display_manager.supported_output())
can_view_canvas3d = (types.OutputSceneCanvas3d in display_manager.supported_output())
can_view_wavefront = (types.OutputSceneWavefront in display_manager.supported_output())
can_view_threejs = (types.OutputSceneThreejs in display_manager.supported_output())
opts = self._process_viewing_options(kwds)
viewer = opts.get('viewer', None)
# make sure viewer is one of the supported options
if viewer not in [None, 'jmol', 'tachyon', 'canvas3d', 'wavefront', 'threejs']:
import warnings
warnings.warn('viewer={} is not supported'.format(viewer))
viewer = None
# select suitable default
if viewer is None:
viewer = 'jmol'
# fall back to 2d image if necessary
if viewer == 'canvas3d' and not can_view_canvas3d: viewer = 'jmol'
if viewer == 'wavefront' and not can_view_wavefront: viewer = 'jmol'
if viewer == 'threejs' and not can_view_threejs: viewer = 'jmol'
if viewer == 'jmol' and not can_view_jmol: viewer = 'tachyon'
### Second, return the corresponding graphics file
if viewer == 'jmol':
return self._rich_repr_jmol(**opts)
elif viewer == 'tachyon':
preferred = (
types.OutputImagePng,
types.OutputImageJpg,
types.OutputImageGif,
)
for output_container in preferred:
if output_container in display_manager.supported_output():
return self._rich_repr_tachyon(output_container, **opts)
elif viewer == 'canvas3d':
return self._rich_repr_canvas3d(**opts)
elif viewer == 'wavefront':
return self._rich_repr_wavefront(**opts)
elif viewer == 'threejs':
return self._rich_repr_threejs(**opts)
else:
assert False # unreachable
def _rich_repr_tachyon(self, output_container, **kwds):
"""
Rich Representation using Tachyon.
INPUT:
- ``output_container`` -- the rich output container to contain
the rendered image (can be png, gif, or jpg). Determines the
type of the output.
- ``**kwds`` -- Optional keyword arguments are passed to the
Tachyon raytracer.
OUTPUT:
Instance of
:class:`~sage.repl.rich_output.output_graphics.OutputImagePng`,
:class:`~sage.repl.rich_output.output_graphics.OutputImageGif`, or
:class:`~sage.repl.rich_output.output_graphics.OutputImageJpg`.
EXAMPLES::
sage: import sage.repl.rich_output.output_catalog as catalog
sage: sphere()._rich_repr_tachyon(catalog.OutputImagePng)
OutputImagePng container
sage: import sage.repl.rich_output.output_catalog as catalog
sage: sphere()._rich_repr_tachyon(catalog.OutputImageJpg) # optional -- libjpeg
OutputImageJpg container
"""
filename = tmp_filename(ext='.png')
opts = self._process_viewing_options(kwds)
T = self._prepare_for_tachyon(
opts['frame'], opts['axes'], opts['frame_aspect_ratio'],
opts['aspect_ratio'], opts['zoom']
)
x, y = opts['figsize'][0]*100, opts['figsize'][1]*100
if DOCTEST_MODE:
x, y = 10, 10
tachyon_rt(T.tachyon(), filename, opts['verbosity'],
'-res %s %s' % (x, y))
from sage.repl.rich_output.buffer import OutputBuffer
import sage.repl.rich_output.output_catalog as catalog
import PIL.Image as Image
if output_container is catalog.OutputImagePng:
buf = OutputBuffer.from_file(filename)
elif output_container is catalog.OutputImageGif:
gif = tmp_filename(ext='.gif')
Image.open(filename).save(gif)
buf = OutputBuffer.from_file(gif)
elif output_container is catalog.OutputImageJpg:
jpg = tmp_filename(ext='.jpg')
Image.open(filename).save(jpg)
buf = OutputBuffer.from_file(jpg)
else:
raise ValueError('output_container not supported')
return output_container(buf)
def _rich_repr_jmol(self, **kwds):
"""
Rich Representation as JMol scene
INPUT:
Optional keyword arguments are passed to JMol.
OUTPUT:
Instance of
:class:`sage.repl.rich_output.output_graphics3d.OutputSceneJmol`.
EXAMPLES::
sage: sphere()._rich_repr_jmol()
OutputSceneJmol container
"""
from sage.misc.temporary_file import tmp_dir
root_dir = os.path.abspath(tmp_dir())
scene_zip = os.path.join(root_dir, 'scene.spt.zip')
preview_png = os.path.join(root_dir, 'preview.png')
opts = self._process_viewing_options(kwds)
zoom = opts['zoom']
T = self._prepare_for_jmol(
opts['frame'],
opts['axes'],
opts['frame_aspect_ratio'],
opts['aspect_ratio'],
zoom,
)
T.export_jmol(scene_zip, **opts)
from sage.interfaces.jmoldata import JmolData
jdata = JmolData()
if not jdata.is_jvm_available():
# We can only use JMol to generate preview if a jvm is installed
from sage.repl.rich_output.output_graphics import OutputImagePng
tachyon = self._rich_repr_tachyon(OutputImagePng, **opts)
tachyon.png.save_as(preview_png)
else:
# Java needs absolute paths
# On cygwin, they should be native ones
scene_native = scene_zip
import sys
if sys.platform == 'cygwin':
from subprocess import check_output, STDOUT
scene_native = check_output(['cygpath', '-w', scene_native],
stderr=STDOUT).rstrip()
script = '''set defaultdirectory "{0}"\nscript SCRIPT\n'''.format(scene_native)
jdata.export_image(targetfile=preview_png, datafile=script,
image_type="PNG",
figsize=opts['figsize'][0])
from sage.repl.rich_output.output_graphics3d import OutputSceneJmol
from sage.repl.rich_output.buffer import OutputBuffer
scene_zip = OutputBuffer.from_file(scene_zip)
preview_png = OutputBuffer.from_file(preview_png)
return OutputSceneJmol(scene_zip, preview_png)
def _rich_repr_wavefront(self, **kwds):
r"""
Rich Representation as Wavefront (obj + mtl) Scene
INPUT:
Optional keyword arguments are ignored.
OUTPUT:
Instance of
:class:`sage.repl.rich_output.output_graphics3d.OutputSceneWavefront`.
EXAMPLES::
sage: line = line3d([(0,0,0), (1,1,1)])
sage: out = line._rich_repr_wavefront()
sage: out
OutputSceneWavefront container
sage: out.obj.get()
'mtllib ... 6 2 7 11\nf 7 8 12\nf 8 9 12\nf 9 10 12\nf 10 11 12\nf 11 7 12\n'
sage: out.mtl.get()
'newmtl texture...\nKd 0.4 0.4 1.0\nKs 0.0 0.0 0.0\nillum 1\nNs 1.0\nd 1.0\n'
"""
from sage.repl.rich_output.output_graphics3d import OutputSceneWavefront
from sage.repl.rich_output.buffer import OutputBuffer
obj = OutputBuffer('mtllib scene.mtl\n' + self.obj())
return OutputSceneWavefront(obj, self.mtl_str())
def _rich_repr_canvas3d(self, **kwds):
r"""
Rich Representation as Canvas3D Scene
INPUT:
Optional keyword arguments.
OUTPUT:
Instance of
:class:`sage.repl.rich_output.output_graphics3d.OutputSceneCanvas3d`.
EXAMPLES::
sage: out = sphere()._rich_repr_canvas3d()
sage: out
OutputSceneCanvas3d container
sage: out.canvas3d.get()
'[{"vertices":[{"x":0,"y":0,"z":-1},..., "color":"#6666ff", "opacity":1}]'
"""
opts = self._process_viewing_options(kwds)
aspect_ratio = opts['aspect_ratio'] # this necessarily has a value now
frame_aspect_ratio = opts['frame_aspect_ratio']
zoom = opts['zoom']
frame = opts['frame']
axes = opts['axes']
T = self._prepare_for_tachyon(frame, axes, frame_aspect_ratio, aspect_ratio, zoom)
data = flatten_list(T.json_repr(T.default_render_params()))
canvas3d = '[' + ','.join(data) + ']'
from sage.repl.rich_output.output_catalog import OutputSceneCanvas3d
return OutputSceneCanvas3d(canvas3d)
def _rich_repr_threejs(self, **kwds):
r"""
Rich Representation as Three.js Scene
INPUT:
Optional keyword arguments.
OUTPUT:
Instance of
:class:`sage.repl.rich_output.output_graphics3d.OutputSceneThreejs`.
EXAMPLES::
sage: sphere(online=True)._rich_repr_threejs()
OutputSceneThreejs container
"""
options = self._process_viewing_options(kwds)
# Threejs specific options
options.setdefault('axes_labels', ['x','y','z'])
options.setdefault('decimals', 2)
options.setdefault('online', False)
# Normalization of options values for proper JSONing
options['aspect_ratio'] = [float(i) for i in options['aspect_ratio']]
options['decimals'] = int(options['decimals'])
if not options['frame']:
options['axes_labels'] = False
from sage.repl.rich_output import get_display_manager
scripts = get_display_manager().threejs_scripts(options['online'])
b = self.bounding_box()
bounds = '[{{"x":{}, "y":{}, "z":{}}}, {{"x":{}, "y":{}, "z":{}}}]'.format(
b[0][0], b[0][1], b[0][2], b[1][0], b[1][1], b[1][2])
from sage.plot.colors import Color
lights = '[{{"x":-5, "y":3, "z":0, "color":"{}", "parent":"camera"}}]'.format(
Color(.5,.5,.5).html_color())
ambient = '{{"color":"{}"}}'.format(Color(.5,.5,.5).html_color())
import json
points, lines, texts = [], [], []
if not hasattr(self, 'all'):
self += Graphics3d()
for p in self.flatten().all:
if hasattr(p, 'loc'):
color = p._extra_kwds.get('color', 'blue')
opacity = p._extra_kwds.get('opacity', 1)
points.append('{{"point":{}, "size":{}, "color":"{}", "opacity":{}}}'.format(
json.dumps(p.loc), p.size, color, opacity))
if hasattr(p, 'points'):
color = p._extra_kwds.get('color', 'blue')
opacity = p._extra_kwds.get('opacity', 1)
thickness = p._extra_kwds.get('thickness', 1)
lines.append('{{"points":{}, "color":"{}", "opacity":{}, "linewidth":{}}}'.format(
json.dumps(p.points), color, opacity, thickness))
if hasattr(p, '_trans'):
if hasattr(p.all[0], 'string'):
m = p.get_transformation().get_matrix()
texts.append('{{"text":"{}", "x":{}, "y":{}, "z":{}}}'.format(
p.all[0].string, m[0,3], m[1,3], m[2,3]))
points = '[' + ','.join(points) + ']'
lines = '[' + ','.join(lines) + ']'
texts = '[' + ','.join(texts) + ']'
surfaces = self.json_repr(self.default_render_params())
surfaces = flatten_list(surfaces)
surfaces = '[' + ','.join(surfaces) + ']'
from sage.env import SAGE_EXTCODE
with open(os.path.join(
SAGE_EXTCODE, 'threejs', 'threejs_template.html')) as f:
html = f.read()
html = html.replace('SAGE_SCRIPTS', scripts)
js_options = dict((key, options[key]) for key in
['aspect_ratio', 'axes', 'axes_labels', 'decimals', 'frame'])
html = html.replace('SAGE_OPTIONS', json.dumps(js_options))
html = html.replace('SAGE_BOUNDS', bounds)
html = html.replace('SAGE_LIGHTS', lights)
html = html.replace('SAGE_AMBIENT', ambient)
html = html.replace('SAGE_TEXTS', str(texts))
html = html.replace('SAGE_POINTS', str(points))
html = html.replace('SAGE_LINES', str(lines))
html = html.replace('SAGE_SURFACES', str(surfaces))
from sage.repl.rich_output.output_catalog import OutputSceneThreejs
return OutputSceneThreejs(html);
def __str__(self):
"""
EXAMPLES::
sage: S = sphere((0, 0, 0), 1)
sage: str(S)
'Graphics3d Object'
"""
return "Graphics3d Object"
def __add__(left, right):
"""
Addition of objects adds them to the same scene.
EXAMPLES::
sage: A = sphere((0,0,0), 1, color='red')
sage: B = dodecahedron((2, 0, 0), color='yellow')
sage: A+B
Graphics3d Object
For convenience, we take 0 and ``None`` to be the additive identity::
sage: A + 0 is A
True
sage: A + None is A, 0 + A is A, None + A is A
(True, True, True)
In particular, this allows us to use the sum() function without
having to provide an empty starting object::
sage: sum(point3d((cos(n), sin(n), n)) for n in [0..10, step=.1])
Graphics3d Object
A Graphics 3d object can also be added a 2d graphic object::
sage: A = sphere((0, 0, 0), 1) + circle((0, 0), 1.5)
sage: A.show(aspect_ratio=1)
"""
if right == 0 or right is None:
return left
elif left == 0 or left is None:
return right
elif not isinstance(left, Graphics3d):
left = left.plot3d()
elif not isinstance(right, Graphics3d):
right = right.plot3d()
return Graphics3dGroup([left, right])
def _set_extra_kwds(self, kwds):
"""
Allow one to pass rendering arguments on as if they were set
in the constructor.
EXAMPLES::
sage: S = sphere((0, 0, 0), 1)
sage: S._set_extra_kwds({'aspect_ratio': [1, 2, 2]})
sage: S
Graphics3d Object
"""
self._extra_kwds = kwds
def aspect_ratio(self, v=None):
"""
Set or get the preferred aspect ratio of ``self``.
INPUT:
- ``v`` -- (default: ``None``) must be a list or tuple of length three,
or the integer ``1``. If no arguments are provided then the
default aspect ratio is returned.
EXAMPLES::
sage: D = dodecahedron()
sage: D.aspect_ratio()
[1.0, 1.0, 1.0]
sage: D.aspect_ratio([1,2,3])
sage: D.aspect_ratio()
[1.0, 2.0, 3.0]
sage: D.aspect_ratio(1)
sage: D.aspect_ratio()
[1.0, 1.0, 1.0]
"""
if not v is None:
if v == 1:
v = (1,1,1)
if not isinstance(v, (tuple, list)):
raise TypeError("aspect_ratio must be a list or tuple of "
"length 3 or the integer 1")
self._aspect_ratio = map(float, v)
else:
if self._aspect_ratio is None:
self._aspect_ratio = [1.0,1.0,1.0]
return self._aspect_ratio
def frame_aspect_ratio(self, v=None):
"""
Set or get the preferred frame aspect ratio of ``self``.
INPUT:
- ``v`` -- (default: ``None``) must be a list or tuple of
length three, or the integer ``1``. If no arguments are
provided then the default frame aspect ratio is returned.
EXAMPLES::
sage: D = dodecahedron()
sage: D.frame_aspect_ratio()
[1.0, 1.0, 1.0]
sage: D.frame_aspect_ratio([2,2,1])
sage: D.frame_aspect_ratio()
[2.0, 2.0, 1.0]
sage: D.frame_aspect_ratio(1)
sage: D.frame_aspect_ratio()
[1.0, 1.0, 1.0]
"""
if not v is None:
if v == 1:
v = (1,1,1)
if not isinstance(v, (tuple, list)):
raise TypeError("frame_aspect_ratio must be a list or tuple of "
"length 3 or the integer 1")
self._frame_aspect_ratio = map(float, v)
else:
if self._frame_aspect_ratio is None:
self._frame_aspect_ratio = [1.0,1.0,1.0]
return self._frame_aspect_ratio
def _determine_frame_aspect_ratio(self, aspect_ratio):
a_min, a_max = self._safe_bounding_box()
return [(a_max[i] - a_min[i])*aspect_ratio[i] for i in range(3)]
def _safe_bounding_box(self):
"""
Return a bounding box but where no side length is 0.
This is used to avoid zero-division errors for pathological
plots.
EXAMPLES::
sage: G = line3d([(0, 0, 0), (0, 0, 1)])
sage: G.bounding_box()
((0.0, 0.0, 0.0), (0.0, 0.0, 1.0))
sage: G._safe_bounding_box()
([-1.0, -1.0, 0.0], [1.0, 1.0, 1.0])
"""
a_min, a_max = self.bounding_box()
a_min = list(a_min); a_max = list(a_max)
for i in range(3):
if a_min[i] == a_max[i]:
a_min[i] = a_min[i] - 1
a_max[i] = a_max[i] + 1
return a_min, a_max
def bounding_box(self):
"""
Return the lower and upper corners of a 3d bounding box for ``self``.
This is used for rendering and ``self`` should fit entirely
within this box.
Specifically, the first point returned should have x, y, and z
coordinates should be the respective infimum over all points
in ``self``, and the second point is the supremum.
The default return value is simply the box containing the origin.
EXAMPLES::
sage: sphere((1,1,1), 2).bounding_box()
((-1.0, -1.0, -1.0), (3.0, 3.0, 3.0))
sage: G = line3d([(1, 2, 3), (-1,-2,-3)])
sage: G.bounding_box()
((-1.0, -2.0, -3.0), (1.0, 2.0, 3.0))
"""
return ((0.0, 0.0, 0.0), (0.0, 0.0, 0.0))
def transform(self, **kwds):
"""
Apply a transformation to ``self``, where the inputs are
passed onto a TransformGroup object.
Mostly for internal use; see the translate, scale, and rotate
methods for more details.
EXAMPLES::
sage: sphere((0,0,0), 1).transform(trans=(1, 0, 0), scale=(2,3,4)).bounding_box()
((-1.0, -3.0, -4.0), (3.0, 3.0, 4.0))
"""
return TransformGroup([self], **kwds)
def translate(self, *x):
"""
Return ``self`` translated by the given vector (which can be
given either as a 3-iterable or via positional arguments).
EXAMPLES::
sage: icosahedron() + sum(icosahedron(opacity=0.25).translate(2*n, 0, 0) for n in [1..4])
Graphics3d Object
sage: icosahedron() + sum(icosahedron(opacity=0.25).translate([-2*n, n, n^2]) for n in [1..4])
Graphics3d Object
TESTS::
sage: G = sphere((0, 0, 0), 1)
sage: G.bounding_box()
((-1.0, -1.0, -1.0), (1.0, 1.0, 1.0))
sage: G.translate(0, 0, 1).bounding_box()
((-1.0, -1.0, 0.0), (1.0, 1.0, 2.0))
sage: G.translate(-1, 5, 0).bounding_box()
((-2.0, 4.0, -1.0), (0.0, 6.0, 1.0))
"""
if len(x) == 1:
x = x[0]
return self.transform(trans=x)
def scale(self, *x):
"""
Return ``self`` scaled in the x, y, and z directions.
EXAMPLES::
sage: G = dodecahedron() + dodecahedron(opacity=.5).scale(2)
sage: G.show(aspect_ratio=1)
sage: G = icosahedron() + icosahedron(opacity=.5).scale([1, 1/2, 2])
sage: G.show(aspect_ratio=1)
TESTS::
sage: G = sphere((0, 0, 0), 1)
sage: G.scale(2)
Graphics3d Object
sage: G.scale(1, 2, 1/2).show(aspect_ratio=1)
sage: G.scale(2).bounding_box()
((-2.0, -2.0, -2.0), (2.0, 2.0, 2.0))
"""
if isinstance(x[0], (tuple, list)):
x = x[0]
return self.transform(scale=x)
def rotate(self, v, theta):
r"""
Return ``self`` rotated about the vector `v` by `\theta` radians.
EXAMPLES::
sage: from sage.plot.plot3d.shapes import Cone
sage: v = (1,2,3)
sage: G = arrow3d((0, 0, 0), v)
sage: G += Cone(1/5, 1).translate((0, 0, 2))
sage: C = Cone(1/5, 1, opacity=.25).translate((0, 0, 2))
sage: G += sum(C.rotate(v, pi*t/4) for t in [1..7])
sage: G.show(aspect_ratio=1)
sage: from sage.plot.plot3d.shapes import Box
sage: Box(1/3, 1/5, 1/7).rotate((1, 1, 1), pi/3).show(aspect_ratio=1)
"""
vx, vy, vz = v
return self.transform(rot=[vx, vy, vz, theta])
def rotateX(self, theta):
"""
Return ``self`` rotated about the `x`-axis by the given angle.
EXAMPLES::
sage: from sage.plot.plot3d.shapes import Cone
sage: G = Cone(1/5, 1) + Cone(1/5, 1, opacity=.25).rotateX(pi/2)
sage: G.show(aspect_ratio=1)
"""
return self.rotate((1, 0, 0), theta)
def rotateY(self, theta):
"""
Return ``self`` rotated about the `y`-axis by the given angle.
EXAMPLES::
sage: from sage.plot.plot3d.shapes import Cone
sage: G = Cone(1/5, 1) + Cone(1/5, 1, opacity=.25).rotateY(pi/3)
sage: G.show(aspect_ratio=1)
"""
return self.rotate((0, 1, 0), theta)
def rotateZ(self, theta):
"""
Return ``self`` rotated about the `z`-axis by the given angle.
EXAMPLES::
sage: from sage.plot.plot3d.shapes import Box
sage: G = Box(1/2, 1/3, 1/5) + Box(1/2, 1/3, 1/5, opacity=.25).rotateZ(pi/5)
sage: G.show(aspect_ratio=1)
"""
return self.rotate((0, 0, 1), theta)
def viewpoint(self):
"""
Return the viewpoint of this plot.
Currently only a stub for x3d.
EXAMPLES::
sage: type(dodecahedron().viewpoint())
<class 'sage.plot.plot3d.base.Viewpoint'>
"""
# This should probably be reworked somehow.
return Viewpoint(0,0,6)
def default_render_params(self):
"""
Return an instance of RenderParams suitable for plotting this object.
EXAMPLES::
sage: type(dodecahedron().default_render_params())
<class 'sage.plot.plot3d.base.RenderParams'>
"""
return RenderParams(ds=.075)
def testing_render_params(self):
"""
Return an instance of RenderParams suitable for testing this object.
In particular, it opens up '/dev/null' as an auxiliary zip
file for jmol.
EXAMPLES::
sage: type(dodecahedron().testing_render_params())
<class 'sage.plot.plot3d.base.RenderParams'>
"""
params = RenderParams(ds=.075)
params.output_archive = zipfile.ZipFile('/dev/null', 'w', zipfile.ZIP_STORED, True)
return params
def x3d(self):
"""
An x3d scene file (as a string) containing the this object.
EXAMPLES::
sage: print(sphere((1, 2, 3), 5).x3d())
<X3D version='3.0' profile='Immersive' xmlns:xsd='http://www.w3.org/2001/XMLSchema-instance' xsd:noNamespaceSchemaLocation=' http://www.web3d.org/specifications/x3d-3.0.xsd '>
<head>
<meta name='title' content='sage3d'/>
</head>
<Scene>
<Viewpoint position='0 0 6'/>
<Transform translation='1 2 3'>
<Shape><Sphere radius='5.0'/><Appearance><Material diffuseColor='0.4 0.4 1.0' shininess='1.0' specularColor='0.0 0.0 0.0'/></Appearance></Shape>
</Transform>
</Scene>
</X3D>
sage: G = icosahedron() + sphere((0,0,0), 0.5, color='red')
sage: print(G.x3d())
<X3D version='3.0' profile='Immersive' xmlns:xsd='http://www.w3.org/2001/XMLSchema-instance' xsd:noNamespaceSchemaLocation=' http://www.web3d.org/specifications/x3d-3.0.xsd '>
<head>
<meta name='title' content='sage3d'/>
</head>
<Scene>
<Viewpoint position='0 0 6'/>
<Shape>
<IndexedFaceSet coordIndex='...'>
<Coordinate point='...'/>
</IndexedFaceSet>
<Appearance><Material diffuseColor='0.4 0.4 1.0' shininess='1.0' specularColor='0.0 0.0 0.0'/></Appearance></Shape>
<Transform translation='0 0 0'>
<Shape><Sphere radius='0.5'/><Appearance><Material diffuseColor='1.0 0.0 0.0' shininess='1.0' specularColor='0.0 0.0 0.0'/></Appearance></Shape>
</Transform>
</Scene>
</X3D>
"""
return """
<X3D version='3.0' profile='Immersive' xmlns:xsd='http://www.w3.org/2001/XMLSchema-instance' xsd:noNamespaceSchemaLocation=' http://www.web3d.org/specifications/x3d-3.0.xsd '>
<head>
<meta name='title' content='sage3d'/>
</head>
<Scene>
%s
%s
</Scene>
</X3D>
"""%(self.viewpoint().x3d_str(), self.x3d_str())
def tachyon(self):
"""
An tachyon input file (as a string) containing the this object.
EXAMPLES::
sage: print(sphere((1, 2, 3), 5, color='yellow').tachyon())
begin_scene
resolution 400 400
camera
...
plane
center -2000 -1000 -500
normal 2.3 2.4 2.0
TEXTURE
AMBIENT 1.0 DIFFUSE 1.0 SPECULAR 1.0 OPACITY 1.0
COLOR 1.0 1.0 1.0
TEXFUNC 0
Texdef texture...
Ambient 0.333333333333 Diffuse 0.666666666667 Specular 0.0 Opacity 1.0
Color 1.0 1.0 0.0
TexFunc 0
Sphere center 1.0 -2.0 3.0 Rad 5.0 texture...
end_scene
sage: G = icosahedron(color='red') + sphere((1,2,3), 0.5, color='yellow')
sage: G.show(viewer='tachyon', frame=false)
sage: print(G.tachyon())
begin_scene
...
Texdef texture...
Ambient 0.333333333333 Diffuse 0.666666666667 Specular 0.0 Opacity 1.0
Color 1.0 1.0 0.0
TexFunc 0
TRI V0 ...
Sphere center 1.0 -2.0 3.0 Rad 0.5 texture...
end_scene
"""
render_params = self.default_render_params()
# switch from LH to RH coords to be consistent with java rendition
render_params.push_transform(Transformation(scale=[1,-1,1]))
return """
begin_scene
resolution 400 400
camera
zoom 1.0
aspectratio 1.0
antialiasing %s
raydepth 8
center 2.3 2.4 2.0
viewdir -2.3 -2.4 -2.0
updir 0.0 0.0 1.0
end_camera
light center 4.0 3.0 2.0
rad 0.2
color 1.0 1.0 1.0
plane
center -2000 -1000 -500
normal 2.3 2.4 2.0
TEXTURE
AMBIENT 1.0 DIFFUSE 1.0 SPECULAR 1.0 OPACITY 1.0
COLOR 1.0 1.0 1.0
TEXFUNC 0
%s
%s
end_scene""" % (render_params.antialiasing,
"\n".join(sorted([t.tachyon_str() for t in self.texture_set()])),
"\n".join(flatten_list(self.tachyon_repr(render_params))))
def obj(self):
"""
An .obj scene file (as a string) containing the this object.
A .mtl file of the same name must also be produced for
coloring.
EXAMPLES::
sage: from sage.plot.plot3d.shapes import ColorCube
sage: print(ColorCube(1, ['red', 'yellow', 'blue']).obj())
g obj_1
usemtl ...
v 1 1 1
v -1 1 1
v -1 -1 1
v 1 -1 1
f 1 2 3 4
...
g obj_6
usemtl ...
v -1 -1 1
v -1 1 1
v -1 1 -1
v -1 -1 -1
f 21 22 23 24
"""
return "\n".join(flatten_list([self.obj_repr(self.default_render_params()), ""]))
def export_jmol(self, filename='jmol_shape.jmol', force_reload=False,
zoom=1, spin=False, background=(1,1,1), stereo=False,
mesh=False, dots=False,
perspective_depth = True,
orientation = (-764,-346,-545,76.39), **ignored_kwds):
# orientation chosen to look same as tachyon
"""
A jmol scene consists of a script which refers to external files.
Fortunately, we are able to put all of them in a single zip archive,
which is the output of this call.
EXAMPLES::
sage: out_file = tmp_filename(ext=".jmol")
sage: G = sphere((1, 2, 3), 5) + cube() + sage.plot.plot3d.shapes.Text("hi")
sage: G.export_jmol(out_file)
sage: import zipfile
sage: z = zipfile.ZipFile(out_file)
sage: z.namelist()
['obj_...pmesh', 'SCRIPT']
sage: print(z.read('SCRIPT'))
data "model list"
2
empty
Xx 0 0 0
Xx 5.5 5.5 5.5
end "model list"; show data
select *
wireframe off; spacefill off
set labelOffset 0 0
background [255,255,255]
spin OFF
moveto 0 -764 -346 -545 76.39
centerAt absolute {0 0 0}
zoom 100
frank OFF
set perspectivedepth ON
isosurface sphere_1 center {1.0 2.0 3.0} sphere 5.0
color isosurface [102,102,255]
pmesh obj_... "obj_...pmesh"
color pmesh [102,102,255]
select atomno = 1
color atom [102,102,255]
label "hi"
isosurface fullylit; pmesh o* fullylit; set antialiasdisplay on;
sage: print(z.read(z.namelist()[0]))
24
0.5 0.5 0.5
-0.5 0.5 0.5
...
-0.5 -0.5 -0.5
6
5
0
1
...
"""
render_params = self.default_render_params()
render_params.mesh = mesh
render_params.dots = dots
render_params.output_file = filename
render_params.force_reload = render_params.randomize_counter = force_reload
render_params.output_archive = zipfile.ZipFile(filename, 'w', zipfile.ZIP_DEFLATED, True)
# Render the data