{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import k3d\n", "import base64" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Produce a plot" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "iteration = 4\n", "size = 3**iteration\n", "\n", "voxels = np.ones((size, size, size));\n", "\n", "def iterate(length, x, y, z):\n", "\n", " nl = length // 3 \n", "\n", " if nl < 1:\n", " return\n", "\n", " margin = (nl-1) // 2\n", "\n", " voxels[z-margin:z+margin+1, y-margin:y+margin+1, :] = 0\n", " voxels[z-margin:z+margin+1, :, x-margin:x+margin+1] = 0\n", " voxels[:, y-margin:y+margin+1, x-margin:x+margin+1] = 0 \n", "\n", " for ix,iy,iz in np.ndindex((3,3,3)):\n", " if (1 if ix !=1 else 0) + (1 if iy != 1 else 0) + (1 if iz != 1 else 0) !=2:\n", " iterate(nl, x + (ix-1) * nl, y + (iy-1) * nl , z + (iz-1) * nl)\n", "\n", "iterate(size, size//2, size//2, size//2)\n", "\n", "plot = k3d.plot()\n", "plot += k3d.voxels(voxels.astype(np.uint8), compression_level=9)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Create and save to *.k3d file" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "template = \"\"\"\n", "\n", "\n", "\n", " \n", " K3D in js\n", " \n", " \n", " \n", "\n", "\n", "
\n", "\n", "\n", "\n", "\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data = plot.get_binary_snapshot()\n", "\n", "with open(\"k3d_in_javascript.html\", \"w\") as f: \n", " # base64 is only for embeding data in html normally recommeded way is to load data via ajax\n", " f.write(template.replace(\"[DATA]\", base64.b64encode(data).decode(\"utf-8\")))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.12" } }, "nbformat": 4, "nbformat_minor": 4 }