Skip to content

Latest commit

 

History

History
1388 lines (1077 loc) · 72.5 KB

KeyShotPythonScripting_API_UnderstandingTheBasics_Guide.md

File metadata and controls

1388 lines (1077 loc) · 72.5 KB

Understanding the Basics

Table of Contents

  1. Understanding the Basics

  2. lux Library Classes

  3. lux Library Functions

  4. lux Library Constants

  5. Key Concepts in Scripting

  6. Script Examples Reference

  7. luxmath

  8. Modular Scripts

  9. Agnostic Scripting

  10. Scene Tree

  1. Material Graph

KeyShot Python Basics:

Since KeyShot scripting is based on Python, getting comfortable with Python's syntax, data types, control structures (like loops and conditionals), and basic data structures (like lists and dictionaries) will provide a strong foundation.

KeyShot Scripting Environment:

Familiarize yourself with the KeyShot Scripting Console and how to execute scripts within KeyShot. It’s a great place to test small snippets of code and see immediate results in the KeyShot environment.

Exploring KeyShot Scripting Documentation:

Documentation: KeyShot provides documentation on its Python API, accessible directly through the Help menu in KeyShot. This documentation is invaluable for understanding what functions and classes are available for scripting.

Practical Exercises:

Start Small:

Begin with simple scripts, like changing the color of a material or automating camera movements. Gradually increase complexity as you become more comfortable.

Scripting Challenges: Set small, achievable goals, such as automating a part of your workflow that you find repetitive. This could be as simple as exporting renderings with different camera angles or applying materials to multiple models programmatically.

Debugging and Problem Solving:

Debugging: Learn the basics of debugging Python scripts. KeyShot's Script Console will show errors and print statements, which can help you understand what your script is doing and identify any issues.

Online Communities: Don’t hesitate to seek help from online forums or communities. The KeyShot forum itself can be a great resource, as well as broader Python programming communities.

Best Practices:

Version Control: As you become more comfortable with scripting, consider using a version control system like Git. This allows you to track changes to your scripts over time, making it easier to experiment without losing work.

Read and Refactor: Read other people's code whenever possible. This can provide new insights and techniques that you can incorporate into your own scripts. Also, regularly revisit and refactor your code to improve its efficiency and readability.

Continuous Learning:

Keep Exploring: The world of scripting and automation is vast. As you grow more confident in your skills, explore more advanced topics like creating user interfaces within KeyShot, integrating with external APIs, or even automating the entire pipeline from model import to final rendering.

lux Library Classes:

The lux library within KeyShot's Python environment includes a variety of classes designed to interact with and manipulate aspects of KeyShot scenes, from rendering settings and materials to scene structure and camera settings. Here's a detailed list of the classes available in the lux library:

Quick Reference:

KeyShot Python API Classes and Their General Functionalities

  1. ColorParameter: Manages color-related parameters in materials or environments.
  2. Colorway: Handles colorway settings for multi-materials or studios.
  3. Env: Configures environment settings like background, lighting, etc.
  4. ImageStyle: Controls image style settings for render outputs.
  5. MaterialGraph: Represents and manipulates the material graph structure.
  6. MaterialMetadata: Manages metadata associated with materials.
  7. MultiMaterial: Manages and configures multi-materials.
  8. RenderOptions: Sets options for rendering, such as resolution and quality.
  9. SceneNode: Represents nodes in the scene tree for manipulation.
  10. ShaderEdge: Handles connections between shader nodes in material graphs.
  11. ShaderNode: Represents individual shader nodes in material graphs.
  12. ShaderParameter: Manages parameters of shader nodes.
  13. Studio: Configures studio settings, including camera, environment, and model sets.
  14. ThumbnailRenderOptions: Sets rendering options for thumbnails.
  15. Animation: Controls animation-related settings and operations.
  16. BloomParameter: Manages bloom effect parameters in image styles.
  17. Curve: Represents and manipulates curve data.
  18. CurveControlPoint: Manages control points for curves.
  19. CurveParameter: Handles curve parameters in shader nodes.
  20. DenoiseParameter: Configures denoise settings in render options.
  21. Display: Controls display settings within KeyShot.
  22. FlakeParameter: Manages flake effect parameters in materials.
  23. GeometryNode: Represents geometry nodes in the scene.
  24. GeometryShaders: Manages shaders applied to geometries.
  25. Image: Handles image data and operations.
  26. ImageEffects: Configures post-processing effects on images.
  27. ImageLayers: Manages layers in composite images.
  28. Label: Controls label properties on materials.
  29. Light: Manages light sources in the scene.
  30. LightMaterial: Handles materials specifically for lights.
  31. Material: Represents and manipulates materials.
  32. NormalMapParameter: Manages normal map parameters in materials.
  33. NumberParameter: Handles numeric parameters in shader nodes.
  34. OrthographicCamera: Configures orthographic camera settings.
  35. PanoramicCamera: Manages panoramic camera settings.
  36. PerspectiveCamera: Controls perspective camera properties.
  37. ProceduralTexture: Handles procedural textures in materials.
  38. RenderLayers: Manages render layers in the scene.
  39. ScatteringMedium: Configures settings for volume scattering.
  40. SphericalCamera: Manages spherical camera settings.
  41. Texture: Represents and manipulates texture data.
  42. TextureParameter: Manages texture parameters in materials.
  43. ToonMaterial: Handles toon shader materials.
  44. VideoMap: Manages video textures.
  45. Volume: Represents volumetric materials or effects.

lux Library Functions:

The lux library in KeyShot's Python environment provides a range of functions to script and automate tasks within KeyShot, such as rendering, scene manipulation, camera control, and more. Here's a detailed list of the functions available in the lux library, based on the provided documentation:

Standard Functions

