This section includes detailed descriptions of KeyShot Python API Classes and their Functionalities, along with a comprehensive list of Constants in the 'lux' library. 3. Standard Functions 4. Headless-Specific Functions 5. Constants 6. Export Options 7. Image Style 8. Viewer Options 9. Message Window 10. Thumbnail Models 11. Node Types 12. All Parameters 13. Render Settings and Options 14. Save Options 15. Shader Nodes 16. Scene Units 17. Camera Types and Views 18. CMF Exclusive 19. Script Examples Reference - Batch Rename ModelSets GUI - Render Ambient Occlusion - Get Scene Materials - Duplicate and Randomly Scatter Objects (Headless Compliant) - Saves the Scenes Materials and Multi-Material Sub-Materials to the Material Library - Save Sub-Materials of Multi-Materials (PC and Apple Compatible) - Import CAD File, Create New Model Set, and Name After File 20. Supported File Formats - Supported Import File Formats - Supported Export File Formats
- ColorParameter: Manages color-related parameters in materials or environments.
- Colorway: Handles colorway settings for multi-materials or studios.
- Env: Configures environment settings like background, lighting, etc.
- ImageStyle: Controls image style settings for render outputs.
- MaterialGraph: Represents and manipulates the material graph structure.
- MaterialMetadata: Manages metadata associated with materials.
- MultiMaterial: Manages and configures multi-materials.
- RenderOptions: Sets options for rendering, such as resolution and quality.
- SceneNode: Represents nodes in the scene tree for manipulation.
- ShaderEdge: Handles connections between shader nodes in material graphs.
- ShaderNode: Represents individual shader nodes in material graphs.
- ShaderParameter: Manages parameters of shader nodes.
- Studio: Configures studio settings, including camera, environment, and model sets.
- ThumbnailRenderOptions: Sets rendering options for thumbnails.
- Animation: Controls animation-related settings and operations.
- BloomParameter: Manages bloom effect parameters in image styles.
- Curve: Represents and manipulates curve data.
- CurveControlPoint: Manages control points for curves.
- CurveParameter: Handles curve parameters in shader nodes.
- DenoiseParameter: Configures denoise settings in render options.
- Display: Controls display settings within KeyShot.
- FlakeParameter: Manages flake effect parameters in materials.
- GeometryNode: Represents geometry nodes in the scene.
- GeometryShaders: Manages shaders applied to geometries.
- Image: Handles image data and operations.
- ImageEffects: Configures post-processing effects on images.
- ImageLayers: Manages layers in composite images.
- Label: Controls label properties on materials.
- Light: Manages light sources in the scene.
- LightMaterial: Handles materials specifically for lights.
- Material: Represents and manipulates materials.
- NormalMapParameter: Manages normal map parameters in materials.
- NumberParameter: Handles numeric parameters in shader nodes.
- OrthographicCamera: Configures orthographic camera settings.
- PanoramicCamera: Manages panoramic camera settings.
- PerspectiveCamera: Controls perspective camera properties.
- ProceduralTexture: Handles procedural textures in materials.
- RenderLayers: Manages render layers in the scene.
- ScatteringMedium: Configures settings for volume scattering.
- SphericalCamera: Manages spherical camera settings.
- Texture: Represents and manipulates texture data.
- TextureParameter: Manages texture parameters in materials.
- ToonMaterial: Handles toon shader materials.
- VideoMap: Manages video textures.
- 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:
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 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.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.
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:
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_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_BASIC = 0
IMAGE_STYLE_PHOTOGRAPHIC = 1
KSP_VIEWER_SHOW_LOGO = 1
KSP_VIEWER_SHOW_WATERMARK = 2
MESSAGE_BOX_CRITICAL = 3
MESSAGE_BOX_INFO = 1
MESSAGE_BOX_WARNING = 2
META_DATA_SIMPLE = 1
META_DATA_XMP = 0
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'
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
Identifiers for different parameter types, e.g., PARAMETER_TYPE_BOOLEAN = 1, PARAMETER_TYPE_COLOR = 13, etc.
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_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_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_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'
UNIT_CM = 1
UNIT_FT = 3
UNIT_IN = 2
UNIT_M = 4
UNIT_MM = 0
Constants for specifying camera types and views, e.g., CAMERA_TYPE_ORTHOGRAPHIC, VIEW_FRONT, VIEW_BACK, etc.
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_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
library_path = "C:\\Users\\Public\\Documents\\KeyShot"
library_path = "/Library/Application Support/KeyShot"
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
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.
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.
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.
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:
Analyze .py as .txt Scripting_Examples.md contains the following Scripts.
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.
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. 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.
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. 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.
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. lux.getSceneMaterials(): Retrieves a list of all materials present in the current scene.
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. 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.
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.
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. 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.
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. 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.
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. 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. 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. 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.
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. 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.
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 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.
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=3Operations: 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.
Purpose: Encapsulates a 4x4 matrix, commonly used for affine transformations including translation, rotation, and scaling in 3D space. 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 matrixMatrix 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).
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 nodeCamera 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 cameraCustom Animations: Script custom animations by interpolating between transformation matrices over time.
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.
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.
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:
- 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.
- 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.
- 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.
- 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.
- 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.
- 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:
Set the KeyShot "Resources Library" path based on the operating system.
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.
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()ThegetSceneTree()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 ofgetSceneTree()
- Functionality: Retrieves the root node of the scene graph in KeyShot.
- Return Type: The function returns a
SceneNodeobject, 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 UsinggetSceneTree()
- Import KeyShot lux Module:
import lux- Retrieve the Root Node: root_node = lux.getSceneTree()
- Traverse the Scene Graph:
- You can now use various methods of the
SceneNodeclass to traverse and manipulate the scene. - For example, to get child nodes:
children = root_node.getChildren()
- 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.
- 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:
def print_scene_object_names():
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 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. 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. 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. 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. Point Light, Area Light, IES Light, etc. Properties: Color, Intensity, Falloff, etc. 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) Manipulating the Material Graph via Scripting is an advanced feature that has been added in KeyShot. 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.
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.
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.
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.
edges = node.getOutputEdges()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.
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 KeyShotYou 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()).
You can remove a node, either via the instance:
graph.removeNode(node)Or its ID:
graph.removeNode(node.getID())You can for example create a metal node like this:
metalNode = graph.newNode(lux.SHADER_TYPE_METAL)You can remove an edge, either via the instance:
graph.removeEdge(edge)
graph.removeEdge(edge.getID())You can for example create an edge between node1 and node2 on the surface parameter:
edge = graph.newEdge(source=node1, target=node2, param="surface")Non-Empty Default Values for lux.getInputDialog(): When using lux.getInputDialog() to create custom input dialogs in KeyShot, ensure that all fields, especially those of type lux.DIALOG_TEXT, have non-empty default values. This requirement prevents runtime errors related to uninitialized or empty fields in the dialog.
Error Message: Exception: Items of item tuple must be specified! Cause: This error occurs when a tuple expected by a function like lux.getInputDialog() is incomplete or improperly formatted, particularly for selection items (lux.DIALOG_ITEM). Solution: Ensure that all tuples defining dialog items are complete and correctly formatted. For selection items (lux.DIALOG_ITEM), include all required elements: the label, item type, description, default selection, and a list of options.
Error Message: TypeError: argument 1 must be str, not list Cause: This error is typically raised when a function expects a string argument, but a list (or another non-string type) is provided instead. Solution: Carefully review function calls to ensure that all arguments are of the expected type. For functions expecting a string, do not pass lists or other composite types without first converting or extracting the appropriate string value. Implementation Tips: Debugging: Use print statements or logging to debug argument types and values passed into functions. This can help identify where type mismatches occur. Type Checking: Implement explicit type checks or use Python's type hinting to make your code clearer and catch type-related errors early. Consistent Formatting: When dealing with functions that require tuples (like lux.getInputDialog()), double-check the consistency and completeness of your tuples to prevent formatting-related exceptions. Example: Here is an example illustrating how to correctly define a field in lux.getInputDialog() with a non-empty default value:
# Define input fields for the dialog
values = [
("name", lux.DIALOG_TEXT, "Model Name:", "DefaultModelName"), # Non-empty default value
# Other fields as needed
]
# Create the dialog
opts = lux.getInputDialog(title="Model Import Settings",
desc="Configure settings for importing models.",
values=values)KeyShot Scripting: Handling Material Graphs When working with material graphs in KeyShot via Python scripting, it's crucial to utilize the correct functions provided by the lux module for accessing and manipulating materials. The MaterialGraph class encapsulates a graph of material nodes constituting a material in the scene, enabling manipulation of material parameters, addition/removal of material nodes, and their association with input and output edges. Accessing Material Graphs and Handling Errors Function to Use: To get a material graph, use lux.getMaterialGraph(name), where name is the name of the material. AttributeError: module 'lux' has no attribute 'getMaterial'. Did you mean: 'MultiMaterial'? AttributeError: module 'lux' has no attribute 'getMaterials'. Did you mean: 'getCameras'? Solutions: These errors typically occur when attempting to access materials or their properties using incorrect or non-existent lux module functions. Use lux.getMaterialGraph(name) to access the material graph of a specific material by its name. To obtain information about materials used in the scene, or to manipulate materials directly, consider using the following functions correctly: lux.getSceneMaterials(): Retrieves currently used materials in the scene. lux.getName(): Retrieves the name of a node, which can be useful when working with materials and model sets. lux.getMaterialNodes(): Retrieves a list of material root nodes within a material graph. For multi-materials, it returns individual sub-material roots; for regular materials, it returns a list with a single item equivalent to getRoot(). Correcting Misused Functions Incorrect Use: Attempting to use lux.getMaterial() or lux.getMaterials() directly, which are not valid functions and can lead to AttributeError. Correction: Utilize the correct functions for your intended operations, such as lux.getSceneMaterials() for retrieving materials or lux.getMaterialGraph(name) for accessing a material's graph. Implementation Tips Review KeyShot Python API Documentation: Always refer to the most current KeyShot Python API documentation to understand available functions and their proper usage. Debugging: Use print statements to debug the names and types of variables, especially when passing them as arguments to functions, to ensure they match the expected values. By adhering to these guidelines and utilizing the correct functions for accessing and manipulating material graphs in KeyShot, you can avoid common errors and enhance your scripting workflow.
KeyShot Scripting: Correcting Camera Access Error Error Encounter: AttributeError: AttributeError: module 'lux' has no attribute 'getActiveCamera' This error indicates an attempt to use a non-existent function getActiveCamera in the lux module to retrieve the currently active camera. Cause: The error arises from a misunderstanding or incorrect reference to the available KeyShot Python API functions for camera manipulation. Correct Usage: The correct function to use for getting the active camera's information is lux.getCamera(), not lux.getActiveCamera. Solution: Review KeyShot Python API Documentation: Always consult the latest KeyShot Python API documentation to understand the correct naming and usage of functions related to camera operations. Code Adjustment: Replace any incorrect usage of lux.getActiveCamera with lux.getCamera() in your scripts. This function retrieves the current camera settings, including its name, type, and parameters. Example Correct Usage:
# Correctly getting the active camera's information
camera_info = lux.getCamera()
print("Active Camera:", camera_info)Additional Tips: Understanding Camera Functions: Familiarize yourself with other camera-related functions in the KeyShot Python API to fully leverage camera manipulation in your scripts. Functions such as lux.setCamera(), lux.saveCamera(), and lux.setStandardView() can be particularly useful. Error Checking: Implement try-except blocks around your camera function calls to catch and handle potential errors gracefully, improving script robustness. By adhering to the correct usage of lux.getCamera() for accessing the active camera's details, you can avoid common attribute errors and effectively control camera settings within your KeyShot Python scripts.
##All scripts must be complete and ensured to conform to the lux library. No Assumptions, No Examples, No Hypotheticals, No Outlines, No Placeholders, etc... Only the entire working concept script! I will test it in the KeyShot environment and give you errors to adjust. ##
- Scripting_Examples.md contains the following-
- 3ds Max (.max) [Windows Only]
- Adobe Swatch Exchange (.ase)
- ALIAS (.wire) [Windows Only]
- AutoCAD (.dwg, .dxf)
- CATIA (.cgr, .catpart, .catproduct, .catdrawing)
- Cinema 4D (.c4d)
- Creo (.prt, .asm) [Windows Only]
- Creo View (.pvz, .pvs, .edz, .ed, .c3di, .ol) [Windows Only]
- Inventor (.ipt, .iam)
- Maya (.ma, .mb) [Windows Only]
- NX (.prt)
- NX Continuous Release
- Onshape [Plugin]
- Pro/ENGINEER Wildfire (.prt, .asm)
- Revit (.rvt)
- Rhinoceros (.3dm)
- SketchUp (.skp)
- Solid Edge (.par, .asm, .psm)
- SOLIDWORKS (.sldprt, .sldasm)
- Acis (.sat)
- Alembic (.abc)
- 3DS (.3ds)
- 3MF (.3mf)
- 3DXML (.3dxml)
- Collada (.dae)
- FBX (.fbx)
- GLB/glTF (.glb, .gltf)
- IGES (.igs, .iges) [Windows: 2021.3 and prior, MacOS: 2019.0 and prior]
- JT (.jt)
- OBJ (.obj)
- Parasolid (.x_t)
- STEP (.stp, .step)
- STL (.stl)
- USD (.usd, .usda, .usdc, .usdz)
- OBJ (.obj)
- FBX (.fbx)
- GLB/glTF (.glb, .gltf)
- STL (.stl)
- USD (.usd, .usda, .usdc, .usdz)
- 3MF (.3mf)