### Install Example Dependencies Source: https://github.com/jupyter-widgets/pythreejs/blob/master/CONTRIBUTING.md Install the Python packages required to run the pythreejs examples. ```bash python -m pip install -e .[examples] ``` -------------------------------- ### Install Documentation Dependencies Source: https://github.com/jupyter-widgets/pythreejs/blob/master/CONTRIBUTING.md Install the necessary Python packages for building the documentation. ```bash python -m pip install -e .[docs] ``` -------------------------------- ### Setup a pythreejs renderer Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Capture.ipynb Configures a scene with a sphere, a cube, a perspective camera, and lights, then creates a renderer with orbit controls. ```python view_width = 600 view_height = 400 sphere = Mesh( SphereBufferGeometry(1, 32, 16), MeshStandardMaterial(color='red') ) cube = Mesh( BoxBufferGeometry(1, 1, 1), MeshPhysicalMaterial(color='green'), position=[2, 0, 4] ) camera = PerspectiveCamera( position=[10, 6, 10], aspect=view_width/view_height) key_light = DirectionalLight(position=[0, 10, 10]) ambient_light = AmbientLight() scene = Scene(children=[sphere, cube, camera, key_light, ambient_light]) controller = OrbitControls(controlling=camera) renderer = Renderer(camera=camera, scene=scene, controls=[controller], width=view_width, height=view_height) ``` -------------------------------- ### Install pythreejs with pip Source: https://github.com/jupyter-widgets/pythreejs/blob/master/README.md Use pip to install the pythreejs package. This is the standard installation method for Python packages. ```bash pip install pythreejs ``` -------------------------------- ### Build and Install JS Distribution Source: https://github.com/jupyter-widgets/pythreejs/blob/master/CONTRIBUTING.md Build the JavaScript distribution and install the pythreejs Jupyter nbextension using system prefix. ```bash cd js npm run build:all jupyter nbextension install --py --symlink --sys-prefix pythreejs ``` -------------------------------- ### Install JS Distribution as User Local Source: https://github.com/jupyter-widgets/pythreejs/blob/master/CONTRIBUTING.md Build the JavaScript distribution and install the pythreejs Jupyter nbextension for the current user. ```bash jupyter nbextension install --py --symlink --user pythreejs ``` -------------------------------- ### Setup 3D objects and materials Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/renderer_limit.ipynb Initializes various MeshStandardMaterials and TorusGeometry objects to be used in rendering. ```python # Setup our objects mat1 = MeshStandardMaterial(color='#ff0000') mat2 = MeshStandardMaterial(color='#00ff00') mat3 = MeshStandardMaterial(color='#0000ff') mat4 = MeshStandardMaterial(color='#ffff00') mat5 = MeshStandardMaterial(color='#ff00ff') mat6 = MeshStandardMaterial(color='#00ffff') torus = TorusGeometry(radius=12, tube=3, radialSegments=16, tubularSegments=100) mesh1 = Mesh(geometry=torus, material=mat1) mesh2 = Mesh(geometry=torus, material=mat2) mesh3 = Mesh(geometry=torus, material=mat3) mesh4 = Mesh(geometry=torus, material=mat4) mesh5 = Mesh(geometry=torus, material=mat5) mesh6 = Mesh(geometry=torus, material=mat6) ``` -------------------------------- ### Use example model IDs helper Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Geometries.ipynb Helper function to reduce repository churn for examples with embedded state. ```python # Reduce repo churn for examples with embedded state: from pythreejs._example_helper import use_example_model_ids use_example_model_ids() ``` -------------------------------- ### Setup Scene with Lights and Camera Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Picker.ipynb Initializes the 3D scene, including directional and ambient lights, and a perspective camera. The camera is configured with its position, up vector, and aspect ratio. ```python # Set up scene: key_light = DirectionalLight(color='white', position=[3, 5, 1], intensity=0.4) c = PerspectiveCamera(position=[0, 3, 3], up=[0, 0, 1], aspect=view_width / view_height, children=[key_light]) scene = Scene(children=[surf, c, surfgrid, AmbientLight(intensity=0.8)]) ``` -------------------------------- ### Setup scene for raw WebGLRenderer Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/renderer_limit.ipynb Configures a scene, camera, and lights required for direct use of the WebGLRenderer. ```python # Test using raw WebGLRenderer # Need a scene, cam, and lights to do so scene = Scene() scene.add(mesh1) cam = PerspectiveCamera(position=[0, 0, 50], fov=75) cam.lookAt([0, 0, 0]) scene.add(cam) amb = AmbientLight(color="#ffffff", intensity=0.5) point = PointLight(color="#ffffff", intensity=1.0, distance=0.0) point.position = [ -100, 100, 100 ] point.lookAt([0, 0, 0]) cam.add(amb) cam.add(point) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Capture.ipynb Import pythreejs, ipywebrtc, and ipywidgets for renderer setup and output capture. ```python from pythreejs import * import ipywebrtc from ipywidgets import Output, VBox ``` -------------------------------- ### Import necessary libraries Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/GeometryVertices.ipynb Imports pythreejs, IPython.display, math, and numpy for use in the examples. ```python from pythreejs import * from IPython.display import display from math import pi import numpy as np ``` -------------------------------- ### Scene Setup Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/threejs/voxel_painter.ipynb Initializes the 3D scene, adding essential elements like pickable objects, a surface grid, a rollover helper, ambient light, and a directional light. ```python scene = Scene( children = [ pickable_objects, surf_grid, rollOver_point, AmbientLight( color = '#606060' ), DirectionalLight( color = '#ffffff', position = normalize([1, 0.75, 0.5]), intensity = 0.5 ) ] ) ``` -------------------------------- ### Start Jupyter Notebook with Debugging Source: https://github.com/jupyter-widgets/pythreejs/blob/master/CONTRIBUTING.md Launch a Jupyter Notebook server with debugging enabled. ```bash jupyter notebook --debug ``` -------------------------------- ### Install Node.js with Conda Source: https://github.com/jupyter-widgets/pythreejs/blob/master/CONTRIBUTING.md Install Node.js version 12 or higher using conda for development prerequisites. ```bash conda install -c conda-forge 'nodejs>=12' ``` -------------------------------- ### Install pythreejs with Pip (Editable Mode) Source: https://github.com/jupyter-widgets/pythreejs/blob/master/docs/source/develop-install.md Install pythreejs in editable mode using pip for development. ```bash pip install -e . ``` -------------------------------- ### Install JupyterLab Extension Source: https://github.com/jupyter-widgets/pythreejs/blob/master/docs/source/index.md Install the pythreejs extension for JupyterLab. Ensure the version specifier matches the Python package if installing an older version. ```bash jupyter labextension install jupyter-threejs ``` -------------------------------- ### Install Jupyter Notebook Extensions Source: https://github.com/jupyter-widgets/pythreejs/blob/master/docs/source/develop-install.md Install and enable pythreejs extensions for Jupyter Notebook. Use the appropriate flag for your environment (sys-prefix, user, or system). ```bash jupyter nbextension install [--sys-prefix / --user / --system] --symlink --py pythreejs jupyter nbextension enable [--sys-prefix / --user / --system] --py pythreejs ``` -------------------------------- ### Start JupyterLab with Debugging Source: https://github.com/jupyter-widgets/pythreejs/blob/master/CONTRIBUTING.md Launch a JupyterLab server without opening a browser, with debugging enabled. ```bash jupyter lab --no-browser --debug ``` -------------------------------- ### Install pythreejs Jupyter Notebook Extension Source: https://github.com/jupyter-widgets/pythreejs/blob/master/docs/source/installing.md Install the pythreejs Jupyter Notebook extension. Use --sys-prefix, --user, or --system based on your environment. ```bash jupyter nbextension install [--sys-prefix / --user / --system] --py pythreejs ``` -------------------------------- ### Usage Example: Displaying CubicLattice Source: https://github.com/jupyter-widgets/pythreejs/blob/master/docs/source/extending.md Demonstrates how to instantiate and display the custom CubicLattice widget. It shows both direct display and embedding the widget within a pythreejs scene with camera and lighting. ```python import pythreejs from IPython.display import display from my_module import CubicLattice lattice = CubicLattice(basis=[[0,0,0], [0.5, 0.5, 0.5]]) # Preview the lattice directly: display(lattice) # Or put it in a scene: width=600 height=400 key_light = pythreejs.DirectionalLight(position=[-5, 5, 3], intensity=0.7) ambient_light = pythreejs.AmbientLight(color='#777777') camera = pythreejs.PerspectiveCamera( position=[-5, 0, -5], children=[ # Have the key light follow the camera: key_light ], aspect=width/height, ) control = pythreejs.OrbitControls(controlling=camera) scene = pythreejs.Scene(children=[lattice, camera, ambient_light]) renderer = pythreejs.Renderer(camera=camera, scene=scene, controls=[control], width=width, height=height) display(renderer) ``` -------------------------------- ### Event Listener Setup Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/threejs/voxel_painter.ipynb Attaches the combined click and mousemove event handlers to the appropriate picker objects, enabling interaction with the 3D scene. ```python click_picker.observe(on_click, names=['point']) mousemove_picker.observe(on_mousemove, names=['faceIndex']) ``` -------------------------------- ### Setup Roll-over Helper Mesh Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/threejs/voxel_painter.ipynb Creates a semi-transparent mesh used as a visual indicator for where the next voxel will be placed. ```python rollOver_geo = cube_geo rollOver_mat = MeshBasicMaterial( color = '#ff0000', opacity = 0.5, transparent = True ) rollOver_point = Mesh( geometry = rollOver_geo, material = rollOver_mat, visible = False, ) ``` -------------------------------- ### Run Tests with Pytest Source: https://github.com/jupyter-widgets/pythreejs/blob/master/CONTRIBUTING.md Install test dependencies and run pytest with specific flags for testing the pythreejs package. ```bash python -m pip install -e .[test] pytest -vv -l --nbval-lax --current-env . ``` -------------------------------- ### Install Jupyter Notebook Extension Source: https://github.com/jupyter-widgets/pythreejs/blob/master/docs/source/index.md Register and enable the pythreejs front-end extensions for Jupyter Notebook versions older than 5.3, or when the kernel is in a different environment than the notebook server. ```bash jupyter nbextension install [--sys-prefix | --user | --system] --py pythreejs jupyter nbextension enable [--sys-prefix | --user | --system] --py pythreejs ``` -------------------------------- ### Setup Double-Click Picker for Algorithm Execution Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Picker.ipynb Configures a double-click picker on the surface to trigger an algorithm execution. A red sphere marks the clicked point, and a red line visualizes the algorithm's output. ```python # Create our picker for the double-click event ("dblclick") click_picker = Picker(controlling=surf, event='dblclick') def on_click(change): value = change['new'] with out: print('Clicked on %s' % (value,)) # Add a red sphere on the picked point point = Mesh(geometry=SphereGeometry(radius=0.05), material=MeshLambertMaterial(color='red'), position=value) scene.add(point) # Plot solution as a red line, this will start out empty points = [value] line = Line2(geometry=LineGeometry(positions=points), material=LineMaterial(color='red', linewidth=2)) scene.add(line) with out: # Pick up any print statements in the algorithm for pt in find_minima(f, value, [-xmax, xmax], [-xmax, xmax]): # For each point, update the line: pt = list(pt) pt[2] += 1e-2 # offset to clear surface line.geometry = LineGeometry(positions=np.vstack([line.geometry.positions, pt])) # When the point selected by the picker changes, trigger our function: click_picker.observe(on_click, names=['point']) # Update figure: renderer.controls = renderer.controls + [click_picker] box.children = box.children + (out,) ``` -------------------------------- ### Display VideoRecorder widget Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Capture.ipynb Provides a user interface for the VideoRecorder, allowing users to start, stop, and download video recordings. ```python video_recorder ``` -------------------------------- ### Setup Surface Geometry and Material Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Picker.ipynb Configures the 3D surface geometry and material for visualization. The surface geometry is defined by the grid data, and the material uses a texture mapped with function values evaluated at grid square centers. ```python # Surface geometry: surf_g = SurfaceGeometry(z=list(grid_z.flat), width=2 * xmax, height=2 * xmax, width_segments=nx - 1, height_segments=ny - 1) # Surface material. Note that the map uses the center-evaluated function-values: surf = Mesh(geometry=surf_g, material=MeshLambertMaterial(map=height_texture(center_z, 'YlGnBu_r'))) ``` -------------------------------- ### Develop Federated Extension for JupyterLab 3 Source: https://github.com/jupyter-widgets/pythreejs/blob/master/CONTRIBUTING.md Enable development mode for the JupyterLab 3 federated extension, overwriting existing installations. ```bash jupyter labextension develop . --overwrite ``` -------------------------------- ### Control video recording and download from kernel Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Capture.ipynb Enables autosave for video recordings, starts the recording process, and then stops it. Finally, it triggers a client-side download of the recorded video. ```python video_recorder.autosave = True video_recorder.recording = True # After executing this, try to interact with the renderer above before executing the next cell video_recorder.recording = False video_recorder.download() ``` -------------------------------- ### Set up camera and lights Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Shadows.ipynb Initializes a perspective camera and sets up a spot light and ambient light for the scene. ```python camera = PerspectiveCamera( position=[10, 6, 10], aspect=view_width/view_height) key_light = SpotLight(position=[0, 10, 10], angle = 0.3, penumbra = 0.1) ambient_light = AmbientLight() ``` -------------------------------- ### Create Animation Clip and Action for Camera Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Animation.ipynb Combines keyframe tracks into an AnimationClip and creates an AnimationAction to control the animation of the camera. This setup is used to play back the defined position and rotation animations. ```python camera_clip = AnimationClip(tracks=[positon_track, rotation_track]) camera_action = AnimationAction(AnimationMixer(camera), camera_clip, camera) ``` -------------------------------- ### Set up Scene and Renderer Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Combined Camera.ipynb Configure lights, add meshes and camera to the scene, and set up the renderer with orbit controls. ```python key_light = PointLight(position=[-100, 100, 100]) ambient_light = AmbientLight(intensity=0.4) scene = Scene(children=[mesh1, mesh2, key_light, ambient_light, camera]) renderer = Renderer(scene=scene, camera=camera, controls=[OrbitControls(controlling=camera)], width=view_width, height=view_height) display(renderer) ``` -------------------------------- ### Set up scene, camera, and lights Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/ThickLines.ipynb Initializes a `PerspectiveCamera`, `DirectionalLight`, and `AmbientLight` for the 3D scene. ```python view_width = 600 view_height = 400 camera = PerspectiveCamera(position=[10, 0, 0], aspect=view_width/view_height) key_light = DirectionalLight(position=[0, 10, 10]) ambient_light = AmbientLight() ``` -------------------------------- ### Install pythreejs with conda Source: https://github.com/jupyter-widgets/pythreejs/blob/master/README.md Use conda to install the pythreejs package from the conda-forge channel. This is an alternative installation method, often preferred for managing complex dependencies. ```bash conda install -c conda-forge pythreejs ``` -------------------------------- ### Build HTML Documentation Source: https://github.com/jupyter-widgets/pythreejs/blob/master/CONTRIBUTING.md Navigate to the 'docs' directory and run 'make html' to build the project documentation. ```bash cd docs make html ``` -------------------------------- ### Install pythreejs JupyterLab extensions Source: https://github.com/jupyter-widgets/pythreejs/blob/master/README.md Install pythreejs extensions for JupyterLab. This process involves installing the manager and data widgets extensions, followed by the pythreejs extension itself. Note: This is not recommended for JupyterLab 3+. ```bash ## ensure you have nodejs install, e.g. with conda # conda install -c conda-forge 'nodejs>=12' jupyter labextension list jupyter labextension install --no-build @jupyter-widgets/jupyterlab-manager jupyter labextension install --no-build jupyter-datawidgets/extension jupyter labextension install jupyter-threejs jupyter labextension list ``` -------------------------------- ### Create and configure the scene and renderer Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Shadows.ipynb Assembles the scene with geometry, camera, and lights, and sets up the renderer with orbit controls. ```python scene = Scene(children=[sphere, cube, plane, camera, key_light, ambient_light]) controller = OrbitControls(controlling=camera) renderer = Renderer(camera=camera, scene=scene, controls=[controller], width=view_width, height=view_height, antialias=True) ``` -------------------------------- ### Set up Scene and Renderer Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Animation.ipynb Configures the scene with the animated mesh, camera, lights, and sets up the renderer with orbit controls for interaction. The animation action is then displayed. ```python camera3 = PerspectiveCamera( position=[5, 3, 5], aspect=view_width/view_height) scene3 = Scene(children=[morphMesh, camera3, DirectionalLight(position=[3, 5, 1], intensity=0.6), AmbientLight(intensity=0.5)]) renderer3 = Renderer(camera=camera3, scene=scene3, controls=[OrbitControls(controlling=camera3)], width=view_width, height=view_height) display(renderer3, pill_action) ``` -------------------------------- ### Create and configure the renderer Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/ThickLines.ipynb Sets up the `Scene` with all objects and `OrbitControls` for camera manipulation, then creates the `Renderer`. ```python scene = Scene(children=[line1, line2, line3, camera, key_light, ambient_light]) controller = OrbitControls(controlling=camera, screenSpacePanning=False) renderer = Renderer(camera=camera, scene=scene, controls=[controller], width=view_width, height=view_height) ``` -------------------------------- ### Set up camera and lights Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Animation.ipynb Configures a perspective camera and directional and ambient lights for the scene. ```python camera = PerspectiveCamera( position=[10, 6, 10], aspect=view_width/view_height) key_light = DirectionalLight(position=[0, 10, 10]) ambient_light = AmbientLight() ``` -------------------------------- ### Rebuild JupyterLab for older versions Source: https://github.com/jupyter-widgets/pythreejs/blob/master/README.md For JupyterLab versions prior to 3, you may need to install Node.js and rebuild the JupyterLab application after installing pythreejs. This ensures the extension is correctly integrated. ```bash # conda install -c cond-forge 'nodejs>=12' jupyter lab build ``` -------------------------------- ### Initialize Renderer and Display Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Picker.ipynb Sets up the pythreejs renderer with the defined camera, scene, and orbit controls. It then creates an Output widget for capturing print statements and displays the renderer within a VBox. ```python renderer = Renderer(camera=c, scene=scene, width=view_width, height=view_height, controls=[OrbitControls(controlling=c)]) out = Output() # An Output for displaying captured print statements box = VBox([renderer]) display(box) ``` -------------------------------- ### Initialize VideoRecorder Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Capture.ipynb Sets up a VideoRecorder to capture video from the stream using the VP8 codec and saving it with the base filename 'video'. ```python video_recorder = ipywebrtc.VideoRecorder(stream=stream, filename='video', codecs='vp8') ``` -------------------------------- ### Initialize ImageRecorder Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Capture.ipynb Sets up an ImageRecorder to capture PNG snapshots from the stream, saving them with the base filename 'snapshot'. ```python recorder = ipywebrtc.ImageRecorder(filename='snapshot', format='png', stream=stream) ``` -------------------------------- ### Create a standard GL line for comparison Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/ThickLines.ipynb Sets up a basic `LineSegments` object with a `BufferGeometry` and `LineBasicMaterial`. Note that `linewidth` greater than 1 may not be supported on all systems. ```python g1 = BufferGeometry( attributes={ 'position': BufferAttribute(np.array([ [0, 0, 0], [1, 1, 1], [2, 2, 2], [4, 4, 4] ], dtype=np.float32), normalized=False), 'color': BufferAttribute(np.array([ [1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1] ], dtype=np.float32), normalized=False), }, ) m1 = LineBasicMaterial(vertexColors='VertexColors', linewidth=10) line1 = LineSegments(g1, m1) line1 ``` -------------------------------- ### Uninstall pythreejs with conda Source: https://github.com/jupyter-widgets/pythreejs/blob/master/README.md Use conda to uninstall the pythreejs package. This is an alternative method for removing packages installed via conda. ```bash conda uninstall pythreejs ``` -------------------------------- ### Initialize and display Renderer Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/renderer_limit.ipynb Creates a Renderer instance with the configured camera and scene, including OrbitControls for camera manipulation. ```python Renderer(camera=cam, scene=scene, controls=[OrbitControls(cam)]) ``` -------------------------------- ### Initialize Renderer with Controls Source: https://github.com/jupyter-widgets/pythreejs/blob/master/docs/source/introduction.md Use this to set up a renderer with interactive controls like OrbitControls. Ensure controls are passed as a list to the 'controls' argument. ```python Renderer(controls=[OrbitControls(...), ...], ...) ``` -------------------------------- ### Get shape and face count of Geometry Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/GeometryVertices.ipynb Retrieves the shape of the vertices and the number of faces in the Geometry object. This is useful for understanding the complexity of the geometry. ```python np.shape(g2.vertices), len(g2.faces) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Shadows.ipynb Imports pythreejs, ipywidgets, and IPython.display for setting up the scene and rendering. ```python from pythreejs import * import ipywidgets from IPython.display import display ``` -------------------------------- ### Set up Scene and Renderer for Animation Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Animation.ipynb Configures the scene, camera, lights, and renderer to display the animated object. OrbitControls are included for interactive camera manipulation. ```python scene = Scene(children=[sphere, cube, camera, key_light, ambient_light]) controller = OrbitControls(controlling=camera) renderer = Renderer(camera=camera, scene=scene, controls=[controller], width=view_width, height=view_height) ``` -------------------------------- ### Update vertex positions Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/BufferAttributes and BufferGeometry.ipynb Modifies the 'array' property of an existing BufferAttribute to update the vertex positions of the geometry. This example shows a different set of coordinates. ```python vertices.array = scale_factor * np.array([ [-1.0, -1.0, 0.0], [ 2.0, -2.0, 1.0], [ 1.0, 1.0, 0.0], [ 1.0, 1.0, 0.0], [-1.0, 1.0, 0.0], [-1.0, -1.0, 0.0], ]) ``` -------------------------------- ### Move cube and update sphere shadow properties Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Shadows.ipynb Repositions the cube and ensures the sphere material is updated to correctly receive shadows after initial setup. ```python cube.position = (0, 1, 2) # Also enable sphere to receive shadow: sphere.receiveShadow = True sphere.material.needsUpdate = True ``` -------------------------------- ### Initialize WebGLRenderer Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/test.ipynb Creates an instance of the WebGLRenderer, which is responsible for drawing the 3D scene onto the screen. ```python # Renderer renderer = WebGLRenderer() ``` -------------------------------- ### Create and Render a Cube with BufferGeometry Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Examples.ipynb This snippet demonstrates creating a cube using BufferGeometry with custom vertices, faces, and vertex colors. It then sets up a Mesh, Scene, PerspectiveCamera, and Renderer to display the cube. Use this for custom geometry where vertex attributes are essential. ```python from pythreejs import * import numpy as np from IPython.display import display vertices = np.asarray([ [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1] ], dtype='float32') faces = np.asarray([ [0, 1, 3], [0, 3, 2], [0, 2, 4], [2, 6, 4], [0, 4, 1], [1, 4, 5], [2, 3, 6], [3, 7, 6], [1, 5, 3], [3, 5, 7], [4, 6, 5], [5, 6, 7] ], dtype='uint16').ravel() # We need to flatten index array vertexcolors = np.asarray([(0,0,0), (0,0,1), (0,1,0), (1,0,0), (0,1,1), (1,0,1), (1,1,0), (1,1,1)], dtype='float32') cubeGeometry = BufferGeometry(attributes=dict( position=BufferAttribute(vertices, normalized=False), index=BufferAttribute(faces, normalized=False), color=BufferAttribute(vertexcolors), )) myobjectCube = Mesh( geometry=cubeGeometry, material=MeshLambertMaterial(vertexColors='VertexColors'), position=[-0.5, -0.5, -0.5] # Center the cube ) cCube = PerspectiveCamera( position=[3, 3, 3], fov=20, children=[DirectionalLight(color='#ffffff', position=[-3, 5, 1], intensity=0.5)]) sceneCube = Scene(children=[myobjectCube, cCube, AmbientLight(color='#dddddd')]) rendererCube = Renderer(camera=cCube, background='black', background_opacity=1, scene = sceneCube, controls=[OrbitControls(controlling=cCube)]) display(rendererCube) ``` -------------------------------- ### Render Scene with Skeletal Animation Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Animation.ipynb Sets up the scene, camera, lights, and `OrbitControls` for interaction. It then renders the `SkinnedMesh` with its associated `SkeletonHelper` and displays the interactive renderer. ```python camera4 = PerspectiveCamera( position=[40, 24, 40], aspect=view_width/view_height) scene4 = Scene(children=[mesh, helper, camera4, DirectionalLight(position=[3, 5, 1], intensity=0.6), AmbientLight(intensity=0.5)]) renderer4 = Renderer(camera=camera4, scene=scene4, controls=[OrbitControls(controlling=camera4)], width=view_width, height=view_height) display(renderer4) ``` -------------------------------- ### Initialize Pickers for Interaction Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/threejs/voxel_painter.ipynb Sets up Picker instances to detect double-click and mouse-move events on the pickable objects, enabling interaction. ```python click_picker = Picker( controlling = pickable_objects, event = 'dblclick' ) mousemove_picker = Picker( controlling = pickable_objects, event = 'mousemove' ) ``` -------------------------------- ### Create unique vertices for a square Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/BufferAttributes and BufferGeometry.ipynb Defines a BufferAttribute for vertex positions of a square, ensuring each vertex is unique. This is a common setup for geometries where each corner needs distinct properties. ```python # Simple square with unique vertices vertices = BufferAttribute( array=scale_factor * np.array([ [-1.0, -1.0, 0.0], [ 1.0, -1.0, 0.0], [ 1.0, 1.0, 0.0], [-1.0, 1.0, 0.0], ], dtype=np.float32), normalized=False) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Combined Camera.ipynb Import pythreejs and IPython.display for creating and displaying 3D scenes and widgets. ```python from pythreejs import * from IPython.display import display ``` -------------------------------- ### Create Rotation Keyframe Track and Animation Action Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Animation.ipynb Defines a keyframe track to animate the 'y' rotation of the surface object and creates an AnimationAction. This example animates the surface spinning around its y-axis. ```python spin_track = NumberKeyframeTrack(name='.rotation[y]', times=[0, 2], values=[0, 6.28]) spin_clip = AnimationClip(tracks=[spin_track]) spin_action = AnimationAction(AnimationMixer(surf), spin_clip, surf) ``` -------------------------------- ### Create a Scene Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/test.ipynb Initializes a Scene object, which acts as a container for all objects, cameras, and lights in the 3D environment. ```python # Scenes scene = Scene() ``` -------------------------------- ### Setup Figure Grid Data Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Picker.ipynb Generates grid data for visualizing a function in 3D. It calculates function values at both grid lattice points and the centers of grid squares using NumPy. ```python nx, ny = (20, 20) # grid resolution xmax = 1 # grid extent (+/-) x = np.linspace(-xmax, xmax, nx) y = np.linspace(-xmax, xmax, ny) step = x[1] - x[0] xx, yy = np.meshgrid(x, y) # Grid lattice values: grid_z = np.vectorize(f)(xx, yy) # Grid square center values: center_z = np.vectorize(f)(0.5 * step + xx[:-1,:-1], 0.5 * step + yy[:-1,:-1]) ``` -------------------------------- ### Camera Configuration Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/threejs/voxel_painter.ipynb Sets up a perspective camera with specified position, aspect ratio, field of view, and near/far clipping planes. It also configures the camera to look at the origin. ```python camera = PerspectiveCamera( position = [500, 800, 1300], aspect = width/height, fov = 35, near = 1, far = 10000 ) camera.lookAt([0,0,0]) ``` -------------------------------- ### Enable pythreejs Jupyter Notebook Classic extension Source: https://github.com/jupyter-widgets/pythreejs/blob/master/README.md Manually enable the pythreejs extension for the classic Jupyter Notebook interface. This involves listing, installing, and enabling the extension using jupyter nbextension commands. ```bash jupyter nbextension list jupyter nbextension install --py --symlink --sys-prefix pythreejs jupyter nbextension enable --py --sys-prefix pythreejs jupyter nbextension list ``` -------------------------------- ### Create Color Keyframe Track and Animation Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Animation.ipynb Defines a keyframe track to animate the color of an object's material and creates an AnimationClip and Action. This example animates the sphere's material color from red to blue. ```python color_track = ColorKeyframeTrack(name='.material.color', times=[0, 1], values=[1, 0, 0, 0, 0, 1]) # red to blue color_clip = AnimationClip(tracks=[color_track], duration=1.5) color_action = AnimationAction(AnimationMixer(sphere), color_clip, sphere) ``` -------------------------------- ### Create Parametric Geometry with JavaScript Function Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Examples.ipynb Define a parametric surface using a JavaScript function string. The function takes scaled u, v parameters and a THREE.Vector3 to modify in place. This example creates a torus-like shape with two different materials for front and back faces. ```python f = "" function f(origu, origv, out) { // scale u and v to the ranges I want: [0, 2*pi] var u = 2*Math.PI*origu; var v = 2*Math.PI*origv; var x = Math.sin(u); var y = Math.cos(v); var z = Math.cos(u+v); out.set(x,y,z) } " surf_g = ParametricGeometry(func=f, slices=16, stacks=16); surf = Mesh(geometry=surf_g, material=MeshLambertMaterial(color='green', side='FrontSide')) surf2 = Mesh(geometry=surf_g, material=MeshLambertMaterial(color='yellow', side='BackSide')) c = PerspectiveCamera(position=[5, 5, 3], up=[0, 0, 1], children=[DirectionalLight(color='white', position=[3, 5, 1], intensity=0.6)]) scene = Scene(children=[surf, surf2, c, AmbientLight(intensity=0.5)]) renderer = Renderer(camera=c, scene=scene, controls=[OrbitControls(controlling=c)], width=400, height=400) display(renderer) ``` -------------------------------- ### Initialize Combined Camera Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Combined Camera.ipynb Create a CombinedCamera instance with specified dimensions and initial position. ```python view_width = 600 view_height = 400 camera = CombinedCamera(position=[0, 0, 60], width=view_width, height=view_height) ``` -------------------------------- ### Create a Perspective Camera Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/test.ipynb Sets up a perspective camera with a specific position and field of view, and directs its gaze towards the origin. The camera defines the viewpoint for rendering. ```python # Cameras cam = PerspectiveCamera(position=[0, 0, 50], fov=75) cam.lookAt([0, 0, 0]) ``` -------------------------------- ### Set light target to track cube Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Shadows.ipynb Configures the spot light to follow the position of the cube. ```python key_light.target = cube ``` -------------------------------- ### Create a DodecahedronGeometry Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Geometries.ipynb Instantiates a DodecahedronGeometry with a specified radius. ```python dodeca_geometry = DodecahedronGeometry(radius=10, detail=0, _flat=True) dodeca_geometry ``` -------------------------------- ### Watch Sources for Changes Source: https://github.com/jupyter-widgets/pythreejs/blob/master/CONTRIBUTING.md Navigate to the 'js' directory and run the 'watch' npm script to automatically recompile sources on changes. ```bash cd js npm watch ``` -------------------------------- ### Trigger client-side download from kernel Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Capture.ipynb Initiates a download of the current snapshot to the client's browser from the kernel. ```python recorder.download() ``` -------------------------------- ### Display the renderer Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Capture.ipynb Renders the configured pythreejs scene in the output. ```python renderer ``` -------------------------------- ### Create an IcosahedronGeometry Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Geometries.ipynb Instantiates an IcosahedronGeometry with a specified radius. ```python IcosahedronGeometry(radius=10, _flat=True) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Shaders.ipynb Imports pythreejs, ipywidgets, and IPython.display for creating and displaying 3D visualizations and interactive elements. ```python from pythreejs import * import ipywidgets as widgets from IPython.display import display ``` -------------------------------- ### Renderer Initialization Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/threejs/voxel_painter.ipynb Configures the pythreejs renderer with the defined camera, scene, and controls, including orbit controls for camera manipulation and pickers for interaction. It also sets the background color and enables antialiasing. ```python renderer = Renderer( camera = camera, scene = scene, controls = [ OrbitControls( controlling = camera ), click_picker, mousemove_picker, ], background = '#f0f0f0', antialias = True, width=width, height=height, ) ``` -------------------------------- ### Create and Display a Simple Sphere Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Examples.ipynb Initializes a red sphere mesh, a perspective camera with a directional light, and an ambient light within a scene. Renders the scene using a Renderer with OrbitControls. ```python from pythreejs import * import numpy as np from IPython.display import display from ipywidgets import HTML, Text, Output, VBox from traitlets import link, dlink ``` ```python ball = Mesh(geometry=SphereGeometry(radius=1, widthSegments=32, heightSegments=24), material=MeshLambertMaterial(color='red'), position=[2, 1, 0]) c = PerspectiveCamera(position=[0, 5, 5], up=[0, 1, 0], children=[DirectionalLight(color='white', position=[3, 5, 1], intensity=0.5)]) scene = Scene(children=[ball, c, AmbientLight(color='#777777')]) renderer = Renderer(camera=c, scene=scene, controls=[OrbitControls(controlling=c)]) display(renderer) ``` -------------------------------- ### Set up Renderer for Surface Animation Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Animation.ipynb Configures the renderer for the scene containing the parametric surface. OrbitControls are enabled for camera interaction. ```python renderer2 = Renderer(camera=camera2, scene=scene2, controls=[OrbitControls(controlling=camera2)], width=view_width, height=view_height) display(renderer2) ``` -------------------------------- ### Import Utility Libraries Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/threejs/voxel_painter.ipynb Imports standard Python libraries for random number generation, mathematical operations, and numerical computations. ```python import random import math import numpy as np ``` -------------------------------- ### Preview the stream Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Capture.ipynb Displays the captured stream, which should mirror the content of the renderer. ```python stream ``` -------------------------------- ### Create Skinned Mesh Geometry Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Animation.ipynb Sets up a `CylinderBufferGeometry` and converts it into a `BufferGeometry` for skinning. This is the initial step for creating a mesh that can be deformed by bones. ```python import numpy as np N_BONES = 3 ref_cylinder = CylinderBufferGeometry(5, 5, 50, 5, N_BONES * 5, True) cylinder = BufferGeometry.from_geometry(ref_cylinder) ``` -------------------------------- ### Render Superellipsoid with pythreejs Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/superellipsoid.ipynb Creates a pythreejs scene to visualize the superellipsoid. It sets up the geometry, material, camera, and renderer, and displays the interactive 3D plot. ```python from pythreejs import * from ipydatawidgets import create_constrained_arraywidget from IPython.display import display view_width = 600 view_height = 400 coordinate_widget = create_constrained_arraywidget(dtype='float32')(array=coords) surf_g = BufferGeometry(attributes=dict( position=BufferAttribute(coordinate_widget), index=BufferAttribute(cvx.simplices.ravel().astype(np.uint16)), )) surf = Mesh(geometry=surf_g, material=MeshBasicMaterial(color='green', wireframe=True)) scene = Scene(children=[surf, AmbientLight(color='#777777')]) c = PerspectiveCamera(position=[2, 2, 3], up=[0, 0, 1], aspect=view_width / view_height, children=[DirectionalLight(color='white', position=[3, 5, 1], intensity=0.6)]) renderer = Renderer( camera=c, scene=scene, controls=[OrbitControls(controlling=c)], width=view_width, height=view_height) display(renderer) ``` -------------------------------- ### Create a TetrahedronGeometry Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Geometries.ipynb Instantiates a TetrahedronGeometry with a specified radius and detail level. ```python TetrahedronGeometry(radius=10, detail=1, _flat=True) ``` -------------------------------- ### Creating Instanced Line Segments with PyThreeJS Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/ThickLines.ipynb This code defines buffers for line segment positions and colors, then sets up an InstancedBufferGeometry to reuse a base line geometry for each instance. It configures attributes for instance start/end points and colors using InterleavedBufferAttribute. ```python # The line segment points and colors. # Each array of six is one instance/segment [x1, y1, z1, x2, y2, z2] posInstBuffer = InstancedInterleavedBuffer( np.array([ [0, 0, 0, 1, 1, 1], [2, 2, 2, 4, 4, 4] ], dtype=np.float32)) colInstBuffer = InstancedInterleavedBuffer( np.array([ [1, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1] ], dtype=np.float32)) # This uses InstancedBufferGeometry, so that the geometry is reused for each line segment lineGeo = InstancedBufferGeometry(attributes={ # Helper line geometry (2x4 grid), that is instanced 'position': BufferAttribute(np.array([ [ 1, 2, 0], [1, 2, 0], [-1, 1, 0], [1, 1, 0], [-1, 0, 0], [1, 0, 0], [-1, -1, 0], [1, -1, 0] ], dtype=np.float32)), 'uv': BufferAttribute(np.array([ [-1, 2], [1, 2], [-1, 1], [1, 1], [-1, -1], [1, -1], [-1, -2], [1, -2] ], dtype=np.float32)), 'index': BufferAttribute(np.array([ 0, 2, 1, 2, 3, 1, 2, 4, 3, 4, 5, 3, 4, 6, 5, 6, 7, 5 ], dtype=np.uint8)), # The line segments are split into start/end for each instance: 'instanceStart': InterleavedBufferAttribute(posInstBuffer, 3, 0), 'instanceEnd': InterleavedBufferAttribute(posInstBuffer, 3, 3), 'instanceColorStart': InterleavedBufferAttribute(colInstBuffer, 3, 0), 'instanceColorEnd': InterleavedBufferAttribute(colInstBuffer, 3, 3), }) ``` -------------------------------- ### Enable pythreejs Jupyter Notebook Extension Source: https://github.com/jupyter-widgets/pythreejs/blob/master/docs/source/installing.md Enable the pythreejs Jupyter Notebook extension. Use --sys-prefix, --user, or --system based on your environment. ```bash jupyter nbextension enable [--sys-prefix / --user / --system] --py pythreejs ``` -------------------------------- ### Create ShaderMaterial with uniforms and defines Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Shaders.ipynb Instantiates a ShaderMaterial with specified uniforms, defines, and shader code. Includes common uniforms from UniformsLib. ```python material = ShaderMaterial( uniforms=dict( time=dict(value=0.0), resolution=dict(value=(1, 1)), user_color=dict(value='green'), **UniformsLib['common'] ), defines=dict( FIX_COLOR=1, ), vertexShader=vertex_shader, fragmentShader=fragment_shader, ) ``` -------------------------------- ### Create and Configure Surface Mesh and Grid Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/threejs/voxel_painter.ipynb Sets up the visual representation of the surface using a Mesh and its corresponding wireframe grid. The surface is rotated to be horizontal. ```python surf_grid = SurfaceGrid( geometry = surf_geo, material = LineBasicMaterial( color = '#000000', opacity = 0.2, transparent = True, ), ) surface = Mesh( geometry = surf_geo, material = MeshBasicMaterial( color = '#00ff00', opacity = 0.3, transparent = True, side = 'DoubleSide', ), visible = True ) m = rotation_matrix(-math.pi/2) surface.setRotationFromMatrix(m) surf_grid.setRotationFromMatrix(m) ``` -------------------------------- ### Build Python Distributions Source: https://github.com/jupyter-widgets/pythreejs/blob/master/CONTRIBUTING.md Build the source distribution (sdist) and wheel (bdist_wheel) for the Python package. ```bash python setup.py sdist bdist_wheel ``` -------------------------------- ### Create Sphere Geometry with Morph Target Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Animation.ipynb Initializes a sphere geometry and prepares it for morph target manipulation. Allow the sync to complete before proceeding. ```python # This lets three.js create the geometry, then syncs back vertex positions etc. # For this reason, you should allow for the sync to complete before executing # the next cell. morph = BufferGeometry.from_geometry(SphereBufferGeometry(1, 32, 16)) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/renderer_limit.ipynb Imports pythreejs and ipywidgets for creating and displaying 3D objects and interactive elements. ```python from pythreejs import * from ipywidgets.widgets import HBox, VBox, Layout import time ``` -------------------------------- ### Create a Torus Geometry Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Geometries.ipynb Instantiates a TorusGeometry with specified radius, tube, segment counts, and arc. ```python TorusGeometry( radius=20, tube=5, radialSegments=20, tubularSegments=6, arc=1.5*pi) ``` -------------------------------- ### Create interactive uniform editors and update function Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Shaders.ipynb Sets up interactive widgets (ColorPicker, FloatSlider) to control shader uniforms and defines a callback function to update the material. ```python # Uniform editors: picker = widgets.ColorPicker(value=material.uniforms['user_color']['value']) time_slider = widgets.FloatSlider(value=material.uniforms['time']['value'], min=-15, max=15) # Interactive code: def update_uniforms(change): uniforms = dict(**material.uniforms) uniforms.update( time=dict(value=time_slider.value), user_color=dict(value=picker.value), ) material.uniforms = uniforms material.needsUpdate = True picker.observe(update_uniforms) time_slider.observe(update_uniforms) # Present "dashboard" in VBox: widgets.VBox([ Preview(material), picker, time_slider, ]) ``` -------------------------------- ### Create a ParametricGeometry Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Geometries.ipynb Instantiates a ParametricGeometry using a custom function, slices, and stacks. ```python ParametricGeometry( func="""function(u,v,out) { var x = 5 * (0.5 - u); var y = 5 * (0.5 - v); out.set(10 * x, 10 * y, x*x - y*y); }""", slices=5, stacks=10, _flat=True) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/BufferAttributes and BufferGeometry.ipynb Imports the required pythreejs modules, IPython display functionality, and numpy for numerical operations. ```python from pythreejs import * from IPython.display import display import numpy as np ``` -------------------------------- ### Import necessary libraries Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/ThickLines.ipynb Imports the required pythreejs, IPython, and numpy modules for creating 3D visualizations. ```python from pythreejs import * from IPython.display import display from ipywidgets import VBox, HBox, Checkbox, jslink import numpy as np ``` -------------------------------- ### Observe image changes and capture output Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Capture.ipynb Sets up an observer to print a message whenever the captured image changes and displays an output widget to capture these messages. ```python out = Output() # To capture print output @out.capture() def on_capture(change): print('Captured image changed!') recorder.image.observe(on_capture, 'value') out ``` -------------------------------- ### Import necessary libraries Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/Renderer.ipynb Imports the required pythreejs, IPython.display, and ipywidgets modules for creating and displaying 3D visualizations. ```python from pythreejs import * from IPython.display import display import ipywidgets ``` -------------------------------- ### Arrange multiple WebGLRenderers Source: https://github.com/jupyter-widgets/pythreejs/blob/master/examples/renderer_limit.ipynb Arranges multiple WebGLRenderer instances within HBox and VBox containers for display. ```python hboxes = [] for i in range(5): views = [] for j in range(5): views.append(r) hbox = HBox(children=views) hboxes.append(hbox) vbox = VBox(children=hboxes) r.layout.padding = '5px' vbox ``` -------------------------------- ### Clone pythreejs Repository Source: https://github.com/jupyter-widgets/pythreejs/blob/master/docs/source/develop-install.md Clone the pythreejs repository to your local machine to begin development. ```bash git clone https://github.com/jupyter-widgets/pythreejs.git cd pythreejs ```