lux.getActiveEnvironment(): Retrieves the currently active environment settings. lux.getOS(): Returns the operating system version string. lux.getObjectMaterial(): Gets the material applied to the specified object(s). lux.getObjects(): Retrieves the object IDs of the scene. lux.getRenderEngine(): Obtains the render engine currently in use. lux.getRenderLayers(): Returns a list of render layers in the current scene. lux.getRenderOptions(): Provides render options as a lux.RenderOptions object. lux.getSceneInfo(): Yields information about the scene, including name, file name, unit/meter scale, and number of triangles, objects, nurbs, curves, scene width/height, and rendering width/height. lux.getSceneMaterials(): Retrieves materials currently used in the scene. lux.getLocked(): Obtains locked nodes of a group (recursively). lux.getMaterial(): Fetches the material of a node. lux.getName(): Gets the name of a node. lux.getParent(): Retrieves the parent node of a specified node. lux.getPath(): Provides the path from the root to the specified node as a tuple of lux.SceneNode objects. lux.getRenderLayer(): Fetches the render layer associated with a node, if any. lux.getSelected(): Obtains selected nodes of a group (recursively). lux.getTransform(): Gets the transformation matrix of a node. lux.getLightingPreset(): Retrieves the currently used lighting preset. lux.getLightingPresets(): Fetches a list of lighting presets, both default and custom ones. lux.getLockResolution(): Indicates whether the resolution is locked or not. lux.getMaterialGraph(): Retrieves a lux.MaterialGraph object representing the material graph for a given material name. lux.getMaterialMapping(): Provides material mapping: object ID to material name. lux.getMaterialTemplates(): Fetches material template names. lux.getMetaData(): Obtains metadata of the scene. lux.getModelSets(): Returns the list of active model sets. lux.getMultiMaterial(): Retrieves a multi-material instance from its name. lux.getSceneTree(): Provides a lux.SceneNode object representing the root of the scene tree. lux.getSphericalCamera(): Fetches spherical information of the active camera in degrees. lux.getStudios(): Retrieves studio names of the scene. lux.getSystemInfo(): Yields information about the system as a dictionary. lux.getActiveStudio(): Obtains the active studio of the scene. lux.getAnimationFrame(): Returns the current animation frame. lux.getAnimationInfo(): Provides information about the animation, including duration in seconds and the number of frames. lux.getAnimationTime(): Yields the current animation time in seconds. lux.getBrowserDialog(): Shows a browser dialog for loading either URL or HTML contents. lux.getActiveCamera(): Retrieves the currently active camera. lux.getActiveEnvironment(): Retrieves the current active environment. lux.getActiveImageStyle(): Gets the currently active image style. lux.getActiveMaterial(): Retrieves the currently active material. lux.getActiveModelSet(): Gets the current active model set. lux.getActiveRenderLayer(): Retrieves the current active render layer. lux.getActiveScene(): Gets the currently active scene. lux.getActiveStudio(): Retrieves the current active studio. lux.getAnimation(): Retrieves information about a specific animation. lux.getAnimations(): Gets a list of animations in the scene. lux.getBackground(): Retrieves the current background settings. lux.getCameras(): Returns a list of cameras in the scene. lux.getEnvironment(): Retrieves a specific environment. lux.getEnvironments(): Lists all environments in the scene. lux.getImageStyles(): Retrieves a list of image styles. lux.getMaterialGraph(): Represents and manipulates the material graph structure. lux.getMaterial(): Retrieves a specific material. lux.getMaterials(): Lists all materials in the scene. lux.getModelSets(): Retrieves model sets in the scene. lux.getRenderLayer(): Gets a specific render layer. lux.getRenderLayers(): Retrieves all render layers in the scene. lux.getRenderOptions(): Gets the current render options. lux.getExternalFiles() (Headless): Lists external files associated with the scene. lux.getImportOptions() (Headless): Retrieves current import options. lux.getKeyShotDisplayVersion() (Headless): Gets the display version of KeyShot. lux.getKeyShotFolder(type=lux.FOLDER_RESOURCE_ROOT) (Headless): Returns the configured resource root. lux.getKeyShotVersion() (Headless): Retrieves the full KeyShot version. lux.getLibraryBackplates(), getLibraryColors(), getLibraryEnvironments(), getLibraryMaterials(), getLibraryTextures() (Headless): Retrieves lists of library items. lux.getLightingPreset() (Headless): Gets the current lighting preset. lux.getMaterialMapping() (Headless): Returns material mapping information. lux.getMaterialTemplates() (Headless): Lists available material templates. lux.getMetaData() (Headless): Retrieves metadata of the scene. lux.getModelSets() (Headless): Returns model sets in the scene. lux.getMultiMaterial() (Headless): Retrieves a multi-material. lux.getOS() (Headless): Identifies the operating system. lux.getObjectMaterial() (Headless): Gets the material applied to objects. lux.getObjects() (Headless): Retrieves objects in the scene. lux.getRenderEngine() (Headless): Determines the render engine in use. lux.getSceneInfo() (Headless): Provides detailed information about the scene. lux.getSceneMaterials() (Headless): Retrieves materials used in the scene. lux.getSphericalCamera() (Headless): Fetches spherical camera settings. lux.getSystemInfo() (Headless): Provides system information. lux.isHeadless(): Checks if KeyShot is running in headless mode. lux.setRenderEngine(engine): Sets the render engine to use for the scene. lux.setSphericalCamera(azimuth, incl, twist): Sets spherical information of the active camera. lux.setStandardView(view): Sets the standard view of the currently active camera. lux.setAdvancedRendering(samples): Enables rendering in advanced mode with specified samples. lux.setAntiAliasing(level): Sets the anti-aliasing level. lux.setBackgroundRendering(ext): Enables rendering in an external background process. lux.setCausticsQuality(quality): Sets the caustics quality. lux.setDofQuality(quality): Sets the depth-of-field quality. lux.setGlobalIllumination(quality): Sets the global illumination quality. lux.setActiveEnvironment(name): Sets the active environment of the scene. lux.setActiveImageStyle(name): Sets the active image style of the scene. lux.setCurrentSubMaterial(node): Sets the sub-material to the specified node. lux.setMultiMaterial(enable): Controls multi-material features of the material graph. lux.setSceneUnit(unit, keep): Sets the scene unit and optionally rescales the scene. lux.setMaterial(mat, link): Sets the material of a node, with the option to link to the material or create a duplicate. lux.setName(name): Sets the name of a node. lux.setRenderLayer(name): Associates a node with a render layer, creating it if the name is non-existent. lux.applyMaterialMapping(mapping): Applies a material mapping to objects. lux.createColorway(): Creates a new colorway. lux.createMultiMaterial(): Creates a new multi-material. lux.exportFile(filePath, options): Exports the current scene or parts of it. lux.getFileDialog(): Opens a file dialog window. lux.getInputDialog(): Displays an input dialog to the user. lux.getMessageWindow(): Shows a message window to the user. lux.getThumbnailRenderOptions(): Retrieves thumbnail render options. lux.renderImage(filePath, options): Initiates the rendering process with specified options. lux.renderPreview(filePath, options): Renders a preview image with specified options. lux.showRenderDialog(): Shows the render dialog. lux.startAnimationRender(filePath, options): Starts rendering an animation with specified options. lux.updateEnvironmentLighting(): Updates the lighting of the current environment. lux.useLibraryMaterial(materialName, objectName): Applies a material from the library to an object. lux.viewSetCamera(cameraName): Sets the active view to a specified camera.

Additionally, here are a few more general functions that are worth noting for completeness, which facilitate script execution, interaction with the KeyShot user interface, and scene configuration:

lux.setAnimationFrame(frame): Sets the current frame in an animation timeline. lux.setAnimationTime(time): Sets the current time in seconds in an animation timeline. lux.showMessage(title, message, type): Displays a custom message window. lux.startBatchRender(): Starts batch rendering based on pre-configured batch settings. lux.startRealtimeRender(): Starts a realtime render in the KeyShot Real-time View. lux.stopAnimationRender(): Stops the currently running animation render. lux.syncExec(function): Synchronously executes a function, ensuring that script execution waits until the function has completed.

Headless-Specific Functions

