<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alexey Yurasov on Medium]]></title>
        <description><![CDATA[Stories by Alexey Yurasov on Medium]]></description>
        <link>https://medium.com/@alexeyyurasov?source=rss-564d6c446b85------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PkwY25gZlQ-Cqky_nJmOvA.jpeg</url>
            <title>Stories by Alexey Yurasov on Medium</title>
            <link>https://medium.com/@alexeyyurasov?source=rss-564d6c446b85------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 19:11:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexeyyurasov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[3D modeling with Python]]></title>
            <link>https://medium.com/@alexeyyurasov/3d-modeling-with-python-c21296756db2?source=rss-564d6c446b85------2</link>
            <guid isPermaLink="false">https://medium.com/p/c21296756db2</guid>
            <dc:creator><![CDATA[Alexey Yurasov]]></dc:creator>
            <pubDate>Mon, 07 Mar 2022 18:00:32 GMT</pubDate>
            <atom:updated>2022-03-07T18:13:54.327Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XcykDDMVH1mi_agxizxH7g.png" /></figure><p>Imagine that we need to build a three-dimensional model of some object in the python programming language, then visualize it, or prepare a file for printing on a 3D printer. Several libraries are available to solve these problems. Let’s take a look, how to build 3D models from points, edges and primitives in python. How to perform elementary 3D modeling techniques: move, rotate, merge, subtract and others.</p><p><em>This is translation of my </em><a href="https://habr.com/ru/post/572760/"><em>original article</em></a><em>.</em></p><p>We will overview the following libraries:</p><ul><li>numpy-stl</li><li>pymesh</li><li>pytorch3d</li><li>SolidPython</li></ul><p>Using each library, we build a <a href="https://en.wikipedia.org/wiki/Menger_sponge">Menger sponge</a> fractal, save model to stl file and then render the image. Along the way, we briefly learn about data structures and terms.</p><p>All examples are provided for the Linux operating system.</p><p>Code samples can be found in the <a href="https://github.com/format37/python3d">GitHub</a> repository.</p><h4>Environment p<strong>reparing</strong></h4><p>Open up your linux terminal and run these shell commands:</p><pre># <a href="https://docs.docker.com/engine/install/">Docker</a> for Pymesh library examples:<br>curl -fsSL https://get.docker.com -o get-docker.sh<br>sudo sh get-docker.sh</pre><pre># PyTorch3d g++ compiler:<br>sudo apt update<br>sudo apt install g++</pre><pre># Repository cloning and library installation:<br>git clone <a href="https://github.com/format37/python3d.git">https://github.com/format37/python3d.git</a><br>cd python3d<br>pip install -r requirements.txt<br>pip install &quot;git+https://github.com/facebookresearch/pytorch3d.git&quot;</pre><pre># OpenScad install:<br>sudo apt-get install openscad</pre><p>If you’re obtain installation troubles, i suggest googling. Unfortunately, some dependencies can become obsolete over time. The main idea of this article is collect and overview as much as possible Python 3D modeling approaches.</p><h3><strong>Numpy-stl: library overview</strong></h3><ul><li><a href="https://pypi.python.org/pypi/numpy-stl">Project page</a></li><li><a href="https://numpy-stl.readthedocs.io/">Documentation</a></li><li><a href="https://github.com/WoLpH/numpy-stl">Github</a></li></ul><p>The structure of the <a href="https://en.wikipedia.org/wiki/Polygon_mesh">polygon mesh</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*3Yq1nVAAxq4l0D7y-8Clpg.png" /><figcaption>Image from Wikipedia</figcaption></figure><p><strong>Vertices — </strong>List of points. Each point described by three numbers — coordinates in 3-dimensional space.</p><p>Next, we gonna use <a href="https://towardsdatascience.com/everything-you-need-to-know-about-jupyter-notebooks-10770719952b">Jupyter notebook</a>.</p><p><em>Example: </em><a href="https://github.com/format37/python3d/blob/main/numpy_stl_examples/numpy_stl_example_01.ipynb"><em>numpy_stl_example_01.ipynb</em></a></p><pre>import numpy as np<br>from myplot import plot_verticles</pre><pre>vertices = np.array([<br>[-3, -3, 0],<br>[+3, -3, 0],<br>[+3, +3, 0],<br>[-3, +3, 0],<br>[+0, +0, +3]<br>])</pre><pre>plot_verticles(vertices = vertices, isosurf = False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*CQHTwfdC9SXr0hEyVIK1SQ.png" /><figcaption>Pyramid verticies</figcaption></figure><p>Despite the fact that only vertices are described, you can already take a look at how the model will look like if you connect them with triangles:</p><pre>plot_verticles(vertices = vertices, isosurf = True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*IF6GDiNurTX-ldSH16pvRw.png" /><figcaption>Pyramid Isosurface</figcaption></figure><p>Looks like the faces already exist. But now we have only vertices. To create an STL file, let’s describe the face, that can be done manually, or provide this operation of the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.ConvexHull.html">spatial.ConvexHull</a> function from the <a href="https://docs.scipy.org/doc/scipy/reference/">scipy</a> library.</p><p><em>Example: </em><a href="https://github.com/format37/python3d/blob/main/numpy_stl_examples/numpy_stl_example_02.ipynb"><em>numpy_stl_example_02.ipynb</em></a></p><pre><strong>import</strong> numpy <strong>as</strong> np<br><strong>from</strong> scipy <strong>import</strong> spatial<br><strong>from</strong> stl <strong>import</strong> mesh<br><strong>from</strong> myplot <strong>import</strong> plot_mesh</pre><pre>vertices = np.array(<br>[<br>[-3, -3, 0],<br>[+3, -3, 0],<br>[+3, +3, 0],<br>[-3, +3, 0],<br>[+0, +0, +3]<br>]<br>)<br>hull = spatial.ConvexHull(vertices)<br>faces = hull.simplices</pre><p>As a result, faces array contains this faces description:</p><pre>array([<br>[4, 1, 0],<br>[4, 2, 1],<br>[3, 4, 0],<br>[3, 4, 2],<br>[3, 2, 1],<br>[3, 1, 0]<br>], dtype=int32)</pre><p><strong>Faces</strong> — List of faces. Each triangular face described by three vertices (points). In other words, position of points in the vertices array.</p><p>For example, the last face contains numbers 3, 1, 0. So face assembled with the points of the 0th, 1st and 3rd elements of the vertices array:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*KpWSP1wK-oFZuIDkQ6OFhA.png" /><figcaption>Faces description principle through the vertices positions</figcaption></figure><p><strong>Mesh</strong> — Set of vertices and faces, determines the shape of polyhedral object.</p><pre>myramid_mesh = mesh.Mesh(<br>  np.zeros(faces.shape[0], dtype=mesh.Mesh.dtype)<br>)<br><strong>for</strong> i, f <strong>in</strong> enumerate(faces):<br>  <strong>for</strong> j <strong>in</strong> range(3):<br>    myramid_mesh.vectors[i][j] = vertices[f[j],:]<br>    plot_mesh(myramid_mesh)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*2ZOyUECQObCWKSYTax4hEA.png" /><figcaption>Pyramid faces</figcaption></figure><p>As can be seen from the figure, one face of the pyramid was turned upside down. In the following examples, when constructing fractals, the ConvexHull method will not be used, since it arranges the points of the face in an arbitrary order, which leads to the flipping of some faces.</p><pre>myramid_mesh.save(&#39;numpy_stl_example_02.stl&#39;)</pre><p>To view STL files, i use the freeware program: Blender.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*ZCqCQYGG03cI6_eTlU1xOg.png" /><figcaption>Screenshot. Blender: numpy_stl_example_02.stl</figcaption></figure><p>The spatial.convexhull method is designed to calculate the convex shell and copes well with the pyramid and cube. But in objects having a cavity, part of the points will be lost and an error will occur when assembling the STL due to the inconsistency of the number of points.</p><p><em>This is clearly visible on the example in two dimensions: </em><a href="https://github.com/format37/python3d/blob/main/numpy_stl_examples/numpy_stl_example_03.ipynb"><em>numpy_stl_example_03.ipynb</em></a></p><pre><strong>import</strong> matplotlib.pyplot <strong>as</strong> plt<br><strong>from</strong> scipy <strong>import</strong> spatial<br><strong>import</strong> numpy <strong>as</strong> np</pre><pre>points = np.array([<br>[0,0],<br>[-2,0],<br>[-2,2],<br>[0,1.5],<br>[2,2],<br>[2,0]<br>])<br>hull = spatial.ConvexHull(points)</pre><p>hull.simplices contains a faces description:</p><pre>array([<br>[2, 1],<br>[2, 4],<br>[5, 1],<br>[5, 4]<br>], dtype=int32)</pre><p>Let’s plot the vertices and faces:</p><pre>plt.plot(points[:,0], points[:,1], &#39;o&#39;)<br>for simplex in hull.simplices:<br>  plt.plot(points[simplex, 0], points[simplex, 1], &#39;k-&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*XYX1m5ZI_Nu2rnbwgp15wQ.png" /><figcaption>Center vertice is not connected to faces</figcaption></figure><p>For such cases, you can find alternative to convexhull, or describe the edges manually:</p><pre>faces = np.array([<br>[0, 1],<br>[1, 2],<br>[2, 3],<br>[3, 4],<br>[4, 5],<br>[5, 0]<br>])</pre><pre>plt.plot(points[:,0], points[:,1], &#39;o&#39;)</pre><pre><strong>for</strong> simplex <strong>in</strong> faces:<br>  plt.plot(points[simplex, 0], points[simplex, 1], &#39;k-&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*eqeMDDJl6G9wR5CJxpw_sg.png" /><figcaption>Two faces were added: one for the bottom vertice, and one for the top</figcaption></figure><h4><strong>Numpy-stl: Building a fractal</strong></h4><p>It’s time to build a fractal. There is no boolean subtraction function in Numpy-stl. To build a Menger Sponge fractal, we did from the contrary. There is two methods:</p><ol><li>Building an elementary cube mesh. Let’s call it <a href="https://en.wikipedia.org/wiki/Voxel">voxel</a>.</li><li>Combining several Voxel into a single mesh.</li></ol><p>We will construct a fractal from cubes, as from the constructor.</p><p><em>Description of the logic of constructing a fractal:</em></p><pre>Suppose the fractal face length is 1. Depth of fractal is the count of unique hole sizes. Voxel length depends on depth of the fractal, it is divided by 3 with each new level of depth.</pre><pre>We gonna find the voxel side at depths 1 and 2. Let&#39;s simplify the task, turning the fractal from 3 to 1-dimensional case:</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5niwHO28hawffNcQSMJgQ.png" /></figure><pre>If fractal level is 2, then the length of the cube side will be 1 / (3 ** 2) which is equivalent to 1/9. Let&#39;s make a set of cubes so that they filled resulting voxel cube by their location. Let&#39;s calculate holes area. Exclude voxels that are in holes. In conclusion, unite the remaining voxels in one object and save.</pre><p><em>Example: </em><a href="https://github.com/format37/python3d/blob/main/numpy_stl_examples/numpy_stl_example_04.ipynb"><em>numpy_stl_example_04.ipynb</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*f9S5ss6F1IcxO0IWe-0FAw.png" /><figcaption>Screenshot. Blender: numpy_stl_example_04.stl</figcaption></figure><h4><strong>Numpy-stl: Rendering</strong></h4><p>To render image, we send mesh, loaded from STL file, to the <a href="https://github.com/format37/python3d/blob/main/numpy_stl_examples/myplot.py"><em>plot_mesh</em></a> function.</p><p><em>Example: </em><a href="https://github.com/format37/python3d/blob/main/numpy_stl_examples/numpy_stl_example_05.ipynb"><em>numpy_stl_example_05.ipynb</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*9c3zk41PrSYWCirKKZpPqg.png" /><figcaption>One of the <a href="https://habrastorage.org/r/w1560/webt/kz/fh/q6/kzfhq6y_wnkd4lxmuhmxsfw-30c.gif">animation</a> frames</figcaption></figure><h3>PyMesh: library overview</h3><ul><li><a href="https://pymesh.readthedocs.io/en/latest/">Documentation</a></li><li><a href="https://github.com/PyMesh/PyMesh">Github</a></li></ul><h4>Installation</h4><pre>Unfortunately, the Pymesh library has been unabled to install through the PIP package manager, despite discribed this approach in the documentation, nor through Anaconda. There are two ways to install.</pre><pre>1. Following the instructions, compile from the source.</pre><pre>2. Using a docker container. I choose this option as more interesting. Container launches with the parameters. Using the startup parameters, mount the scripts folder into the container. Let us give the necessary parameters to the script. After script execution completes, the container will be deleted.<br>If Docker has already installed following instructions at the beginning of the article, no longer need to install.</pre><pre>If the Docker is not suitable for you, compile Pymesh, following the instructions in the documentation. This option also was tested by me.</pre><p>Let’s start with a simple cube. In the Pymesh_Examples folder there is a Pymesh_example_01.py script. In future, container will take files from this folder.</p><p><em>Example: </em><a href="https://github.com/format37/python3d/blob/main/pymesh_examples/pymesh_example_01.py"><em>pymesh_example_01.py</em></a></p><pre><strong>import</strong> pymesh</pre><pre>box_a = pymesh.generate_box_mesh([0,0,0], [1,1,1])<br>filename = &quot;/pymesh_examples/pymesh_example_01.stl&quot;<br>pymesh.save_mesh(filename, box_a, ascii=False)</pre><p>Start container from the project root:</p><pre>sh pymesh_example_01.sh</pre><p><em>What’s happened there:</em></p><ul><li>Pymesh container starts. Initial start the image downloading would take some time.</li><li>Pymesh_examples folder mounted inside container.</li><li>Python script starts inside container: /pymesh_examples/pymesh_example_01.py</li><li>Pymesh library is imported.</li><li>generate_box_mesh function generates a cube on the basis of two opposite vertices at points [0,0,0] and [1,1,1].</li><li>Save_Mesh function saves an object in the STL file.</li><li>After execution, <em>pymesh_example_01</em>.stl file appears in the <em>pymesh_examples</em> folder.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*Vhe8nuFPScXWOcgRKk8PgQ.png" /><figcaption>Screenshot. Blender: pymesh_example_01.stl</figcaption></figure><p>Let’s make a square hole using Boolean subtraction. We gonna build a parallelepiped and subtract it from the main cube.</p><p><em>Example: </em><a href="https://github.com/format37/python3d/blob/main/pymesh_examples/pymesh_example_02.py"><em>pymesh_example_02.py</em></a></p><pre><strong>import</strong> pymesh</pre><pre>box_a = pymesh.generate_box_mesh([0,0,0], [1,1,1])<br>box_b = pymesh.generate_box_mesh([0.4,0.4,0], [0.6,0.6,1])<br>box_c = pymesh.boolean(<br>  box_a,<br>  box_b,<br>  operation=&#39;difference&#39;,<br>  engine=&quot;igl&quot;<br>)<br>filename = &quot;/pymesh_examples/pymesh_example_02.stl&quot;<br>pymesh.save_mesh(filename, box_c, ascii=False)</pre><p>Run:</p><pre>sh pymesh_example_02.sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*MaA_1_t8XcddE4hssffwxg.png" /><figcaption>Screenshot. Blender: pymesh_example_02.stl</figcaption></figure><p>The <a href="https://pymesh.readthedocs.io/en/latest/mesh_boolean.html">boolean</a> function is simple. First parameter is an object from which we subtract. Second is that we subtract. Also we send operation and engine.</p><p>Boolean is applied not only for subtraction. Totally, 4 operations are available:</p><ul><li>Intersection: A∩B</li><li>Union: A∪B</li><li>Difference: A∖B (last two examples)</li><li>Symmetric difference: A XOR B (image not shown)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0vOIVNhSmybOl_qSgXpbiQ.png" /><figcaption>Illustration of boolean operation on a sphere and cube. Image from PyMesh official documentation.</figcaption></figure><p>To better understanding how to move and rotate an object, for debugging purposes it can be convenient to temporarily replace the Difference operation with Union.</p><p>Let’s make a second hole, move and rotate it.</p><p><em>Example: </em><a href="https://github.com/format37/python3d/blob/main/pymesh_examples/pymesh_example_03.py"><em>pymesh_example_03.py</em></a></p><p>Run:</p><pre>sh pymesh_example_03.sh</pre><p>Our script obtained the move and rotate functions. With moving, a new mesh object is created, based on the modified vertices and faces of the original object.</p><p><a href="https://pymesh.readthedocs.io/en/latest/api_misc.html?highlight=Quaternion#quaternion">Quaternion</a> class, describes rotation, and then created a new, rotated object, based on the vertices and faces of the original object, as well as the description of the rotation.</p><p><a href="https://en.wikipedia.org/wiki/Quaternion">Quaternion</a> number<a href="https://en.wikipedia.org/wiki/Number_system"> </a>system extends the complex numbers.</p><p><a href="https://www.3dgep.com/understanding-quaternions/"><em>Understanding Quaternions</em></a></p><p>The result of the script execution is a cube with two intersecting holes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*gqzLPj5cd1czmPq35uT5iQ.png" /><figcaption>Screenshot. Blender: pymesh_example_03.stl</figcaption></figure><p>These tools are quite enough to build a fractal.</p><h4><strong>PyMesh: Building a fractal</strong></h4><p><em>Example: </em><a href="https://github.com/format37/python3d/blob/main/pymesh_examples/pymesh_example_04.py"><em>pymesh_example_04.py</em></a></p><p>In this script, we added one input parameter to set fractal depth. For each depth level, created a box, copied twice, then rotated and offset. It turns out only 3 parallelepipeds, which are subtracted from the main cube. One for each edge. This operation repeated x and y times to fill all rows and column edges. Check for subtraction from empty space does not performed.</p><p>This time we must explicitly specify the depth of the fractal:</p><pre>sh pymesh_example_04.sh 3</pre><p>It will take 5–15 minutes to complete. After launch, new STL file will appear in the pymesh_examples folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*7W9PTpt0bqS0CjTngR_kQw.png" /><figcaption>Screenshot. Blender: pymesh_example_04_3.stl</figcaption></figure><p>With request a 4-level fractal, assembly take about 4 hours, and the file size is 73 mb:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*6FqINRRPynM7kiqz4UfYTA.png" /><figcaption>Screenshot. Blender: pymesh_example_04_4.stl</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I5AFPn1JB3l5_JonIzeQAA.png" /><figcaption>Level 4 Menger Sponge 3D Printed</figcaption></figure><h4><strong>PyMesh: Rendering</strong></h4><p>Last time we rotated the mesh. This time let’s rotate the camera.</p><p><em>Example: </em><a href="https://github.com/format37/python3d/blob/main/pymesh_examples/pymesh_example_05.py"><em>pymesh_example_05.py</em></a></p><p>Run:</p><pre>sh pymesh_example_05.sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*vBQXIBiLiDFf9xVdO6zicQ.png" /><figcaption>One of the <a href="https://habrastorage.org/r/w1560/webt/-c/hr/zq/-chrzqyavbe-xepwt6vtwdth0u8.gif">animation</a> frames</figcaption></figure><h3><strong>PyTorch3d: Library overview</strong></h3><ul><li><a href="https://pytorch3d.org/">Project page</a></li><li><a href="https://pytorch3d.org/docs/why_pytorch3d.html">Documentation</a></li><li><a href="https://github.com/facebookresearch/pytorch3d/blob/master/INSTALL.md">Installation</a></li><li><a href="https://github.com/facebookresearch/pytorch3d">Github</a></li></ul><p><em>Pyramid. Example: </em><a href="https://github.com/format37/python3d/blob/main/pytorch3d_examples/pytorch3d_example_01.py"><em>pytorch3d_example_01.py</em></a></p><p>Approach is very similar to that used in numpy-stl. But since it is supposed to work on the GPU, we will separate the concepts of host and device.</p><ul><li>Host is our computer.</li><li>Device is a video card.</li></ul><p>If you have no card, you still can use the library, then the CPU will act as the GPU.</p><p>Host and device have their own memory. To transfer an item from the host to device and back, we need to perform a small ritual.</p><p>With example below, we immediately describe the vertices on the device, copy them from the device to the host. Edges calculated, based on vertices. Then save the object. Resulting OBJ file can be imported into blender:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*-HFwx9BtHv1cdG764xouwA.png" /><figcaption>Screenshot. Blender: pytorch3d_example_01.obj</figcaption></figure><p>Pay attention to the command <em>verts.cpu().numpy()</em></p><p>The vertices are copied from device to host. If you are working with a GPU, each copy will slow down the algorithm. When planning a program architecture, it is best to keep the count of copy operations between the host and the device to minimum as much as possible. For example, if you initially have a list of vertices on the host, you can calculate faces without copying vertices from the device to the host, as will be done in the next example.</p><p><em>Example: </em><a href="https://github.com/format37/python3d/blob/main/pytorch3d_examples/pytorch3d_example_02.py"><em>pytorch3d_example_02.py</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*N2JpW6Wc_LdTbme-7avCtw.png" /><figcaption>Screenshot. Blender: pytorch3d_example_02.obj</figcaption></figure><h4><strong>PyTorch3d: Building a fractal</strong></h4><p>GPU gives some performance boost.</p><p><em>Example: </em><a href="https://github.com/format37/python3d/blob/main/pytorch3d_examples/pytorch3d_example_03.py"><em>pytorch3d_example_03.py</em></a></p><p>There we are declare vertices of minimal voxel, for specified depth level. Using algorithm, familiar to previous example, we calculate holes coordinates in two dimensions. Then fill the primary cube with voxels, that do not fall into holes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*oALAHRbb5DNSDds_GLY8jg.png" /><figcaption>Screenshot. Blender: pytorch3d_example_03.obj</figcaption></figure><p>Calculation speed increased by an order of magnitude, which made it possible to build a 5-level fractal in about 5 hours:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*Etn4k-SR8ZQjXIxt-IyINw.png" /><figcaption>Screenshot. Blender Menger Sponge 5 level</figcaption></figure><p>Size of this STL file is 1.9 GB. When constructing a fractal of the 5th level, the program stopped due to overflow of the video card memory. I had to collect the object in batches. 10 layers of “2D” fractals were created, then they were attached to the main object until the full fractal was built.</p><h4><strong>PyTorch3d: Rendering</strong></h4><p>In addition to plotly visualizations, pytorch3d pays special attention to rendering. And the approach is quite thorough, with textures and shaders.</p><p><em>Example: </em><a href="https://github.com/format37/python3d/blob/main/pytorch3d_examples/pytorch3d_example_04.py"><em>pytorch3d_example_04.py</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*ivRpBtlSyR4_4LaP6G601w.png" /><figcaption>One of <a href="https://habrastorage.org/r/w1560/webt/lu/hb/rn/luhbrnspu0ep1saufkpl7servzw.gif">animation</a> frames</figcaption></figure><h3><strong>SolidPython: Library overview</strong></h3><ul><li><a href="https://solidpython.readthedocs.io/en/latest/">Documentation</a></li><li><a href="https://github.com/SolidCode/SolidPython">Github</a></li><li><a href="https://openscad.org/cheatsheet/">Openscad cheatsheet</a></li><li><a href="https://en.wikibooks.org/wiki/OpenSCAD_User_Manual">Wiki</a></li></ul><p>SolidPython is the richest modeling library of the considered. 3D scene, described in format, very similar to openscad. Python generates openscad code that is written to a scad file. And then it can be edited in openscad or immediately saved to STL.</p><p><em>Example: </em><a href="https://github.com/format37/python3d/blob/main/solidpython_examples/solidpython_example_01.ipynb"><em>solidpython_example_01.ipynb</em></a></p><pre><strong>from</strong> solid <strong>import</strong> *</pre><pre>d = difference()(<br>  cube(size = 10, center = True),<br>  sphere(r = 6.5, segments=300)<br>)</pre><pre>path = scad_render_to_file(d, &#39;solidpython_example_01.scad&#39;)</pre><p>To specify resolution of sphere, instead of usual $fn openscad parameter, we use word <em>segments</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*Hko9HO_b5R4Hv1RKa5FqJQ.png" /><figcaption>Screenshot. Openscad: solidpython_example_01.scad</figcaption></figure><p>Solidpython is convenient for debugging.</p><ul><li>At one side of screen, we have opened scad file.</li><li>At another side, we have opened Jupyter notebook.</li></ul><p>After executing scad_render_to_file inside Jupyter notebook, picture in openscad updated automatically.</p><p>Openscad can render model to stl file with console <a href="https://en.wikibooks.org/wiki/OpenSCAD_User_Manual/Using_OpenSCAD_in_a_command_line_environment">commands</a>. There is call example from Jupyter notebook:</p><pre>!openscad solidpython_example_01.scad -o solidpython_example_01.stl</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*R1sQI3Z-zqdNcUjTI27PNA.png" /><figcaption>Screenshot. Blender: solidpython_example_01.stl</figcaption></figure><p>Any openscad function returns an object.</p><p>To perform an operation on to object, the object or list of objects is passed in round brackets at the end of the operation call string.</p><p><em>Example: </em><a href="https://github.com/format37/python3d/blob/main/solidpython_examples/solidpython_example_02.ipynb"><em>solidpython_example_02.ipynb</em></a></p><pre><strong>from</strong> solid <strong>import</strong> *</pre><pre>c = circle(r = 1)<br>t = translate([2, 0, 0]) (c)<br>e = linear_extrude(<br>  height = 10,<br>  center = True,<br>  convexity = 10,<br>  twist = -500,<br>  slices = 500<br>) (t)</pre><pre>col = color(&#39;lightgreen&#39;) (e)<br>path = scad_render_to_file(col, &#39;solidpython_example_02.scad&#39;)</pre><p>Resolution settled by the <em>slices</em> parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*QsSRbFiwr_oAnOIwSo_-2Q.png" /><figcaption>Screenshot. Openscad: solidpython_example_02.scad</figcaption></figure><h4><strong>SolidPython: Building a fractal</strong></h4><p><em>Example: </em><a href="https://github.com/format37/python3d/blob/main/solidpython_examples/solidpython_example_03.ipynb"><em>solidpython_example_03.ipynb</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*En5ruJvR3nFFdWiJGLj2mg.png" /><figcaption>Screenshot. Openscad: solidpython_example_03.scad</figcaption></figure><h4><strong>SolidPython: Rendering</strong></h4><p>Let’s render a series of images for the last scene, by camera rotation on the each image.</p><p><em>Example: </em><a href="https://github.com/format37/python3d/blob/main/solidpython_examples/solidpython_example_04.ipynb"><em>solidpython_example_04.ipynb</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*GazUUcnLUcBW_LL-bZFFaA.png" /><figcaption>One of <a href="https://habrastorage.org/r/w1560/webt/m9/f3/oj/m9f3ojaysevcjpqoohud7drifzs.gif">animation</a> frames</figcaption></figure><p>In addition, solidpython offers animation generation using openscad. There is a little <a href="https://solidpython.readthedocs.io/en/latest/#animation">section</a> in documentation with <a href="https://github.com/SolidCode/SolidPython/blob/master/solid/examples/animation_example.py">example</a>.</p><p>Finally, let’s take a look at the code, used to build scene from title of this article.</p><p><em>Example: </em><a href="https://github.com/format37/python3d/blob/main/solidpython_examples/solidpython_example_05.ipynb"><em>solidpython_example_05.ipynb</em></a></p><h4><strong>PyVista</strong></h4><p>I also wish to mention another interesting <a href="https://docs.pyvista.org/">PyVista</a> library.</p><p><em>3D plotting and mesh analysis through a streamlined interface for the Visualization Toolkit (VTK)</em></p><p>He helped me to visualize depth map, by reading mesh from STL file. But besides that, it has a few other interesting features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*QHmc0WH-O5yLdBjQ-qMbww.png" /><figcaption><a href="https://github.com/format37/python3d/blob/main/comments/stl-slicer-v3.ipynb">stl-slicer</a> example screenshot</figcaption></figure><h4><strong>Libraries comparing</strong></h4><p>Current performance comparison is not fully objective, because there is significant differences in algorithms. Pymesh and SolidPython used subtraction, while Numpy-stl and Pytorch3d used mesh union.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*Lz77pj9MCu5FZChCFGVaXA.png" /></figure><h4>My machine:</h4><pre>Ubuntu 20.04.2 LTS<br>Python 3.7.3<br>Intel(R) Core(TM) i3-7350K CPU @ 4.20GHz<br>RAM 35.2Gb<br>GPU GeForce GTX 1080 Ti 11175 MB</pre><h4>Links</h4><ul><li><a href="https://pytorch3d.org/tutorials/render_colored_points">PyTorch3D Point cloud importing</a></li><li><a href="https://en.wikibooks.org/wiki/OpenSCAD_User_Manual/Using_OpenSCAD_in_a_command_line_environment">OpenScad command line environment</a></li><li><a href="https://medium.com/applied-data-science/pytorch3d-robolove-2138d84a425e">PyTorch3D : RoboLove</a></li><li><a href="https://trimsh.org/">trimesh — Страница проекта</a></li><li><a href="https://github.com/hmeyer/openscadpy">openscadpy — Страница проекта</a></li><li><a href="https://mirmik.github.io/zencad/ru/index.html">zenscad — Documentation</a></li><li><a href="https://analyticsindiamag.com/hands-on-guide-to-pytorch3d-a-library-for-deep-learning-with-3d-data/">Hands-on Guide to PyTorch 3D — A Library for Deep Learning with 3D Data</a></li><li><a href="https://docs.unrealengine.com/4.26/en-US/ProductionPipelines/ScriptingAndAutomation/Python/">Scripting the Unreal Editor using Python</a></li><li><a href="https://developer.nvidia.com/nvidia-kaolin">Nvidia kaolin</a></li><li><a href="https://analyticsindiamag.com/nvidias-kaolin-3d-deep-learning-library/">Guide To NVIDIA’s Kaolin: A 3D Deep Learning Library</a></li><li><a href="https://matplotlib.org/stable/tutorials/toolkits/mplot3d.html">matplotlib 3D rendering</a></li></ul><h4>About me:</h4><p>Alexey Yurasov, ML engineer</p><ul><li><a href="https://github.com/format37">github</a></li><li><a href="https://www.linkedin.com/in/format37/">linkedin</a></li><li><a href="https://www.upwork.com/freelancers/format37">upwork</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c21296756db2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>