1#!/usr/local/bin/python3.8
2# coding=utf-8
3#
4# Copyright (C) 2009 John Beard john.j.beard@gmail.com
5#
6# This program is free software; you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation; either version 2 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program; if not, write to the Free Software
18# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19#
20"""
21This extension renders a wireframe sphere constructed from lines of latitude
22and lines of longitude.
23
24The number of lines of latitude and longitude is independently variable. Lines
25of latitude and longtude are in separate subgroups. The whole figure is also in
26its own group.
27
28The whole sphere can be tilted towards or away from the veiwer by a given
29number of degrees. If the whole sphere is then rotated normally in Inkscape,
30any position can be achieved.
31
32There is an option to hide the lines at the back of the sphere, as if the
33sphere were opaque.
34"""
35# FIXME: Lines of latitude only have an approximation of the function needed
36#            to hide the back portion. If you can derive the proper equation,
37#            please add it in.
38#            Line of longitude have the exact method already.
39#            Workaround: Use the Inkscape ellipse tool to edit the start and end
40#            points of the lines of latitude to end at the horizon circle.
41#
42# TODO:  Add support for odd numbers of lines of longitude. This means breaking
43#        the line at the poles, and having two half ellipses for each line.
44#        The angles at which the ellipse arcs pass the poles are not constant and
45#        need to be derived before this can be implemented.
46# TODO:  Add support for prolate and oblate spheroids
47#
48#    0.10    2009-10-25  First version. Basic spheres supported.
49#                        Hidden lines of latitude still not properly calculated.
50#                        Prolate and oblate spheroids not considered.
51
52from math import acos, atan, cos, pi, sin, tan
53
54import inkex
55
56# add a tiny value to the ellipse radii, so that if we get a
57# zero radius, the ellipse still shows up as a line
58EPSILON = 0.001
59
60
61class WireframeSphere(inkex.GenerateExtension):
62    """Writeframe extension, generate a wireframe"""
63    container_label = 'WireframeSphere'
64
65    def container_transform(self):
66        transform = super(WireframeSphere, self).container_transform()
67        if self.options.TILT < 0:
68            transform *= inkex.Transform(scale=(1, -1))
69        return transform
70
71    def add_arguments(self, pars):
72        pars.add_argument("--num_lat", type=int, dest="NUM_LAT", default=19)
73        pars.add_argument("--num_long", type=int, dest="NUM_LONG", default=24)
74        pars.add_argument("--radius", type=float, dest="RADIUS", default=100.0)
75        pars.add_argument("--tilt", type=float, dest="TILT", default=35.0)
76        pars.add_argument("--rotation", type=float, dest="ROT_OFFSET", default=4)
77        pars.add_argument("--hide_back", type=inkex.Boolean, dest="HIDE_BACK", default=False)
78
79    def generate(self):
80        opt = self.options
81
82        # PARAMETER PROCESSING
83        if opt.NUM_LONG % 2 != 0:  # lines of longitude are odd : abort
84            inkex.errormsg('Please enter an even number of lines of longitude.')
85            return
86
87        radius = self.svg.unittouu(str(opt.RADIUS) + 'px')
88        tilt = abs(opt.TILT) * (pi / 180)  # Convert to radians
89        rotate = opt.ROT_OFFSET * pi / 180  # Convert to radians
90
91        # only process longitudes if we actually want some
92        if opt.NUM_LONG > 0:
93            # Yieled elements are added to generated container
94            yield self.longitude_lines(opt.NUM_LONG, tilt, radius, rotate)
95
96        if opt.NUM_LAT > 0:
97            # Yieled elements are added to generated container
98            # Account for the fact that we loop over N-1 elements
99            yield self.latitude_lines(opt.NUM_LAT + 1, tilt, radius)
100
101        # THE HORIZON CIRCLE - circle, centred on the sphere centre
102        yield self.draw_ellipse((radius, radius), (0, 0))
103
104    def longitude_lines(self, number, tilt, radius, rotate):
105        """Add lines of latitude as a group"""
106        # GROUP FOR THE LINES OF LONGITUDE
107        grp_long = inkex.Group()
108        grp_long.set('inkscape:label', 'Lines of Longitude')
109
110        # angle between neighbouring lines of longitude in degrees
111        #delta_long = 360.0 / number
112
113        for i in range(0, number // 2):
114            # The longitude of this particular line in radians
115            long_angle = rotate + (i * (360.0 / number)) * (pi / 180.0)
116            if long_angle > pi:
117                long_angle -= 2 * pi
118            # the rise is scaled by the sine of the tilt
119            # length     = sqrt(width*width+height*height)  #by pythagorean theorem
120            # inverse    = sin(acos(length/so.RADIUS))
121            inverse = abs(sin(long_angle)) * cos(tilt)
122
123            rads = (radius * inverse + EPSILON, radius)
124
125            # The rotation of the ellipse to get it to pass through the pole (degs)
126            rotation = atan(
127                (radius * sin(long_angle) * sin(tilt)) /
128                (radius * cos(long_angle))
129            ) * (180.0 / pi)
130
131            # remove the hidden side of the ellipses if required
132            # this is always exactly half the ellipse, but we need to find out which half
133            start_end = (0, 2 * pi)  # Default start and end angles -> full ellipse
134            if self.options.HIDE_BACK:
135                if long_angle <= pi / 2:  # cut out the half ellispse that is hidden
136                    start_end = (pi / 2, 3 * pi / 2)
137                else:
138                    start_end = (3 * pi / 2, pi / 2)
139
140            # finally, draw the line of longitude
141            # the centre is always at the centre of the sphere
142            elem = grp_long.add(self.draw_ellipse(rads, (0, 0), start_end))
143            # the rotation will be applied about the group centre (the centre of the sphere)
144            elem.transform = inkex.Transform(rotate=(rotation,))
145        return grp_long
146
147    def latitude_lines(self, number, tilt, radius):
148        """Add lines of latitude as a group"""
149        # GROUP FOR THE LINES OF LATITUDE
150        grp_lat = inkex.Group()
151        grp_lat.set('inkscape:label', 'Lines of Latitude')
152
153        # Angle between the line of latitude (subtended at the centre)
154        delta_lat = 180.0 / number
155
156        for i in range(1, number):
157            # The angle of this line of latitude (from a pole)
158            lat_angle = ((delta_lat * i) * (pi / 180))
159
160            # The width of the LoLat (no change due to projection)
161            # The projected height of the line of latitude
162            rads = (
163                radius * sin(lat_angle), # major
164                (radius * sin(lat_angle) * sin(tilt)) + EPSILON, # minor
165            )
166
167            # The x position is the sphere center, The projected y position of the LoLat
168            pos = (0, radius * cos(lat_angle) * cos(tilt))
169
170            if self.options.HIDE_BACK:
171                if lat_angle > tilt:  # this LoLat is partially or fully visible
172                    if lat_angle > pi - tilt:  # this LoLat is fully visible
173                        grp_lat.add(self.draw_ellipse(rads, pos))
174                    else:  # this LoLat is partially visible
175                        proportion = -(acos(tan(lat_angle - pi / 2) \
176                                       / tan(pi / 2 - tilt))) / pi + 1
177                        # make the start and end angles (mirror image around pi/2)
178                        start_end = (pi / 2 - proportion * pi, pi / 2 + proportion * pi)
179                        grp_lat.add(self.draw_ellipse(rads, pos, start_end))
180
181            else:  # just draw the full lines of latitude
182                grp_lat.add(self.draw_ellipse(rads, pos))
183        return grp_lat
184
185    def draw_ellipse(self, r_xy, c_xy, start_end=(0, 2 * pi)):
186        """Creates an elipse with all the required sodipodi attributes"""
187        path = inkex.PathElement()
188        path.update(**{
189            'style': {'stroke': '#000000',
190                      'stroke-width': str(self.svg.unittouu('1px')),
191                      'fill': 'none'},
192            'sodipodi:cx': str(c_xy[0]),
193            'sodipodi:cy': str(c_xy[1]),
194            'sodipodi:rx': str(r_xy[0]),
195            'sodipodi:ry': str(r_xy[1]),
196            'sodipodi:start': str(start_end[0]),
197            'sodipodi:end': str(start_end[1]),
198            'sodipodi:open': 'true',  # all ellipse sectors we will draw are open
199            'sodipodi:type': 'arc',
200            'sodipodi:arc-type': 'arc',
201        })
202        return path
203
204if __name__ == '__main__':
205    WireframeSphere().run()
206