Headless lux.get Functions: lux.getExternalFiles(): Lists external files associated with the scene. lux.getImportOptions(): Retrieves current import options. lux.getKeyShotDisplayVersion(): Gets the display version of KeyShot. lux.getKeyShotFolder(type=lux.FOLDER_RESOURCE_ROOT): Returns the configured resource root. lux.getKeyShotVersion(): Retrieves the full KeyShot version. lux.getLibraryBackplates(): Retrieves lists of library backplates. lux.getLibraryColors(): Retrieves lists of library colors. lux.getLibraryEnvironments(): Retrieves lists of library environments. lux.getLibraryMaterials(): Retrieves lists of library materials. lux.getLibraryTextures(): Retrieves lists of library textures. lux.getLightingPreset(): Gets the current lighting preset. lux.getMaterialMapping(): Returns material mapping information. lux.getMaterialTemplates(): Lists available material templates. lux.getMetaData(): Retrieves metadata of the scene. lux.getModelSets(): Returns model sets in the scene. lux.getMultiMaterial(): Retrieves a multi-material. lux.getOS(): Identifies the operating system. lux.getObjectMaterial(): Gets the material applied to objects. lux.getObjects(): Retrieves objects in the scene. lux.getRenderEngine(): Determines the render engine in use. lux.getSceneInfo(): Provides detailed information about the scene. lux.getSceneMaterials(): Retrieves materials used in the scene. lux.getSphericalCamera(): Fetches spherical camera settings. lux.getSystemInfo(): Provides system information. Headless lux.set Functions: lux.setActiveEnvironment(name): Sets the active environment of the scene. lux.setActiveImageStyle(name): Sets the active image style. lux.setActiveStudio(name): Sets the active studio. lux.setAnimationFrame(frame): Sets the current animation frame. lux.setAnimationTime(seconds): Sets the current animation time in seconds. lux.setCamera(camera): Sets the active camera. lux.setCameraDirection(direction): Sets the camera direction. lux.setCameraDistance(distance): Sets the camera distance. lux.setCameraFieldOfView(fov): Sets the camera field of view. lux.setCameraFocalLength(length): Sets the camera focal length. lux.setCameraLookAt(point): Sets the camera look-at point. lux.setCameraOrthographic(enable): Enables or disables orthographic camera mode. lux.setCameraPanoramic(enable): Enables or disables panoramic camera mode. lux.setCameraPerspective(enable): Enables or disables perspective camera mode. lux.setCameraPosition(position): Sets the camera position. lux.setCameraShift(shift): Sets the camera shift. lux.setCameraUp(up): Sets the camera up vector. lux.setLightingPreset(preset): Sets the lighting preset. lux.setLockResolution(lock): Locks or unlocks the resolution. lux.setMaterialTemplate(template): Applies a material template. lux.setModelSets(sets): Sets the model sets. lux.setObjectMaterial(obj, mat): Sets the material for an object. lux.setRenderEngine(engine): Sets the render engine. lux.setSphericalCamera(azimuth, inclination, twist): Sets spherical camera settings. lux.setStandardView(view): Sets a standard camera view. lux.clearGeometry(): Clears all geometry from the scene. lux.createSceneMaterial(materialType, properties): Creates a new material in the scene of the specified type with given properties. lux.deleteMaterial(materialName): Deletes the specified material from the scene. lux.enablePerformanceMode(enable): Enables or disables performance mode. lux.encodeVideo(inputFolder, outputFile, startFrame, endFrame, fps, format): Encodes a sequence of images into a video file. lux.findMaterialMetadata(materialName): Finds metadata for the specified material. lux.hasContents(): Checks if the current scene has any content. lux.importMaterials(materialFile): Imports materials from a specified file. lux.isCameraUnsaved(cameraName): Checks if the specified camera has unsaved changes. lux.isPaused(): Checks if the headless render is paused. lux.isPerformanceModeEnabled(): Checks if performance mode is enabled. lux.isSceneChanged(): Checks if the current scene has been changed since the last save. lux.loadMaterials(materialFile): Loads materials from a specified file. lux.openFile(filePath): Opens a KeyShot scene file. lux.openPackage(packagePath): Opens a KeyShot package file. lux.pause(): Pauses the current headless render. lux.prettyPrint(object): Pretty prints the representation of an object, useful for debugging. lux.processQueue(): Processes the internal KeyShot queue, allowing for batch operations. lux.renderCMF(filePath, options): Renders a Color Material Finish (CMF) document. lux.saveCamera(cameraName, filePath): Saves the specified camera settings to a file. lux.saveFile(filePath, options): Saves the current scene to a file with specified options. lux.saveMaterial(materialName, filePath): Saves the specified material to a file. lux.saveMaterialMetadata(materialName, filePath): Saves metadata for the specified material to a file. lux.saveMaterialPackage(materialName, packagePath): Saves the specified material to a package file. lux.savePackage(packagePath, options): Saves the current scene to a package file with specified options. lux.setKeepAspectRatio(keep): Sets whether to keep the aspect ratio of the camera. lux.sync(): Forces a synchronization of the scene, ensuring all operations are up to date. lux.unpause(): Resumes the current headless render if it was paused.

lux Library Constatnts:

The lux library in KeyShot's Python environment provides a comprehensive set of constants that are used across various functions and classes to specify options, settings, and behaviors in a standardized manner. Here is a detailed list of constants available in the lux library, as extracted from the provided documentation:

Constants

KeyShot GUI

DIALOG_CHECK = 4
DIALOG_DOUBLE = 2
DIALOG_FILE = 5
DIALOG_FOLDER = 6
DIALOG_INTEGER = 1
DIALOG_ITEM = 3
DIALOG_LABEL = 7
DIALOG_TEXT = 0

Export Options

EXPORT_3MF = 5
EXPORT_BAKING = 4
EXPORT_FBX = 1
EXPORT_GLTF = 2
EXPORT_OBJ = 0
EXPORT_OUTPUT_GEOMETRY_SHADERS = 1
EXPORT_OUTPUT_TEXTURES = 0
EXPORT_SINGLE_COLOR = 0
EXPORT_STL = 4
EXPORT_SUB_DIV_ADAPTIVE = 2
EXPORT_SUB_DIV_EDGE_LENGTH = 1
EXPORT_SUB_DIV_NORMAL = 1
EXPORT_SUB_DIV_POLYCOUNT = 0
EXPORT_USD = 6
EXPORT_VERTEX_COLOR = 1

Image Style

IMAGE_STYLE_BASIC = 0
IMAGE_STYLE_PHOTOGRAPHIC = 1

Veiwer Options

KSP_VIEWER_SHOW_LOGO = 1
KSP_VIEWER_SHOW_WATERMARK = 2

Message Window

MESSAGE_BOX_CRITICAL = 3
MESSAGE_BOX_INFO = 1
MESSAGE_BOX_WARNING = 2

Meta:

META_DATA_SIMPLE = 1
META_DATA_XMP = 0

Thumbnail Models

MODEL_ID_CLOTH_DRAPE = 'ClothDrape_100x200_mm'
MODEL_ID_CRYSTAL = 'Crystal'
MODEL_ID_LIQUID_GLASS = 'LiquidGlass_60_mm'
MODEL_ID_LUXION_SPHERE = 'LuxionSphere'
MODEL_ID_MATERIAL_DISC_100_MM = 'MaterialDisc_100_mm'
MODEL_ID_MATERIAL_DISC_1_M = 'MaterialDisc_1_m'
MODEL_ID_MATERIAL_DISC_25_MM = 'MaterialDisc_25_mm'
MODEL_ID_MATERIAL_DISC_TOON_100_MM = 'MaterialDiscToon_100_mm'
MODEL_ID_SPHERE_CUTAWAY_100_MM = 'SphereCutaway_100_mm'

NODEs:

NODE_TYPE_ANIMATION = 3
NODE_TYPE_CAMERA = 6
NODE_TYPE_GROUP = 1
NODE_TYPE_MODEL = 5
NODE_TYPE_MODEL_SET = 4
NODE_TYPE_OBJECT = 2

Parameter Types Constants

Identifiers for different parameter types, e.g., PARAMETER_TYPE_BOOLEAN = 1, PARAMETER_TYPE_COLOR = 13, etc.

All Parameters

PARAMETER_TYPE_ANIMATIONCURVE = 17
PARAMETER_TYPE_AXALTACOLOR = 18
PARAMETER_TYPE_BOOLEAN = 1
PARAMETER_TYPE_COLOR = 13
PARAMETER_TYPE_COLORALPHA = 14
PARAMETER_TYPE_COLORGRADIENT = 16
PARAMETER_TYPE_DOUBLE = 7
PARAMETER_TYPE_DOUBLE3 = 8
PARAMETER_TYPE_FLOAT = 4
PARAMETER_TYPE_FLOAT2 = 5
PARAMETER_TYPE_FLOAT3 = 6
PARAMETER_TYPE_FLOATARRAY = 15
PARAMETER_TYPE_INTEGER = 2
PARAMETER_TYPE_INTEGERLIST = 3
PARAMETER_TYPE_MATRIX = 12
PARAMETER_TYPE_SHADERBUMP = 65539
PARAMETER_TYPE_SHADERGEOMETRY = 65540
PARAMETER_TYPE_SHADERLABEL = 65538
PARAMETER_TYPE_SHADERSURFACE = 65537
PARAMETER_TYPE_SHADERUV = 65541
PARAMETER_TYPE_STRING = 9
PARAMETER_TYPE_STRINGLIST = 10
PARAMETER_TYPE_WEAVEPATTERN = 19

Render Settings and Options

RENDER_ENGINE_INTERIOR = 1
RENDER_ENGINE_INTERIOR_GPU = 4
RENDER_ENGINE_PRODUCT = 0
RENDER_ENGINE_PRODUCT_GPU = 3
RENDER_MODE_ADVANCED = 0
RENDER_MODE_SAMPLES = 2
RENDER_MODE_TIME = 1
RENDER_OUTPUT_EXR = 2
RENDER_OUTPUT_JPEG = 0
RENDER_OUTPUT_PNG = 5
RENDER_OUTPUT_PSD16 = 8
RENDER_OUTPUT_PSD32 = 7
RENDER_OUTPUT_PSD8 = 6
RENDER_OUTPUT_TIFF32 = 3
RENDER_OUTPUT_TIFF8 = 1

Save Constants:

Options for excluding certain data when saving KeyShot scenes, e.g., SAVE_EXCLUDE_ANIMATIONS = 128, SAVE_EXCLUDE_CAMERAS = 8, etc.

Save

SAVE_EXCLUDE_ANIMATIONS = 128
SAVE_EXCLUDE_CAMERAS = 8
SAVE_EXCLUDE_CONFIGURATOR = 1
SAVE_EXCLUDE_ENVIRONMENTS = 16
SAVE_EXCLUDE_GEOMETRY = 4
SAVE_EXCLUDE_IMAGE_STYLES = 32
SAVE_EXCLUDE_NURBS = 64
SAVE_EXCLUDE_STUDIOS = 2

Shader Nodes Constants:

Identifiers for different shader types, e.g., SHADER_TYPE_ADVANCED, SHADER_TYPE_ANISOTROPIC, SHADER_TYPE_AXALTA_PAINT, etc.

Shader NODEs:

SHADER_TYPE_ADVANCED = 'lux_advanced'
SHADER_TYPE_ANISOTROPIC = 'lux_anisotropic'
SHADER_TYPE_AXALTA_PAINT = 'dupont_paint'
SHADER_TYPE_BAKED_PLASTIC = 'lux_baked_plastic'
SHADER_TYPE_BRUSHED = 'lux_brushed2'
SHADER_TYPE_BRUSHED_RADIAL = 'lux_brushed_solid'
SHADER_TYPE_BUBBLES = 'lux_bubbles'
SHADER_TYPE_BUMP_ADD = 'lux_bumpmap_add'
SHADER_TYPE_BUMP_TO_ROUGHNESS = 'lux_bump2roughness'
SHADER_TYPE_CAMOUFLAGE = 'lux_camouflage'
SHADER_TYPE_CELLULAR = 'lux_worley'
SHADER_TYPE_COLOR_ADJUST = 'lux_color_adjust'
SHADER_TYPE_COLOR_COMPOSITE = 'lux_color_blend'
SHADER_TYPE_COLOR_FADE = 'animation_color'
SHADER_TYPE_COLOR_GRADIENT = 'lux_color_gradient'
SHADER_TYPE_COLOR_INVERT = 'lux_color_invert'
SHADER_TYPE_COLOR_KEY_MASK = 'lux_color_distance'
SHADER_TYPE_COLOR_TO_NUMBER = 'convert_rgba_to_float'
SHADER_TYPE_CONTOUR = 'lux_contour_tex'
SHADER_TYPE_CURVATURE = 'lux_curvature'
SHADER_TYPE_CURVE_COLOR_RANDOMIZE = 'lux_curve_randomize'
SHADER_TYPE_CURVE_FADE = 'animation_curve'
SHADER_TYPE_CUTAWAY = 'lux_cutaway'
SHADER_TYPE_DIELECTRIC = 'lux_glass'
SHADER_TYPE_DIFFUSE = 'lux_diffuse'
SHADER_TYPE_DISPLACE = 'lux_displace'
SHADER_TYPE_EMISSIVE = 'lux_emissive'
SHADER_TYPE_FIBER_WEAVE = 'lux_carbon'
SHADER_TYPE_FLAKES = 'lux_flakes'
SHADER_TYPE_FLAT = 'lux_constant'
SHADER_TYPE_FUZZ = 'lux_fuzz'
SHADER_TYPE_GEM = 'lux_gem'
SHADER_TYPE_GENERAL = 'lux_general'
SHADER_TYPE_GENERIC = 'lux_generic'
SHADER_TYPE_GLASS = 'lux_window_glass'
SHADER_TYPE_GLASS_SOLID = 'lux_glass_simple'
SHADER_TYPE_GRANITE = 'lux_granite'
SHADER_TYPE_GROUND = 'lux_ground'
SHADER_TYPE_IES_LIGHT = 'lux_ies_light'
SHADER_TYPE_LEATHER = 'lux_leather_tex'
SHADER_TYPE_LIQUID = 'lux_liquid'
SHADER_TYPE_MAPPING_2D = 'mapping2d'
SHADER_TYPE_MAPPING_WARP = 'lux_mapping_warp'
SHADER_TYPE_MARBLE = 'lux_marble'
SHADER_TYPE_MATCAP = 'matcap'
SHADER_TYPE_MEASURED = '__measured'
SHADER_TYPE_MESH = 'lux_mesh'
SHADER_TYPE_MESH_CIRCULAR = 'lux_lattice_circular'
SHADER_TYPE_MESH_LIGHT = 'lux_mesh_light'
SHADER_TYPE_MESH_POLYGON = 'lux_lattice_polygon'
SHADER_TYPE_METAL = 'lux_metal'
SHADER_TYPE_METALLIC_PAINT = 'metallic_paint'
SHADER_TYPE_MOLD_TECH_PLASTIC = 'lux_moldtech_plastic'
SHADER_TYPE_NOISE_FRACTAL = 'lux_fractal_noise'
SHADER_TYPE_NOISE_TEXTURE = 'lux_noise'
SHADER_TYPE_OCCLUSION = 'lux_occlusion_tex'
SHADER_TYPE_PAINT = 'lux_paint'
SHADER_TYPE_PLASTIC = 'lux_plastic_simple'
SHADER_TYPE_PLASTIC_CLOUDY = 'lux_cloudy_plastic'
SHADER_TYPE_PLASTIC_FIBER = 'lux_textile_fiber'
SHADER_TYPE_PLASTIC_TRANSPARENT = 'lux_plastic'
SHADER_TYPE_POINT_LIGHT = 'lux_point_light'
SHADER_TYPE_RAY_MASK = 'lux_ray_mask'
SHADER_TYPE_REALCLOTH = 'lux_real_cloth'
SHADER_TYPE_ROUNDED_EDGES = 'lux_rounded'
SHADER_TYPE_SCATTERING_MEDIUM = 'lux_scattering_medium'
SHADER_TYPE_SCRATCHES = 'lux_scratches_worley'
SHADER_TYPE_SPOTLIGHT = 'lux_spotlight'
SHADER_TYPE_SPOTS = 'lux_spots'
SHADER_TYPE_TEXTURE_MAP = '__texture'
SHADER_TYPE_THIN_FILM = 'lux_thinfilm'
SHADER_TYPE_TILED_UV = 'lux_tiled_texturemap'
SHADER_TYPE_TOON = 'lux_toon'
SHADER_TYPE_TRANSLUCENT = 'lux_translucent'
SHADER_TYPE_TRANSLUCENT_ADVANCED = 'lux_translucent2'
SHADER_TYPE_TRANSLUCENT_MEDIUM = 'lux_translucent_mc'
SHADER_TYPE_TRI_PLANAR = 'triplanar'
SHADER_TYPE_VELVET = 'lux_velvet'
SHADER_TYPE_VERTEX_COLOR = 'lux_vertex_color'
SHADER_TYPE_VIDEO_MAP = 'sequence_rgba'
SHADER_TYPE_VOLUME_MAP = 'lux_volume'
SHADER_TYPE_WEAVE = 'lux_weave2'
SHADER_TYPE_WIREFRAME = 'show_wireframe'
SHADER_TYPE_WOOD = 'lux_wood'
SHADER_TYPE_WOOD_ADVANCED = 'lux_wood2'
SHADER_TYPE_XRAY = 'lux_xray'

Scene Units Constants:

Scene Units

UNIT_CM = 1
UNIT_FT = 3
UNIT_IN = 2
UNIT_M = 4
UNIT_MM = 0

Camera Constants:

Constants for specifying camera types and views, e.g., CAMERA_TYPE_ORTHOGRAPHIC, VIEW_FRONT, VIEW_BACK, etc.

Camera

CAMERA_TYPE_ORTHOGRAPHIC = 65536
CAMERA_TYPE_PANORAMA = 4096
CAMERA_TYPE_PERSPECTIVE = 16384
CAMERA_TYPE_PERSPECTIVE_STEREO = 32768
CAMERA_TYPE_SHIFT = 8192
PANORAMA_TYPE_CUBEMAP = 1
PANORAMA_TYPE_SPHERICAL = 0
VIEW_BACK = 2
VIEW_BOTTOM = 6
VIEW_FRONT = 1
VIEW_ISOMETRIC = 7
VIEW_LEFT = 3
VIEW_RIGHT = 4
VIEW_TOP = 5
XR_CENTER_CAMERA = 4
XR_CENTER_CAMERA_PIVOT = 5
XR_CENTER_ENVIRONMENT = 1
XR_CENTER_OBJECT = 2
XR_TYPE_CUSTOM = 5
XR_TYPE_HEMISPHERICAL = 3
XR_TYPE_SPHERICAL = 2
XR_TYPE_TUMBLE = 4
XR_TYPE_TURNTABLE = 1

CMF Exclusive

CMF_KIND_COLOR_CMYK = 4
CMF_KIND_COLOR_HEX = 6
CMF_KIND_COLOR_LAB = 5
CMF_KIND_COLOR_NAME = 2
CMF_KIND_COLOR_RGB = 3
CMF_KIND_COLOR_SWATCH = 7
CMF_KIND_IMAGE = 1
CMF_KIND_TEXT = 0

Query the KeyShot Studio 2026.3 resource folder configured for the current session.

library_path = lux.getKeyShotFolder(type=lux.FOLDER_RESOURCE_ROOT)

Library Constants

FOLDER_ANIMATIONS = 8
FOLDER_BACKPLATES = 3
FOLDER_COLORS = 9
FOLDER_CONFIG_ROOT = 14
FOLDER_DOWNLOADS = 16
FOLDER_ENVIRONMENTS = 5
FOLDER_EXTERNAL_PLUGIN = 13
FOLDER_FAVORITES = 11
FOLDER_MATERIALS = 7
FOLDER_MATERIAL_TEMPLATES = 10
FOLDER_MODELS = 15
FOLDER_RESOURCE_ROOT = 1
FOLDER_SCENES = 6
FOLDER_SCREENSHOTS = 2
FOLDER_SCRIPTS = 12
FOLDER_TEXTURES = 4

Differences in Classes and Functions

In headless mode, KeyShot scripting still provides access to essential classes and functions for scene manipulation, such as those related to materials, cameras, rendering, and scene nodes. However, there are specific considerations and functionalities unique to headless mode:

GUI-Dependent Features: Functions and classes that require user interaction through the GUI, such as custom input dialogs (lux.getInputDialog()), are not available or functional in headless mode. Scripts designed for headless operation should avoid relying on any form of GUI feedback or input.

Automation and Batch Processing: Headless mode emphasizes automation. Functions for importing files, setting render options, triggering renders, and exporting results are fully supported and often used in automated workflows. This includes batch rendering, where multiple scenes or variations of a scene can be rendered sequentially without user intervention.

External File Handling: Headless mode might offer more explicit control over handling external files, such as specifying paths for importing and exporting data. This is crucial for automated workflows and integration with other software tools in a production pipeline.

Command-Line Arguments: While not a direct part of the lux library, headless operation often leverages command-line arguments for specifying script files to run, providing parameters to scripts, and controlling KeyShot's startup behavior. This allows for dynamic script execution based on external inputs.

Performance and Resource Management: Headless mode may provide functions or options focused on optimizing performance and resource usage, given that it's often used on high-performance computing resources or for background processing tasks. This can include controls over memory usage, CPU threading, and GPU usage for rendering.

Consistent Core Functionality: Despite these differences, the core functionality provided by lux and luxmath for scene construction, material application, camera control, and rendering settings is consistent between GUI and headless modes. Scripts can generally be developed in the GUI version of KeyShot and then executed in headless mode with minor adjustments, primarily related to user interaction and file path handling.

Guidelines for Making Scripts Headless Compliant

Avoid GUI Functions: Do not use functions that require GUI interaction, such as lux.getInputDialog() for custom input dialogs or any other function that prompts the user for input through the KeyShot interface.

Use Command-Line Arguments: For scripts that require input parameters, consider using command-line arguments to pass values into the script at runtime. This approach allows for dynamic script execution based on external inputs without needing GUI interaction.

Automate Render Settings and Execution: Utilize KeyShot's scripting capabilities to set all necessary render options programmatically. This includes setting camera parameters, environment settings, output resolutions, and render modes. Make sure the script triggers rendering and saves the output automatically.

Error Handling: Implement comprehensive error handling within the script to manage any issues that arise during execution. Since there's no GUI to display errors interactively, consider logging errors to a file or the console output for debugging purposes.

File Paths and External Resources: Handle file paths and external resources carefully, ensuring that paths are defined relative to the script location or passed as arguments, considering that the script may run in different environments or paths than when developed.

Output and Feedback: Since headless mode lacks GUI feedback, design your script to provide appropriate console output or log files to inform users of progress, completion status, and any errors or warnings.

Testing in Both Environments: Test your script extensively in both GUI and headless modes to ensure it behaves as expected. This helps identify any GUI-dependent operations or other issues that might only manifest in one mode.

Headless:

The lux library for KeyShot, when operated in headless mode (without the graphical user interface, GUI), offers functionality focused on scripting for automation, batch processing, and server-based rendering tasks. While the core functionality between GUI and headless modes remains consistent, focusing on scene manipulation, rendering, and camera control, there are some differences in available classes and functions to accommodate the non-interactive, command-line nature of headless operation.

Opts:

In KeyShot scripting, the opts variable often refers to a set of options or settings that can be configured for various operations, such as rendering, importing files, and exporting data. These options are typically stored in a Python dictionary or an object that allows for the customization of behavior and parameters of a given function. Below are examples of some commonly used opts in different contexts within KeyShot scripting:

Rendering Options: When configuring render settings, opts may include parameters to control aspects of the rendering process, such as resolution, quality, and format. Here's an example of setting up render options:

Import Options: For importing geometry or scenes into KeyShot, opts can specify how the import process behaves, such as whether to center the geometry, scale it, or how to handle existing materials:

Image Render Options: For image rendering, opts can include detailed settings about the output image, such as file format, DPI, and whether to include alpha channels:

Script Examples Reference:

Analyze .py as .txt Scripts_Commented.zip contains the following Scripts.

Batch Rename ModelSets GUI

Summary: This script provides a GUI for batch renaming model sets in KeyShot. It allows users to specify a prefix, name, suffix, and separator for each model set's new name. The script iterates through all model sets in the scene and presents a dialog for renaming each one individually.

Key Functions:

lux.getSceneTree(): Retrieves the root of the scene tree. node.isModelSet(): Checks if a node is a model set. lux.getInputDialog(): Displays a dialog box for user input. model_set.setName(): Sets a new name for a model set.

Duplicate and Randomly Scatter Objects

Summary: The script duplicates a selected object and scatters the duplicates randomly within the scene. It's headless compliant, meaning it can run in both GUI and headless modes of KeyShot. The script allows specifying the number of duplicates, axes for translation, and whether to rotate the duplicates.

Key Functions:

lux.getSceneTree().find(): Finds objects in the scene tree. lux.getInputDialog(): Captures user input for various parameters in GUI mode. luxmath.Vector(), luxmath.Matrix(): Used for creating vectors and matrices for transformations. obj.duplicate(), dup.applyTransform(): Duplicates objects and applies transformation matrices. Classes/Modules:

luxmath.Vector: Represents vectors for transformations. luxmath.Matrix: Handles matrices for object transformations.

Render Ambient Occlusion

Summary: This script renders an ambient occlusion image of the current scene. It prompts the user to specify output parameters such as folder path, image name, dimensions, and maximum render time. It temporarily changes the environment and materials to ensure an accurate occlusion render and then restores them.

Key Functions:

lux.getSceneInfo(): Retrieves information about the current scene. lux.getActiveEnvironment(), env.setLightingEnvironment(): Gets and sets the scene's lighting environment. lux.getMaterialMapping(), lux.applyMaterialMapping(): Gets and reapplies material mappings to restore original scene state. lux.getRenderOptions(), lux.renderImage(): Configures render options and initiates the rendering process.

Get Scene Materials

Summary: This script lists all materials currently used in the KeyShot scene by printing their names. It demonstrates a simple way to access and display scene information, particularly useful for auditing or documentation purposes.

Key Functions:

lux.getSceneMaterials(): Retrieves a list of all materials present in the current scene.

Saves Multi-Material Sub-Materials to Library (PC and Apple Compatible)

Summary: Designed for both Windows and macOS systems, this script saves all sub-materials of multi-materials in the current KeyShot scene to a specified material library, excluding duplicates. It identifies multi-materials by examining their material graph and iterates through each to save sub-materials individually.

Key Functions:

lux.getSceneTree(), node.getChildren(): Accesses the scene tree to find all nodes. lux.getMaterialGraph(), material_graph.getMaterialNodes(): Retrieves the material graph for a given material name, identifying sub-materials. lux.saveMaterial(): Saves a specified material to the library. platform.system(): Determines the operating system to set the library path accordingly.

Duplicate and Randomly Scatter Objects (Headless Compliant)

Summary: This script duplicates a selected object and scatters the duplicates randomly across the scene. It supports both GUI and headless modes, allowing users to specify the number of duplicates, translation axes, and rotation. The script uses randomization to place duplicates within the scene's bounding box.

Key Functions and Classes:

lux.getSceneTree().find(): Searches the scene tree to select objects. lux.getInputDialog(), inputItem(), inputInt(), inputBool(): Collect user inputs through GUI or command-line prompts. luxmath.Vector(), luxmath.Matrix(): Used for generating random transformations and applying them to duplicates. obj.duplicate(), dup.applyTransform(): Duplicates the selected object and applies random transformations. Modules Used:

random: Generates random numbers for translations and rotations. luxmath: KeyShot's module for mathematical operations related to vectors and matrices.

Saves the Scenes Materials and Multi-Material Sub-Materials to the Material Library

Summary: This script saves all scene materials and the sub-materials of multi-materials to a specified material library, avoiding duplicates. It is particularly useful for managing and organizing scene materials efficiently within KeyShot.

Key Functions:

lux.getSceneMaterials(): Retrieves all materials from the current scene. lux.saveMaterial(): Saves a specific material to the KeyShot material library. os, platform: Utilized for setting the library path dynamically based on the operating system.

Save Sub-Materials of Multi-Materials (PC and Apple Compatible)

Summary: Designed to be compatible with both Windows and macOS, this script focuses on saving sub-materials of multi-materials without saving the multi-materials themselves. It ensures no duplicate sub-materials are saved to the material library.

Key Functions:

lux.getMaterialGraph(), material_graph.getMaterialNodes(): Identifies and processes sub-materials within multi-materials. lux.saveMaterial(): Saves the sub-materials to the designated library path. platform.system(): Checks the operating system to set the appropriate library path.

Import CAD File, Create New Model Set, and Name After File

Summary: Automates the process of importing a CAD file, creating a new model set in KeyShot, and naming the model set after the imported file. It simplifies the importation and organization of CAD models within KeyShot projects.

Key Functions:

lux.getInputDialog(): Displays a dialog for selecting the CAD file to import. lux.importFile(): Imports the selected CAD file. os.path.splitext(), os.path.basename(): Extracts the filename to use as the model set name. lux.newModelSet(): Creates a new model set named after the imported file.

Batch Rename ModelSets GUI

Summary: Enables users to batch rename model sets in KeyShot using a GUI. It offers fields to input a new name for each model set, incorporating a prefix, suffix, and separator based on user preferences.

Key Functions:

lux.getSceneTree(), node.isModelSet(): Iterates through model sets in the scene. lux.getInputDialog(): Captures new naming specifications from the user. model_set.setName(): Applies the new names to each model set.

Import CAD File and Create Model Set Named After File

Summary: Streamlines the workflow of importing a CAD file and organizing it within KeyShot by automatically creating a model set named after the file. It demonstrates an efficient way to manage and categorize imported CAD models.

Key Functions:

lux.getInputDialog(): Opens a dialog for file selection. lux.importFile(): Imports the CAD file into KeyShot. lux.newModelSet(): Creates a new model set with the imported file's name.

luxmath:

The luxmath module in KeyShot's Python environment provides mathematical functionality, particularly focusing on operations involving vectors and matrices, which are essential for 3D transformations, camera positioning, and other spatial calculations in KeyShot scenes. Below is an overview of how luxmath works, including descriptions of its primary classes and their functionalities:

luxmath Classes:

luxmath consists of two main classes: Vector and Matrix. These classes are designed to handle 3D vectors and 4x4 matrices, respectively, allowing for a variety of mathematical operations that are common in 3D graphics and scene manipulation.

Vector:

Purpose: Represents a 3D vector with x, y, and z components. It's used for operations like translations, rotations (when specifying an axis), and scaling.

Construction: Can be instantiated with either a single value (applied to all three components), three individual values for x, y, and z, or a tuple/list of three values.

vec = luxmath.Vector(1, 2, 3) # x=1, y=2, z=3

Operations:

Addition, subtraction with other vectors. Multiplication, division by a scalar. Normalization to get a unit vector. Dot and cross product calculations. Length calculation, and more.

Matrix

Purpose: Encapsulates a 4x4 matrix, commonly used for affine transformations including translation, rotation, and scaling in 3D space.

Construction: Can be created as an identity matrix or from a 16-element list/tuple representing the 4x4 matrix components.

mat = luxmath.Matrix().makeIdentity() # Creates an identity matrix

Operations:

Matrix multiplication (combining transformations). Inversion (useful for calculating the inverse of a transformation). Transpose. Determinant calculation. Specific transformations like translation, rotation (around an axis or with a quaternion), and scaling. Conversion to and from transformation components (translate, rotate, scale).

Working with luxmath

The functionality provided by luxmath is crucial for scripting complex transformations and precisely controlling the spatial aspects of scenes, cameras, and objects within KeyShot. Here are some examples of how luxmath might be used in KeyShot scripting:

Positioning Objects: Use Matrix and Vector to compute the transformation matrix for positioning an object in the scene.

translation = luxmath.Vector(10, 0, 5) # Translate 10 units on X, 5 units on Z
rotation = luxmath.Matrix().makeRotate(luxmath.Vector(0, 1, 0), 45) # Rotate 45 degrees around Y
transform = rotation.translate(translation) # Combine translation and rotation
node.applyTransform(transform) # Apply to a scene node

Camera Setup: Configure a camera's position and orientation by calculating the appropriate matrix.

cameraPosition = luxmath.Vector(0, 2, -5)
lookAtPoint = luxmath.Vector(0, 1, 0)
upDirection = luxmath.Vector(0, 1, 0) # Typically the world's up direction
# Calculate view matrix or use existing functions for positioning the camera

Custom Animations: Script custom animations by interpolating between transformation matrices over time.

Modular Scripts:

scripts can and should be made modular, especially when working with KeyShot scripting or any programming environment. Modular scripting refers to the practice of organizing a script into separate, distinct components or modules. Each module focuses on a specific aspect of the script's functionality, making the code more organized, reusable, and easier to maintain. This approach aligns well with principles of software development, such as DRY (Don't Repeat Yourself) and separation of concerns.

Benefits of Modular Scripts Reusability:

Functions or classes defined in a module can be easily reused across different scripts, reducing duplication and effort. Maintainability: Changes in one part of a script do not affect other unrelated parts, making debugging and updating easier. Clarity: Modular scripts help in organizing code logically, making it more readable and understandable for both the author and others.

Collaboration: Allows multiple people to work on different parts of a script simultaneously without conflicts, enhancing teamwork efficiency.

Implementing Modularity in KeyShot Scripts

Function Decomposition: Break down the script into functions, each performing a single responsibility. For example, separate functions for setting up materials, cameras, rendering settings, and outputting render results.

Class Usage: Define classes for more complex behaviors or when managing state. For instance, a class for handling scene manipulation can encapsulate related operations.

External Modules: Organize related functions and classes into separate Python files (modules), which can be imported and utilized in main scripts or other modules.

Use of Python Packages: For very large or complex scripting projects, organize modules into packages, which are directories containing a special init.py file and multiple module files. This is useful for grouping related functionalities, like all material-related operations in one package and camera manipulations in another.

By adopting a modular approach, your KeyShot scripts become more scalable, enabling you to build complex automation and customizations in a manageable and efficient way.

Agnostic Scripting:

Making scripts "agnostic" means designing them in a way that they can operate independently of specific, hard-coded conditions, environments, or data. An agnostic script is versatile, reusable across different projects or contexts, and adaptable to various inputs or configurations without requiring significant modifications. Here are strategies to make KeyShot scripts (or any scripts) agnostic:

  1. Parameterization Use parameters or arguments for dynamic data instead of hard-coding values within the script. This allows the same script to be used with different inputs, such as file paths, material names, or rendering settings.

  2. Configuration Files Store configurations, like render settings or scene-specific data, in external files (JSON, XML, INI, etc.). This approach decouples configuration data from the script logic, making the script adaptable to different scenarios without altering the code.

  3. Environment Variables Utilize environment variables for sensitive or environment-specific information, such as paths or API keys. This method keeps the script portable and secure.

  4. Modular Design Organize the script into modules with well-defined, cohesive functions or classes. Each module should perform a specific task and interact with other modules through well-defined interfaces. This modularity supports reusability and easier adaptation to new requirements.

  5. Error Handling and Logging Implement comprehensive error handling and logging to manage unexpected inputs or failures gracefully. This practice helps ensure the script's robustness across various execution contexts.

  6. Documentation and Comments Provide clear documentation and comments explaining the script's requirements, how to configure it, and its dependencies. This information aids in making the script user-friendly and adaptable by others.

Agnostic Directory Script:

Query the KeyShot Studio 2026.3 resource folder configured for the current session.

library_path = lux.getKeyShotFolder(type=lux.FOLDER_RESOURCE_ROOT)

Scene Tree:

In KeyShot, the scene tree is a hierarchical representation of all the elements within a KeyShot scene. This structure mirrors the concept of a scene graph commonly used in 3D graphics and rendering software, organizing objects, materials, cameras, lights, and other entities in a way that reflects their relationships and dependencies.

Components of the Scene Tree:

The KeyShot scene tree comprises various nodes, each representing a different aspect of the scene:

Root Node: The top-level node under which all other scene elements are nested. It represents the entire scene. Geometry Nodes (Model and Part Nodes): These nodes represent 3D models and their components. A single model can be composed of multiple parts, each potentially having its own material and transformation settings. Material Nodes: Attached to geometry nodes, material nodes define the appearance of models or parts, including color, texture, reflectivity, and other visual properties.

Camera Nodes: Define different viewpoints from which the scene can be rendered. Each camera node stores settings like position, orientation, focal length, and depth of field.

Light Nodes: Represent light sources within the scene. KeyShot supports various types of lights, including area lights, point lights, and environment lights, each with its own set of parameters. Environment Nodes: These nodes are used for global illumination and background settings. They can define HDRIs (High Dynamic Range Images) used for lighting and reflections.

Animation Nodes: If the scene includes animations, each animation is represented as a node in the scene tree, detailing the animated properties and their keyframes.

Understanding the Hierarchical Structure:

The hierarchical nature of the scene tree allows for complex relationships between objects:

Parent-Child Relationships: Objects can be parented to other objects, meaning the child's transformation (position, rotation, scale) is relative to its parent. This is useful for creating complex assemblies where multiple parts move together.

Grouping: Similar objects can be grouped under a common parent node, simplifying the organization and enabling collective transformations or property adjustments.

Instancing: The scene tree structure allows for instancing, where the same object or geometry node is referenced multiple times within the scene without duplicating the actual geometry data. This saves memory and makes scene management more efficient.

Manipulating the Scene Tree via Scripting:

KeyShot's Python API allows scripts to interact with the scene tree, enabling automated tasks like:

Adding or Removing Nodes: Scripts can create new geometry, material, camera, or light nodes and insert them into the scene tree or remove existing nodes.

Modifying Node Properties: Scripts can change the properties of nodes, such as transforming geometry, altering material parameters, or adjusting camera settings.

Environment Nodes:

HDRI Environment, Color Environment, etc.: Properties: Brightness, Rotation, Background Color, etc. Accessing Node Properties Programmatically In a scripting context, you can access and modify these properties through KeyShot's Python API. For instance, to change the color of a diffuse material, you would access the material node associated with an object and set its color property accordingly. Navigating the Tree: Scripts can traverse the scene tree, accessing parent or child nodes, to gather information or make systematic changes to the scene.

Description of getSceneTree()

The getSceneTree() function is a part of KeyShot's Python API and is crucial for accessing and manipulating the scene graph. This function is used to retrieve the root node of the current scene in KeyShot. Once you have this root node, you can navigate through the entire hierarchy of the scene, including all objects, materials, cameras, lights, etc.

Key Aspects of getSceneTree()

  • Functionality: Retrieves the root node of the scene graph in KeyShot.
  • Return Type: The function returns a SceneNode object, which represents the top-level node of the scene.
  • Usage: Essential for scripts that need to traverse or modify the scene hierarchy.
  • No Arguments: getSceneTree() does not require any arguments.

Outline for Using getSceneTree()

  1. Import KeyShot lux Module:
import lux
  1. Retrieve the Root Node:
root_node = lux.getSceneTree()
  1. Traverse the Scene Graph:
  • You can now use various methods of the SceneNode class to traverse and manipulate the scene.
  • For example, to get child nodes: children = root_node.getChildren()
  1. Accessing Specific Elements:
  • Use traversal methods to access specific elements like cameras, materials, or geometries within the scene.
  • Perform operations like changing materials, moving objects, or adjusting camera settings.
  1. Iterative Traversal:
  • Often, you'll use a recursive function to traverse the scene tree starting from the root node to find specific nodes or perform operations on multiple nodes.

Example Use Case

Here's a simple example demonstrating how to use getSceneTree() to print the names of all top-level objects in the scene:

import lux

def print_scene_object_names():
root_node = lux.getSceneTree()
for child_node in root_node.getChildren():
print(child_node.getName())

print_scene_object_names()

In this example, getSceneTree() is used to start at the root of the scene graph, and then the script iterates over its direct children, printing out their names.

Remembering to use getSceneTree() is crucial for any script where you need to interact with the scene's hierarchy, making it a fundamental function in KeyShot Python scripting.

Material Graph:

Material Nodes: In KeyShot, a material node essentially functions as a shader by defining how surfaces interact with light. Each material node encapsulates the properties and behaviors necessary to simulate various physical materials, such as metals, plastics, glass, and more, effectively acting as a shader in the traditional 3D graphics sense.

Understanding Shaders and Material Nodes in KeyShot:

In 3D graphics, a shader is a type of computer program used to determine the appearance of surfaces when rendered, including colors, brightness, and texture details. KeyShot abstracts the complexity of shader programming into a more user-friendly interface through its Material Graph, where:

Material Nodes represent different types of materials (or shaders) that can be applied to objects in a scene. Each type of material node has its unique set of properties that mimic physical material characteristics, such as roughness, refractive index, or metallic properties.

Texture Nodes and Utility Nodes within the Material Graph can be used in conjunction with material nodes to further customize the material's appearance. For example, texture nodes can provide bitmap textures or procedural patterns, while utility nodes can perform operations like blending, color adjustment, or mathematical computations.

Example of Shader Material Nodes: Some examples of shader material nodes in KeyShot include:

Diffuse Material: Simulates non-reflective surfaces, primarily defined by its color. Metal Material: Represents metallic surfaces, with properties for controlling metalness and roughness. Glass Material (Transparent Material): Used for creating transparent materials with control over refraction and transparency. Plastic Material: Offers a way to simulate various plastic finishes with adjustable glossiness and translucency. Paint Material: Designed to simulate painted surfaces, including options for clear coat layers. Each of these material nodes has parameters that allow you to fine-tune the appearance of the material, mirroring the role of shaders in a traditional rendering pipeline but in a more accessible manner.

Accessing and Modifying the Material Graph through Scripting:

You can script the Material Graph in KeyShot using KeyShot's Python scripting API. Scripting the Material Graph allows for automated creation, modification, and application of complex materials programmatically, enabling tasks such as batch processing of materials, procedural material generation, and dynamic adjustments based on external data.

The scripting API provides access to the Material Graph components, including nodes, connections, and parameters. Here are some fundamental concepts for scripting the Material Graph:

Accessing the Material Graph: You start by accessing the material graph of a specific material. Each material in KeyShot that has a Material Graph can be accessed through scripting.

Creating and Connecting Nodes: The API allows for creating various types of nodes (such as material, texture, and utility nodes) and establishing connections between them to define the flow of information within the graph.

Editing Node Properties: Once nodes are created and connected, you can script changes to their properties, like changing texture settings, modifying colors, or adjusting material parameters.

Applying Materials: After creating or modifying a material in the Material Graph through scripting, you can apply it to parts of your scene programmatically.

Overview Material Node Properties:

Diffuse: Basic material, primarily defined by its color. Properties: Color, Roughness, Bump, Label, etc.

Metal: Simulates metallic surfaces. Properties: Color, Roughness, Anisotropy, Bump, etc.

Transparent (Glass): For glass-like materials. Properties: Color, Refraction Index, Dispersion, Bump, etc.

Paint: Designed to simulate painted surfaces. Properties: Color, Clearcoat Roughness, Clearcoat Thickness, etc.

Plastic: Simulates various plastic finishes. Properties: Color, Roughness, Translucency, Bump, etc.

Translucent: For materials like wax or skin that allow light to scatter through them. Properties: Color, Subsurface Color, Translucency, etc.

Texture Nodes: Image Texture: Applies an image file as a texture. Properties: Image Path, Scale, Rotation, etc.

Procedural Textures: Generate patterns or textures algorithmically (Noise, Wood, Gradient, etc.) Properties: Vary based on the type but generally include Scale, Color, Parameters specific to the procedural pattern, etc.

Utility Nodes: Color Adjust: Adjusts the color output of connected nodes. Properties: Hue, Saturation, Value, etc. Bump Add: Combines bump maps.

Properties: Bump Height, Opacity, etc.

Color Composite: Blends colors or textures based on a blend mode. Properties: Blend Mode, Opacity, etc.

Curvature: Uses the surface's curvature for effects like wear or edge highlighting. Properties: Radius, Threshold, etc.

Light Nodes: Point Light, Area Light, IES Light, etc. Properties: Color, Intensity, Falloff, etc.

Root Node: In KeyShot's Material Graph, the concept of a "root node" refers to the primary material node that defines the base properties of the material being constructed or edited within the graph. This root node isn't directly analogous to surface/object/model/assembly/part in the scene hierarchy; instead, it serves as the foundational element within the material's node graph from which additional properties and effects are derived through connections with other nodes (like textures, utilities, color adjustments, etc.).

Understanding the Root Node in a Material Graph Context: Material Graph Root Node: The starting point or the base material type for your material design within the Material Graph. It defines the essential characteristics of the material, such as whether it's a metal, plastic, paint, glass, etc. This node is where you begin building your material by adding and connecting other nodes to enhance or modify its properties.

Name of the Root Node: The name of the root node corresponds to the type of material it represents. For example, if you're creating a metal material, the root node might be named "Metal Material" or simply "Metal." In KeyShot, the specific name would depend on the material type selected when you start building or editing the material in the Material Graph.

Role of the Root Node: The root node's role is crucial because:

It determines the fundamental nature of the material (reflective, transparent, diffuse, etc.).

It acts as the anchor point for additional nodes that introduce textures, patterns, and effects (e.g., roughness maps, bump maps, color adjustments).

It is where the material's primary properties are set, which other nodes can then augment or override. Application to Surfaces/Objects/Models

Once a material is created in the Material Graph, it can be applied to surfaces, objects, models, parts, or assemblies within KeyShot's scene hierarchy. Here, the terms "surface," "object," "model," "assembly," and "part" refer to different elements in the scene to which materials can be assigned:

Surface: A specific area of a model that can have a unique material. Part: A component of a model that may consist of one or more surfaces. Object/Model: Typically, an imported geometry that can consist of multiple parts. Assembly: A group of objects or models that form a larger structure within the scene. The relationship between the Material Graph and these scene elements is that the materials designed in the Material Graph are applied to these elements to define their appearance. The "root node" within the context of the Material Graph is about the material's properties and is distinct from the scene hierarchy where objects, models, parts, and assemblies reside.

How to Find Specific Node Properties:

To find the specific properties of a node and how to script them:

KeyShot Scripting Console: Use the auto-completion feature to explore nodes and their properties. KeyShot Documentation: Consult the latest scripting documentation provided by Luxion for detailed information on each node type and its properties. Scripting Tutorials and Examples: Look for tutorials, forums, and example scripts that demonstrate how to manipulate nodes in the Material Graph.

Scripting Material Graph:

Material Graph Manipulation (GUI and Headless) Use lux.getMaterialGraph() to access the material graph from a script.

The following will go through the basic functions to manipulate the Material Graph. To see a full list of functions available, type help(lux) in the Scripting Console or visit the online documentation, for GUI or Headless scripting.

Access material graph

You can access the material graph like this:

graph = lux.getMaterialGraph("name")

The graph is an instance is of the type lux.MaterialGraph which you can interact with.

Access root node

You can access the root node with the following:

rootNode = graph.getRoot()

The rootNode is an instance is of the type lux.ShaderNode which you can interact with.

Get input edges of a node

However a node instance was obtained, you can get the edges from a Material Graph by typing:

edges = node.getInputEdges()

Each edge instance is of the type lux.ShaderEdge that you can be interact with.

A specific edge can be obtained via:

edge = node.getInputEdge("parameter name")

This will yield lux.ShaderEdge or an error if the name is unknown.

Get output edges of a node

However a node instance was obtained, you can get the edges from a Material Graph by typing:

edges = node.getOutputEdges()

Each edge instance is of the type lux.ShaderEdge that you can be interact with.

Get parameters of a node

However a node instance was obtained, you can get the parameters from a Material Graph by typing:

parameters = node.getParameters()

Each parameter instance is of the type lux.ShaderParameter that you can be interact with.

A specific parameter can be obtained via:

parameter = node.getParameter("parameter name")

This will yield lux.ShaderParameter or error if unknown name.

Change parameter value

A parameter, parameter, obtained via lux.SceneNode.getParameter() or lux.SceneNode.getParameters(), can have its value modified via lux.ShaderParameter.setValue().

If, for example, the parameter’s type was a boolean (true or false), you could change the value via:

parameter.setValue(True)

Is the value supported as input but entered incorrectly it will be shown in a python exception.

If, for example, the parameter was an RGB color and you applied the boolean value, it would yield the error:

Color parameter only accepts values of type tuple or list of size 3 containing floats or ints within range [0.0,1.0], or a color name! The following would therefore be the correct input for a color parameter:

parameter.setValue((0.5, 0, 0))  # Red, (0x7F, 0x00, 0x00)
parameter.setValue("Amber")      # Color known by the color library in KeyShot

You can obtain a Python value via lux.ShaderParameter.getValue() to get an understanding of what’s supported or you can print a representation of the instance (str() or repr()).

Remove a node

You can remove a node, either via the instance:

graph.removeNode(node)

Or its ID:

graph.removeNode(node.getID())

Create a new node

You can for example create a metal node like this:

metalNode = graph.newNode(lux.SHADER_TYPE_METAL)

Remove an edge

You can remove an edge, either via the instance:

graph.removeEdge(edge) Or its ID:

graph.removeEdge(edge.getID())

Create an edge between two nodes

You can for example create an edge between node1 and node2 on the surface parameter:

edge = graph.newEdge(source=node1, target=node2, param="surface")