diff --git a/.gitignore b/.gitignore index 59a5874..fe9c7f9 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ __pycache__/ .DS_Store .vscode/ *.zip +*.whl # the following ignores are used to ignore the local softlink files # the extern folder won't be affected by this @@ -10,4 +11,4 @@ meshio future fileseq -docs/_build/* \ No newline at end of file +docs/_build/* diff --git a/.readthedocs.yaml b/.readthedocs.yaml new file mode 100644 index 0000000..c3c3f96 --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,35 @@ +# Read the Docs configuration file for Sphinx projects +# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details + +# Required +version: 2 + +# Set the OS, Python version and other tools you might need +build: + os: ubuntu-22.04 + tools: + python: "3.11" + # You can also specify other tool versions: + # nodejs: "20" + # rust: "1.70" + # golang: "1.20" + +# Build documentation in the "docs/" directory with Sphinx +sphinx: + configuration: docs/conf.py + # You can configure Sphinx to use a different builder, for instance use the dirhtml builder for simpler URLs + # builder: "dirhtml" + # Fail on all warnings to avoid broken references + # fail_on_warning: true + +# Optionally build your docs in additional formats such as PDF and ePub +# formats: +# - pdf +# - epub + +# Optional but recommended, declare the Python requirements required +# to build your documentation +# See https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html +python: + install: + - requirements: docs/requirements.txt diff --git a/README.md b/README.md index f342028..4c12caa 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ ![GitHub release (latest by date)](https://img.shields.io/github/v/release/InteractiveComputerGraphics/blender-sequence-loader) [![Documentation Status](https://readthedocs.org/projects/blender-sequence-loader/badge/?version=latest)](https://blender-sequence-loader.readthedocs.io/en/latest/?badge=latest) -This is an addon for Blender 3.4+ (might work with 2.8+ but is not extensively tested on less recent versions) that enables loading of file sequences. The addon comes bundled together with [meshio](https://github.com/nschloe/meshio) which enables the loading of geometric data from a multitude of file formats. As stated there, the supported formats are listed in the following. Note that not all of the formats have been tested and some issues may still occur. +This is an addon for Blender 4.0+ (might work with 2.8+ but is not extensively tested on less recent versions) that enables loading of file sequences. The addon comes bundled together with [meshio](https://github.com/nschloe/meshio) which enables the loading of geometric data from a multitude of file formats. As stated there, the supported formats are listed in the following. Note that not all of the formats have been tested and some issues may still occur. > [Abaqus](http://abaqus.software.polimi.it/v6.14/index.html) (`.inp`), > ANSYS msh (`.msh`), @@ -86,9 +86,11 @@ After obtaining an installable `.zip` file either from the releases page or from ## 2. How to use -DISCLAIMER: Some of the screenshots may not be up to date with the most recent version of the addon, especially with respect to the text and ordering of UI elements. +**Note**: When rendering the animation, please turn on the `Lock Interface`. This will prevent artifacts from occurring, especially if the user continues to operate the Blender interface during the render process. -After installing addon, you can find it in the toolbar, which is accessible here or toggled by pressing the `n` key. +![lock interface](images/lock.png) + +After installing addon, you can find it in the toolbar, which is accessible here or toggled by pressing the `N` key. ![drag](images/drag.png) @@ -96,84 +98,145 @@ Then you can find it here. ![homepage](images/location.png) -### 2. Load the animation sequence you want +### 1. Load the animation sequence you want + +The easiest way to import sequences is to use the large "Import Sequences" button. After pressing it, you can select as many sequences as you want which will be imported to the scene after pressing `Accept`. + +#### 1.1 Relative Paths + +The first option is the "Relative Path" option which is turned off by default, i.e. it uses absolute paths by default. + +To enable this option, the blender file has to be saved first. Then the sequences that are imported will be referenced using relative paths from the location of the saved `.blend` file. As such, if you move the `.blend` file in conjunction with the data to another directory (keeping their relative locations the same) the sequence loader will still work. This is especially useful when working with cloud synchronized folders, whose absolute paths may be different on different computers. + +To change the "Root Directory" to be somewhere else please have a look at the "Global Settings" section. + +#### 1.2 Import Default Normals + +The sequence loader tries to look for already stored normals that have to meet certain criteria depending on the file types. Currently supported are .obj and .vtk. + +For .obj: +- Normals have to be normalized to 1. Vertex normals as well as face vertex normals (each vertex can have a different normal for each face) are supported. +- Any normals are stored by using "vn". Vertex normals are simply referenced in the same order as the vertices and for face vertex normals, the respective index of the normal is stated in the third position where the vertex is referenced for face (e.g. 1/2/3 or 1//3 would reference the 3rd normal for the 1st vertex in some face). + +For .vtk: +- Only verex normals are supported. They have to be named "normals". + +#### 1.3 Custom Transformation Matrix + +When enabling this option, you can define a custom transformation matrix (using XYZ Euler Angles) that will be applied once when importing a sequence. -You can select the directory in which your data is located through the GUI by clicking the rightmost icon. It will open the default blender file explorer. Then you can go to the directory you want, for example, like image showed below. **You only need navigate to the directory and click "Accept". Files are shown but not selectable in this dialogue.** +#### 1.4 Load sequences from folder (Legacy importer) -![directory](images/directory.png) +You can select the directory in which your data is located through the GUI by clicking the folder icon. It will open the default blender file explorer. Then, when you are in the desired folder, click `Accept`. You can't select any files in this GUI. -Then the addon will automatically try to detect the sequences in this directory, so that you simply select the sequence you want. If the desired sequence is not shown, you can switch to enter a manual pattern, where a single `@` character is used to denote a running frame index. +Then the addon will automatically try to detect the sequences in this directory, so that you simply select the sequence you want. If the desired sequence is not shown, you can enable the "Custom Pattern" option to enter a manual pattern, where a single `@` character is used to denote a running frame index. + +The refresh button simply looks again for sequences in the selcted folder, in case there were any changes made. + +Then click the `Load` Sequence" button to load the selected sequence or the `Load All` button to load all found sequences. ![sequence](images/sequence.png) -#### 2.1 Absolute vs. Relative Paths +### 2. Global Settings -There is a small checkbox about whether to use `relative paths` or not. +#### 2.1 Root Directory -When toggled on, the blender file must be saved before loading the sequence. Then this sequence will be loaded using relative path from the location of the saved `.blend` file. As such, if you move the `.blend` file in conjunction with the data to another directory (keeping their relative locations the same) the sequence loader will still work. This is especially useful when working with cloud synchronized folders, whose absolute paths may be different on different computers. +This is where a new root directory can be set. All relative paths will be relative to this directory. If left empty, the file path of the Blender file will be used. -If toggled off (default), it will use absolute path to load the sequence. For this, the `.blend` file does not have to be saved in advance. +#### 2.2 Print Sequence Information -![relative_path](images/path.png) +Print some useful information during rendering in a file located in the same folder as the render output and in the console. For the latter, Blender has to be started from the console. -#### 2.2 Sequence List View +#### 2.3 Auto Refresh Active Sequences -After the sequence being imported, it will be available in the `Imported Sequences` panel, with more settings being available in `Sequence Settings` panel once a sequence has been selected. +Automatically refresh all active sequences whenever the frame changes. See "Refresh Sequence" for further explanations. This can be useful when generating a sequence and rendering is done simultaneously. -![settings](images/list.png) +#### 2.4 Auto Refresh All Sequences -By default, all supported file formats are simply imported as geometry (a collection of vertices, lines, triangles and quads). As such, you should be able to directly play/render the animation if it contains geometry. +Like the above but with all sequences. -Note: When rendering the animation, please turn on the `Lock Interface`. This will prevent artifacts from occurring, especially if the user continues to operate the Blender interface during the render process. +### 3. Sequence List View -![lock interface](images/lock.png) +After the sequence being imported, it will be available in the `Sequences` panel, with more settings being available in `Sequence Settings` panel once a sequence has been selected. + +![settings](images/list.png) + +For each sequence we show the name, a button that shows whether a sequence is active or inactive (this button is clickable, see the next section for more details on the functionality), the current frame number which is also driver that can be edited as well as the smallest and largest number of the respective sequence. -##### 2.2.1 Enable/ Disable +##### 3.1 Activate / Deactivate Sequences -It is possible to individually enable and disable sequences from updating when the animation frame changes. This is very useful when working with very large files or many sequences as it reduces the computational overhead of loading these sequences. -`Enabled` means, that the sequence will be updated on frame change, and `Disabled` means that the sequence won't be updated on frame change. +It is possible to individually activate or deactivate sequences from updating when the animation frame changes. This is very useful when working with very large files or many sequences as it reduces the computational overhead of loading these sequences. +`Activated` means, that the sequence will be updated on frame change, and `Deactivated` means that the sequence won't be updated on frame change. -##### 2.2.1 Refresh Sequence +##### 3.2 Refresh Sequence `Refresh Sequence` can be useful when the sequence is imported while the data is still being generated and not yet complete. Refreshing the sequence can detect the frames added after being imported. -#### 2.3 Settings +#### 3.3 Activate / Deactivate All -#### 2.3.1 Geometry Nodes +Activate or deactivate all sequences shown in the sequences view. -While all files are imported as plain geometry, we provide some templates that we have found to be incredibly useful for visualizing particle data. +#### 3.4 Set Timeline -Applying the `Point Cloud` geometry node, the vertices of the mesh are converted to a point cloud, which can be rendered only by [cycles](https://docs.blender.org/manual/en/latest/render/cycles/introduction.html) and only as spheres. The exact geometry node setup can be seen in the geometry nodes tab and may be modified as desired, e.g. to set the particle radius. +Sets the Blender timeline to range of the smallest to largest number of a file of the selected sequence. -Applying `Instances` geometry nodes, the vertices of the mesh are converted to cubes, which can be rendered by both [eevee](https://docs.blender.org/manual/en/latest/render/eevee/index.html) and [cycles](https://docs.blender.org/manual/en/latest/render/cycles/introduction.html). The exact geometry node setup can be seen in the geometry nodes tab and may be modified as desired, e.g. to set the particle radius and to change the instanced geometry. **CAUTION: Because this node setup relies on the `Realize Instances` node, the memory usage increases extremely rapidly. Make sure to save the `.blend` file before attempting this, as Blender may run out of memory!!!** +### 4. Sequence Properties -Applying the `Mesh` geometry node will restore the default geometry nodes, which simply display the imported geometry as it is. +#### 4.1 Match Blender Frame Numbers -Notes: +This shows the file of a sequence at the frame number exactly matching the number in the file, otherwise it will not show anything. So if a file sequence goes from 2-10 and 15-30 only at these frames the respective files will be shown. -1. `Instances` is super memory hungry compared with `Point Cloud`. -2. After applying `Point Cloud` or `Instances` geometry nodes, you need to assign the material inside the geometry nodes. So to save your work, you can simply assign the material here, then apply the `Point Cloud` or `Instances` geometry nodes. -3. To access the attributes for shading, use the `Attribute` node in the Shader Editor and simply specify the attribute string. The imported attributes can be seen in the spreadsheet browser of the Geometry Nodes tab and are also listed in the addon UI. +By default this option is turned off and the sequence starts in Blender from 0 and on each following frame the next available file is loaded. For frame number larger than the length of the file sequence, this procedure is looped. -![material](images/geometry_nodes.png) +#### 4.2 Path + +The path of the file sequence is shown here and can also be edited. Relative paths start with // which basically is placeholder for the root directory. + +#### 4.3 Pattern + +Here you can see and edit the pattern of a file sequence that is used to detect the sequence as well as to determine how many frames the sequence has. A pattern consists of the name, then the frame range followed by an @ and at last, the file extension. + +#### 4.4 Current File -#### 2.3.2 Path Information +This is read-only and shows the absolute path of the file that is currenlty loaded from the selected sequence. -This shows the path of the sequence for debugging purposes, however it's not editable. +#### 4.5 Last Loading Time -#### 2.3.3 Attributes Settings +Read-only field, that shows how long it took to load the current file in milliseconds. + +#### 4.6 Attributes Settings This panel shows the available **Vertex Attributes**, it's not editable. Note: In order to avoid conflicts with Blenders built-in attributes, all the attributes names are renamed by prefixing `bseq_`. For example, `id` -> `bseq_id`. Keep this in mind when accessing attributes in the shader editor. -#### 2.3.4 Split Norm per Vertex +#### 4.6.1 Split Norm per Vertex We also provide the ability to use a per-vertex vector attribute as custom normals for shading. For more details check the official documentation [here](https://docs.blender.org/manual/en/latest/modeling/meshes/structure.html#modeling-meshes-normals-custom). Note: the addon does not check if the selected attribute is suitable for normals or not. E.g. if the data type of the attribute is int instead of float, then Blender will simply give a runtime error. -#### 2.3.5 Advanced Settings +### 5. Advanced Settings + +#### 5.1 Script + +Here you can import your own script for loading and preprocessing your file sequences. For more information look at the teplate.py file under Scripting -> Templates -> Sequence Loader -> Template. + +#### 5.2 Geometry Nodes + +While all files are imported as plain geometry, we provide some templates that we have found to be incredibly useful for visualizing particle data. + +Applying the `Point Cloud` geometry node, the vertices of the mesh are converted to a point cloud, which can be rendered only by [cycles](https://docs.blender.org/manual/en/latest/render/cycles/introduction.html) and only as spheres. The exact geometry node setup can be seen in the geometry nodes tab and may be modified as desired, e.g. to set the particle radius. + +Applying `Instances` geometry nodes, the vertices of the mesh are converted to cubes, which can be rendered by both [eevee](https://docs.blender.org/manual/en/latest/render/eevee/index.html) and [cycles](https://docs.blender.org/manual/en/latest/render/cycles/introduction.html). The exact geometry node setup can be seen in the geometry nodes tab and may be modified as desired, e.g. to set the particle radius and to change the instanced geometry. **CAUTION: Because this node setup relies on the `Realize Instances` node, the memory usage increases extremely rapidly. Make sure to save the `.blend` file before attempting this, as Blender may run out of memory!!!** -TODO +Applying the `Mesh` geometry node will restore the default geometry nodes, which simply display the imported geometry as it is. + +Notes: + +1. `Instances` is super memory hungry compared with `Point Cloud`. +2. After applying `Point Cloud` or `Instances` geometry nodes, you need to assign the material inside the geometry nodes. So to save your work, you can simply assign the material here, then apply the `Point Cloud` or `Instances` geometry nodes. +3. To access the attributes for shading, use the `Attribute` node in the Shader Editor and simply specify the attribute string. The imported attributes can be seen in the spreadsheet browser of the Geometry Nodes tab and are also listed in the addon UI. + +![material](images/geometry_nodes.png) diff --git a/__init__.py b/__init__.py index cb4bed4..d98c67b 100644 --- a/__init__.py +++ b/__init__.py @@ -1,27 +1,24 @@ -bl_info = { - "name": "Sequence Loader", - "description": "Loader for meshio supported mesh files/ simulation sequences", - "author": "Interactive Computer Graphics", - "version": (0, 1, 4), - "blender": (3, 4, 0), - "warning": "", - "support": "COMMUNITY", - "category": "Import-Export", -} - import bpy import os import sys -current_folder = os.path.dirname(os.path.abspath(__file__)) -if current_folder not in sys.path: - sys.path.append(current_folder) +# current_folder = os.path.dirname(os.path.abspath(__file__)) +# if current_folder not in sys.path: +# sys.path.append(current_folder) +# # add paths of external libraries to sys.path +# if os.path.exists(os.path.join(current_folder, "extern")): +# external_libs = ["fileseq/src", "meshio/src", "python-future/src", "rich"] +# for lib in external_libs: +# lib_path = os.path.join(current_folder, "extern", lib) +# if lib_path not in sys.path: +# sys.path.append(lib_path) + -if bpy.context.preferences.filepaths.use_relative_paths == True: - bpy.context.preferences.filepaths.use_relative_paths = False +# if bpy.context.preferences.filepaths.use_relative_paths == True: +# bpy.context.preferences.filepaths.use_relative_paths = False -from bseq import * -from bseq.operators import menu_func_import +from .bseq import * +from .bseq.operators import menu_func_import, add_keymap, delete_keymap classes = [ BSEQ_obj_property, @@ -32,10 +29,14 @@ BSEQ_OT_resetpt, BSEQ_OT_resetins, BSEQ_OT_resetmesh, - BSEQ_Import, + BSEQ_PT_Import, + BSEQ_PT_Import_Child1, + BSEQ_PT_Import_Child2, + BSEQ_Globals_Panel, BSEQ_List_Panel, BSEQ_UL_Obj_List, BSEQ_Settings, + BSEQ_Advanced_Panel, BSEQ_Templates, BSEQ_UL_Att_List, BSEQ_OT_set_as_split_norm, @@ -46,11 +47,17 @@ BSEQ_OT_disable_all, BSEQ_OT_enable_all, BSEQ_OT_refresh_sequences, - WM_OT_batchSequences, - WM_OT_MeshioObject + BSEQ_OT_set_start_end_frames, + BSEQ_OT_batch_sequences, + BSEQ_PT_batch_sequences_settings, + BSEQ_OT_meshio_object, + # BSEQ_OT_import_zip, + # BSEQ_OT_delete_zips, + # BSEQ_addon_preferences, + BSEQ_OT_load_all, + BSEQ_OT_load_all_recursive ] - def register(): bpy.app.handlers.load_post.append(BSEQ_initialize) for cls in classes: @@ -59,8 +66,8 @@ def register(): bpy.types.Scene.BSEQ = bpy.props.PointerProperty(type=BSEQ_scene_property) bpy.types.Object.BSEQ = bpy.props.PointerProperty(type=BSEQ_obj_property) bpy.types.Mesh.BSEQ = bpy.props.PointerProperty(type=BSEQ_mesh_property) - bpy.types.TOPBAR_MT_file_import.append(menu_func_import) + add_keymap() # manually call this function once # so when addon being installed, it can run correctly @@ -75,10 +82,9 @@ def unregister(): del bpy.types.Object.BSEQ bpy.app.handlers.load_post.remove(BSEQ_initialize) bpy.types.TOPBAR_MT_file_import.remove(menu_func_import) + delete_keymap() unsubscribe_to_selected() - if __name__ == "__main__": - # unregister() register() diff --git a/additional_file_formats/__init__.py b/additional_file_formats/__init__.py deleted file mode 100644 index 4d0b7e7..0000000 --- a/additional_file_formats/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from . import bgeo -from . import mzd \ No newline at end of file diff --git a/blender_manifest.toml b/blender_manifest.toml new file mode 100644 index 0000000..92c19ec --- /dev/null +++ b/blender_manifest.toml @@ -0,0 +1,80 @@ +schema_version = "1.0.0" + +# Example of manifest file for a Blender extension +# Change the values according to your extension +id = "sequence_loader" +version = "0.3.4" +name = "Blender Sequence Loader" +tagline = "Just-in-time loader for meshio-supported mesh file sequences" +maintainer = "Stefan Rhys Jeske " +# Supported types: "add-on", "theme" +type = "add-on" + +# # Optional: link to documentation, support, source files, etc +website = "https://github.com/InteractiveComputerGraphics/blender-sequence-loader" + +# # Optional: tag list defined by Blender and server, see: +# # https://docs.blender.org/manual/en/dev/advanced/extensions/tags.html +tags = ["Animation", "Object"] + +blender_version_min = "4.2.0" +# # Optional: Blender version that the extension does not support, earlier versions are supported. +# # This can be omitted and defined later on the extensions platform if an issue is found. +# blender_version_max = "5.1.0" + +# License conforming to https://spdx.org/licenses/ (use "SPDX: prefix) +# https://docs.blender.org/manual/en/dev/advanced/extensions/licenses.html +license = [ + "SPDX:MIT", +] +# # Optional: required by some licenses. +# copyright = [ +# "2002-2024 Developer Name", +# "1998 Company Name", +# ] + +# # Optional: list of supported platforms. If omitted, the extension will be available in all operating systems. +# platforms = ["windows-x64", "macos-arm64", "linux-x64"] +# # Other supported platforms: "windows-arm64", "macos-x64" + +# # Optional: bundle 3rd party Python modules. +# # https://docs.blender.org/manual/en/dev/advanced/extensions/python_wheels.html +wheels = [ + "./wheels/Fileseq-1.15.2-py3-none-any.whl", + "./wheels/future-0.18.3-py3-none-any.whl", + "./wheels/meshio-5.3.4-py3-none-any.whl", + "./wheels/rich-13.7.0-py3-none-any.whl", +] + +# # Optional: add-ons can list which resources they will require: +# # * files (for access of any filesystem operations) +# # * network (for internet access) +# # * clipboard (to read and/or write the system clipboard) +# # * camera (to capture photos and videos) +# # * microphone (to capture audio) +# # +# # If using network, remember to also check `bpy.app.online_access` +# # https://docs.blender.org/manual/en/dev/advanced/extensions/addons.html#internet-access +# # +# # For each permission it is important to also specify the reason why it is required. +# # Keep this a single short sentence without a period (.) at the end. +# # For longer explanations use the documentation or detail page. +# +[permissions] +files = "Core functionality to load files from disk" + +# # Optional: advanced build settings. +# # https://docs.blender.org/manual/en/dev/advanced/extensions/command_line_arguments.html#command-line-args-extension-build +[build] +# These are the default build excluded patterns. +# You only need to edit them if you want different options. +paths_exclude_pattern = [ + "__pycache__/", + "/.git/", + "/*.zip", + "/extern/", + "/docs/", + "/images/", + "build_addon.py", + "download_wheels.sh" +] \ No newline at end of file diff --git a/bseq/__init__.py b/bseq/__init__.py index 361914c..13ca993 100644 --- a/bseq/__init__.py +++ b/bseq/__init__.py @@ -1,19 +1,25 @@ -from bseq.utils import refresh_obj -from .operators import BSEQ_OT_load, BSEQ_OT_edit, BSEQ_OT_resetpt, BSEQ_OT_resetmesh, BSEQ_OT_resetins, BSEQ_OT_set_as_split_norm, BSEQ_OT_remove_split_norm, BSEQ_OT_disable_selected, BSEQ_OT_enable_selected, BSEQ_OT_refresh_seq, BSEQ_OT_disable_all, BSEQ_OT_enable_all, BSEQ_OT_refresh_sequences, WM_OT_batchSequences, WM_OT_MeshioObject +from .utils import refresh_obj +from .operators import BSEQ_OT_load, BSEQ_OT_edit, BSEQ_OT_resetpt, BSEQ_OT_resetmesh, BSEQ_OT_resetins, BSEQ_OT_set_as_split_norm, BSEQ_OT_remove_split_norm, BSEQ_OT_disable_selected, BSEQ_OT_enable_selected, BSEQ_OT_refresh_seq, BSEQ_OT_disable_all, BSEQ_OT_enable_all, BSEQ_OT_refresh_sequences, BSEQ_OT_set_start_end_frames, BSEQ_OT_batch_sequences, BSEQ_PT_batch_sequences_settings, BSEQ_OT_meshio_object, BSEQ_OT_import_zip, BSEQ_OT_delete_zips, BSEQ_addon_preferences, BSEQ_OT_load_all, BSEQ_OT_load_all_recursive from .properties import BSEQ_scene_property, BSEQ_obj_property, BSEQ_mesh_property -from .panels import BSEQ_UL_Obj_List, BSEQ_List_Panel, BSEQ_Settings, BSEQ_Import, BSEQ_Templates, BSEQ_UL_Att_List, draw_template +from .panels import BSEQ_UL_Obj_List, BSEQ_List_Panel, BSEQ_Settings, BSEQ_PT_Import, BSEQ_PT_Import_Child1, BSEQ_PT_Import_Child2, BSEQ_Globals_Panel, BSEQ_Advanced_Panel, BSEQ_Templates, BSEQ_UL_Att_List, draw_template from .messenger import subscribe_to_selected, unsubscribe_to_selected -import bpy -from bpy.app.handlers import persistent from .importer import update_obj from .globals import * +import bpy +from bpy.app.handlers import persistent + @persistent def BSEQ_initialize(scene): if update_obj not in bpy.app.handlers.frame_change_post: - bpy.app.handlers.frame_change_post.append(auto_refresh) bpy.app.handlers.frame_change_post.append(update_obj) + if auto_refresh_active not in bpy.app.handlers.frame_change_post: + bpy.app.handlers.frame_change_post.append(auto_refresh_active) + if auto_refresh_all not in bpy.app.handlers.frame_change_post: + bpy.app.handlers.frame_change_post.append(auto_refresh_all) + if clean_unused_bseq_data not in bpy.app.handlers.save_pre: + bpy.app.handlers.save_pre.append(clean_unused_bseq_data) subscribe_to_selected() if print_information not in bpy.app.handlers.render_init: bpy.app.handlers.render_init.append(print_information) @@ -24,12 +30,16 @@ def BSEQ_initialize(scene): "BSEQ_OT_load", "BSEQ_obj_property", "BSEQ_initialize", - "BSEQ_Import", + "BSEQ_PT_Import", + "BSEQ_PT_Import_Child1", + "BSEQ_PT_Import_Child2", + "BSEQ_Globals_Panel", "BSEQ_List_Panel", "BSEQ_UL_Obj_List", "BSEQ_scene_property", "BSEQ_Templates", "BSEQ_Settings", + "BSEQ_Advanced_Panel", "BSEQ_UL_Att_List", "subscribe_to_selected", "BSEQ_OT_resetpt", @@ -46,6 +56,13 @@ def BSEQ_initialize(scene): "BSEQ_OT_disable_all", "BSEQ_OT_enable_all", "BSEQ_OT_refresh_sequences", - "WM_OT_batchSequences", - "WM_OT_MeshioObject" + "BSEQ_OT_set_start_end_frames", + "BSEQ_OT_batch_sequences", + "BSEQ_PT_batch_sequences_settings", + "BSEQ_OT_meshio_object", + "BSEQ_OT_import_zip", + "BSEQ_OT_delete_zips", + "BSEQ_addon_preferences", + "BSEQ_OT_load_all", + "BSEQ_OT_load_all_recursive" ] diff --git a/additional_file_formats/README.md b/bseq/additional_file_formats/README.md similarity index 100% rename from additional_file_formats/README.md rename to bseq/additional_file_formats/README.md diff --git a/bseq/additional_file_formats/__init__.py b/bseq/additional_file_formats/__init__.py new file mode 100644 index 0000000..66f512f --- /dev/null +++ b/bseq/additional_file_formats/__init__.py @@ -0,0 +1,3 @@ +from . import bgeo +from . import mzd +from . import obj \ No newline at end of file diff --git a/additional_file_formats/bgeo.py b/bseq/additional_file_formats/bgeo.py similarity index 100% rename from additional_file_formats/bgeo.py rename to bseq/additional_file_formats/bgeo.py diff --git a/additional_file_formats/mzd.py b/bseq/additional_file_formats/mzd.py similarity index 99% rename from additional_file_formats/mzd.py rename to bseq/additional_file_formats/mzd.py index 23a0029..af4ff3c 100644 --- a/additional_file_formats/mzd.py +++ b/bseq/additional_file_formats/mzd.py @@ -22,6 +22,7 @@ def readMZD_to_meshio(filepath): with open(filepath, 'rb') as file: byte = file.read(24) + # check if mzd file is empty if byte != head: return -4 while 1: @@ -49,7 +50,7 @@ def readMZD_to_meshio(filepath): if out_numVertices < 0: return -127 if out_numVertices == 0: - break + return meshio.Mesh(points=np.array([]), cells={}) byte = file.read(12 * out_numVertices) out_vertPositions = np.frombuffer(byte, dtype=np.float32) diff --git a/bseq/additional_file_formats/obj.py b/bseq/additional_file_formats/obj.py new file mode 100644 index 0000000..57437b3 --- /dev/null +++ b/bseq/additional_file_formats/obj.py @@ -0,0 +1,135 @@ +""" +I/O for the Wavefront .obj file format, cf. +. +""" +import datetime + +import numpy as np + +# from .._files import open_file +# from .._helpers import register_format +# from .._mesh import CellBlock, Mesh + +import meshio + + +def read(filename): + with open(filename, "r") as f: + mesh = read_buffer(f) + return mesh + + +def read_buffer(f): + points = [] + vertex_normals = [] + texture_coords = [] + face_groups = [] + face_normals = [] + face_texture_coords = [] + face_group_ids = [] + face_group_id = -1 + while True: + line = f.readline() + + if not line: + # EOF + break + + strip = line.strip() + + if len(strip) == 0 or strip[0] == "#": + continue + + split = strip.split() + + if split[0] == "v": + points.append([float(item) for item in split[1:]]) + elif split[0] == "vn": + vertex_normals.append([float(item) for item in split[1:]]) + elif split[0] == "vt": + texture_coords.append([float(item) for item in split[1:]]) + elif split[0] == "s": + # "s 1" or "s off" controls smooth shading + pass + elif split[0] == "f": + # old: dat = [int(item.split("/")[0]) for item in split[1:]] + # A face in obj has one of the following formats: 1, 1/2, 1//3, 1/2/3 + # We want to support all formats now amd store the texture and normal indices in other arrays + face_indices = [] + face_texture_indices = [] + face_normal_indices = [] + + for item in split[1:]: + indices = item.split("/") + face_indices.append(int(indices[0])) + if len(indices) > 1 and indices[1] != "": + face_texture_indices.append(int(indices[1])) + if len(indices) > 2: + face_normal_indices.append(int(indices[2])) + + if len(face_groups) == 0 or ( + len(face_groups[-1]) > 0 and len(face_groups[-1][-1]) != len(face_indices) + ): + face_groups.append([]) + face_group_ids.append([]) + face_texture_coords.append([]) + face_normals.append([]) + face_groups[-1].append(face_indices) + face_group_ids[-1].append(face_group_id) + if face_texture_indices: + face_texture_coords[-1].append(face_texture_indices) + if face_normal_indices: + face_normals[-1].append(face_normal_indices) + elif split[0] == "g": + # new group + face_groups.append([]) + face_group_ids.append([]) + face_texture_coords.append([]) + face_normals.append([]) + face_group_id += 1 + else: + # who knows + pass + + # There may be empty groups, too. + # Remove them. + face_groups = [f for f in face_groups if len(f) > 0] + face_group_ids = [g for g in face_group_ids if len(g) > 0] + face_normals = [n for n in face_normals if len(n) > 0] + face_texture_coords = [t for t in face_texture_coords if len(t) > 0] + + # convert to numpy arrays and remove + points = np.array(points) + face_groups = [np.array(f) for f in face_groups] + texture_coords = [np.array(t) for t in texture_coords] + vertex_normals = [np.array(n) for n in vertex_normals] + point_data = {} + cell_data = {} + field_data = {} + + if face_texture_coords and len(texture_coords) == max([max(max(face)) for face in face_texture_coords]): + field_data["obj:vt"] = texture_coords + cell_data["obj:vt_face_idx"] = face_texture_coords + elif len(texture_coords) == len(points): + point_data["obj:vt"] = texture_coords + + if face_normals and len(vertex_normals) == max([max(max(face)) for face in face_normals]): + field_data["obj:vn"] = vertex_normals + cell_data["obj:vn_face_idx"] = face_normals + elif len(vertex_normals) == len(points): + point_data["obj:vn"] = vertex_normals + + cell_data["obj:group_ids"] = [] + cells = [] + for f, gid in zip(face_groups, face_group_ids): + if f.shape[1] == 3: + cells.append(meshio.CellBlock("triangle", f - 1)) + elif f.shape[1] == 4: + cells.append(meshio.CellBlock("quad", f - 1)) + else: + cells.append(meshio.CellBlock("polygon", f - 1)) + cell_data["obj:group_ids"].append(gid) + + return meshio.Mesh(points, cells, point_data=point_data, cell_data=cell_data, field_data=field_data) + +meshio.register_format("obj", [".obj"], read, {"obj": None}) diff --git a/additional_file_formats/table.py b/bseq/additional_file_formats/table.py similarity index 100% rename from additional_file_formats/table.py rename to bseq/additional_file_formats/table.py diff --git a/bseq/callback.py b/bseq/callback.py index e89bb6b..079b702 100644 --- a/bseq/callback.py +++ b/bseq/callback.py @@ -1,31 +1,37 @@ import bpy import fileseq +import traceback + +from .utils import show_message_box # Code here are mostly about the callback/update/items functions used in properties.py file_sequences = [] def update_path(self, context): + ''' + Detects all the file sequences in the directory + ''' + # When the path has been changed, reset the selected sequence to None context.scene.BSEQ['fileseq'] = 1 context.scene.BSEQ.use_pattern = False context.scene.BSEQ.pattern = "" - - ''' - Detects all the file sequences in the directory - ''' + file_sequences.clear() p = context.scene.BSEQ.path try: - f = fileseq.findSequencesOnDisk(p) - except: - return [("None", "No sequence detected", "", 1)] + f = fileseq.findSequencesOnDisk(bpy.path.abspath(p)) + except Exception as e: + show_message_box("Error when reading path\n" + traceback.format_exc(), + "fileseq Error" + str(e), + icon="ERROR") + return None if not f: - return [("None", "No sequence detected", "", 1)] + return None - file_sequences.clear() - if len(f) >= 20: + if len(f) >= 30: file_sequences.append(("None", "Too much sequence detected, could be false detection, please use pattern below", "", 1)) else: count = 1 diff --git a/bseq/globals.py b/bseq/globals.py index e875ff0..3a7ef10 100644 --- a/bseq/globals.py +++ b/bseq/globals.py @@ -23,13 +23,14 @@ def print_information(scene): if bseq_prop.init: file.write("Object name: {}\n".format(obj.name)) file.write("Is it being animated: {}\n".format(bseq_prop.enabled)) - file.write("Filepath: {}\n".format(bseq_prop.pattern)) - file.write("Is it relative path: {}\n".format(bseq_prop.use_relative)) + file.write("Filepath: {}\n".format(bseq_prop.path)) + file.write("Pattern: {}\n".format(bseq_prop.pattern)) + file.write("Current file: {}\n".format(bseq_prop.current_file)) file.write("\n\n") -def auto_refresh(scene, depsgraph=None): - if not bpy.context.scene.BSEQ.auto_refresh: +def auto_refresh_all(scene, depsgraph=None): + if not bpy.context.scene.BSEQ.auto_refresh_all: return for obj in bpy.data.objects: if obj.BSEQ.init == False: @@ -38,4 +39,26 @@ def auto_refresh(scene, depsgraph=None): continue if obj.mode != "OBJECT": continue - refresh_obj(obj, scene) \ No newline at end of file + refresh_obj(obj, scene) + +def auto_refresh_active(scene, depsgraph=None): + if not bpy.context.scene.BSEQ.auto_refresh_active: + return + for obj in bpy.data.objects: + if obj.BSEQ.init == False: + continue + if obj.BSEQ.enabled == False: + continue + if obj.mode != "OBJECT": + continue + refresh_obj(obj, scene) + +# This becomes necessary, because when deleting objects from the viewport, they dont actually get removed from the +# sequences list, because this is not a global delete. This handler only removes sequences that are not referenced +# in any scene or collection. This handler is added to save_pre, so that unused data blocks dont get saved +def clean_unused_bseq_data(savefile): + for obj in bpy.data.objects: + if obj.BSEQ.init and len(obj.users_collection)==0 and len(obj.users_scene)==0: + + # This will throw an error if it is actually still used somewhere + bpy.data.objects.remove(obj) \ No newline at end of file diff --git a/bseq/importer.py b/bseq/importer.py index d5dbc93..523b6f7 100644 --- a/bseq/importer.py +++ b/bseq/importer.py @@ -4,12 +4,17 @@ import traceback import fileseq import os -from .utils import show_message_box +from .utils import show_message_box, get_relative_path, get_absolute_path, load_meshio_from_path import numpy as np from mathutils import Matrix +import time # this import is not useless -import additional_file_formats +from .additional_file_formats import * +def extract_edges(cell: meshio.CellBlock): + if cell.type == "line": + return cell.data.astype(np.uint64) + return np.array([]) def extract_faces(cell: meshio.CellBlock): if cell.type == "triangle": @@ -50,6 +55,8 @@ def extract_faces(cell: meshio.CellBlock): return faces elif cell.type == "vertex": return np.array([]) + elif cell.type == "line": + return np.array([]) show_message_box(cell.type + " is unsupported mesh format yet") return np.array([]) @@ -63,8 +70,8 @@ def has_keyframe(obj, attr): def apply_transformation(meshio_mesh, obj, depsgraph): # evaluate the keyframe animation system - eval_location = obj.evaluated_get(depsgraph).location if has_keyframe(obj, "location") else None - eval_scale = obj.evaluated_get(depsgraph).scale if has_keyframe(obj, "scale") else None + eval_location = obj.evaluated_get(depsgraph).location if has_keyframe(obj, "location") else obj.location + eval_scale = obj.evaluated_get(depsgraph).scale if has_keyframe(obj, "scale") else obj.scale if has_keyframe(obj, "rotation_quaternion"): eval_rotation = obj.evaluated_get(depsgraph).rotation_quaternion @@ -73,17 +80,43 @@ def apply_transformation(meshio_mesh, obj, depsgraph): elif has_keyframe(obj, "rotation_euler"): eval_rotation = obj.evaluated_get(depsgraph).rotation_euler else: - eval_rotation = None + eval_rotation = obj.rotation_euler eval_transform_matrix = mathutils.Matrix.LocRotScale(eval_location, eval_rotation, eval_scale) # evaluate the rigid body transformations (only relevant for .bin format) rigid_body_transformation = mathutils.Matrix.Identity(4) - if meshio_mesh.field_data.get("transformation_matrix") is not None: - rigid_body_transformation = meshio_mesh.field_data["transformation_matrix"] + if meshio_mesh is not None: + if "transformation_matrix" in meshio_mesh.field_data: + rigid_body_transformation = meshio_mesh.field_data["transformation_matrix"] # multiply everything together (with custom transform matrix) - obj.matrix_world = rigid_body_transformation @ obj.BSEQ.initial_transform_matrix @ eval_transform_matrix + obj.matrix_world = rigid_body_transformation @ eval_transform_matrix + +# function to create a single custom Blender mesh attribute +def create_or_retrieve_attribute(mesh, k, v): + if k not in mesh.attributes: + if len(v) == 0: + return mesh.attributes.new(k, "FLOAT", "POINT") + if len(v.shape) == 1: + # one dimensional attribute + return mesh.attributes.new(k, "FLOAT", "POINT") + if len(v.shape) == 2: + dim = v.shape[1] + if dim > 3: + # show_message_box('higher than 3 dimensional attribue, ignored') + return None + if dim == 1: + return mesh.attributes.new(k, "FLOAT", "POINT") + if dim == 2: + return mesh.attributes.new(k, "FLOAT2", "POINT") + if dim == 3: + return mesh.attributes.new(k, "FLOAT_VECTOR", "POINT") + if len(v.shape) > 2: + # show_message_box('more than 2 dimensional tensor, ignored') + return None + else: + return mesh.attributes[k] def update_mesh(meshio_mesh, mesh): # extract information from the meshio mesh @@ -93,70 +126,74 @@ def update_mesh(meshio_mesh, mesh): n_loop = 0 n_verts = len(mesh_vertices) if n_verts == 0: + mesh.clear_geometry() + mesh.update() + mesh.validate() return + edges = np.array([], dtype=np.uint64) faces_loop_start = np.array([], dtype=np.uint64) faces_loop_total = np.array([], dtype=np.uint64) loops_vert_idx = np.array([], dtype=np.uint64) shade_scheme = False if mesh.polygons: shade_scheme = mesh.polygons[0].use_smooth + for cell in meshio_mesh.cells: - data = extract_faces(cell) - # np array can't be simply written as `if not data:`, - if not data.any(): - continue - n_poly += len(data) - n_loop += data.shape[0] * data.shape[1] - loops_vert_idx = np.append(loops_vert_idx, data.ravel()) - faces_loop_total = np.append(faces_loop_total, np.ones((len(data)), dtype=np.uint64) * data.shape[1]) + edge_data = extract_edges(cell) + face_data = extract_faces(cell) + + if edge_data.any(): + edges = np.append(edges, edge_data) + + if face_data.any(): + n_poly += len(face_data) + n_loop += face_data.shape[0] * face_data.shape[1] + loops_vert_idx = np.append(loops_vert_idx, face_data.ravel()) + faces_loop_total = np.append(faces_loop_total, np.ones((len(face_data)), dtype=np.uint64) * face_data.shape[1]) + if faces_loop_total.size > 0: faces_loop_start = np.cumsum(faces_loop_total) # Add a zero as first entry faces_loop_start = np.roll(faces_loop_start, 1) faces_loop_start[0] = 0 - + if len(mesh.vertices) == n_verts and len(mesh.polygons) == n_poly and len(mesh.loops) == n_loop: pass else: mesh.clear_geometry() mesh.vertices.add(n_verts) + mesh.edges.add(len(edges)) mesh.loops.add(n_loop) mesh.polygons.add(n_poly) mesh.vertices.foreach_set("co", mesh_vertices.ravel()) + mesh.edges.foreach_set("vertices", edges) mesh.loops.foreach_set("vertex_index", loops_vert_idx) mesh.polygons.foreach_set("loop_start", faces_loop_start) mesh.polygons.foreach_set("loop_total", faces_loop_total) mesh.polygons.foreach_set("use_smooth", [shade_scheme] * len(faces_loop_total)) + # newer function but is about 4 times slower + # mesh.clear_geometry() + # mesh.from_pydata(mesh_vertices, edge_data, face_data) + mesh.update() mesh.validate() + if bpy.context.scene.BSEQ.use_imported_normals: + if "obj:vn" in meshio_mesh.point_data: + mesh.BSEQ.split_norm_att_name = "bseq_obj:vn" + elif "normals" in meshio_mesh.point_data and len(meshio_mesh.point_data["normals"]) == len(mesh.vertices): + mesh.BSEQ.split_norm_att_name = "bseq_normals" + elif "obj:vn" in meshio_mesh.field_data and "obj:vn_face_idx" in meshio_mesh.cell_data: + mesh.BSEQ.split_norm_att_name = "obj:vn" + # copy attributes - attributes = mesh.attributes for k, v in meshio_mesh.point_data.items(): k = "bseq_" + k - attribute = None - if k not in attributes: - if len(v.shape) == 1: - # one dimensional attribute - attribute = mesh.attributes.new(k, "FLOAT", "POINT") - if len(v.shape) == 2: - dim = v.shape[1] - if dim > 3: - show_message_box('higher than 3 dimensional attribue, ignored') - continue - if dim == 1: - attribute = mesh.attributes.new(k, "FLOAT", "POINT") - if dim == 2: - attribute = mesh.attributes.new(k, "FLOAT2", "POINT") - if dim == 3: - attribute = mesh.attributes.new(k, "FLOAT_VECTOR", "POINT") - if len(v.shape) > 2: - show_message_box('more than 2 dimensional tensor, ignored') - continue - else: - attribute = attributes[k] + attribute = create_or_retrieve_attribute(mesh, k, v) + if attribute is None: + continue name_string = None if attribute.data_type == "FLOAT": name_string = "value" @@ -165,12 +202,28 @@ def update_mesh(meshio_mesh, mesh): attribute.data.foreach_set(name_string, v.ravel()) - # set as split norm + # set as split normal per vertex if mesh.BSEQ.split_norm_att_name and mesh.BSEQ.split_norm_att_name == k: - mesh.use_auto_smooth = True + # If blender version is greater than 4.1.0, then don't set auto smooth. + # It has been removed and normals will be used automatically if they are set. + # https://developer.blender.org/docs/release_notes/4.1/python_api/#mesh + if bpy.app.version < (4, 1, 0): + mesh.use_auto_smooth = True mesh.normals_split_custom_set_from_vertices(v) -# function to create a single meshio object + for k, v in meshio_mesh.field_data.items(): + if k not in mesh.attributes: + attribute = create_or_retrieve_attribute(mesh, k, []) + + # set split normal per loop per vertex + if mesh.BSEQ.split_norm_att_name and mesh.BSEQ.split_norm_att_name == k: + if bpy.app.version < (4, 1, 0): + mesh.use_auto_smooth = True + # currently hard-coded for .obj files + indices = [item for sublist in meshio_mesh.cell_data["obj:vn_face_idx"][0] for item in sublist] + mesh.normals_split_custom_set([meshio_mesh.field_data["obj:vn"][i - 1] for i in indices]) + +# function to create a single meshio object (not a sequence, this just inports some file using meshio) def create_meshio_obj(filepath): meshio_mesh = None try: @@ -179,7 +232,7 @@ def create_meshio_obj(filepath): show_message_box("Error when reading: " + filepath + ",\n" + traceback.format_exc(), "Meshio Loading Error" + str(e), icon="ERROR") - + return # create the object name = os.path.basename(filepath) mesh = bpy.data.meshes.new(name) @@ -189,8 +242,7 @@ def create_meshio_obj(filepath): bpy.ops.object.select_all(action="DESELECT") bpy.context.view_layer.objects.active = object - -def create_obj(fileseq, use_relative, root_path, transform_matrix=Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])): +def create_obj(fileseq, use_relative, root_path, transform_matrix=Matrix.Identity(4)): current_frame = bpy.context.scene.frame_current filepath = fileseq[current_frame % len(fileseq)] @@ -201,26 +253,28 @@ def create_obj(fileseq, use_relative, root_path, transform_matrix=Matrix([[1, 0, meshio_mesh = meshio.read(filepath) except Exception as e: show_message_box("Error when reading: " + filepath + ",\n" + traceback.format_exc(), - "Meshio Loading Error" + str(e), - icon="ERROR") + "Meshio Loading Error" + str(e), + icon="ERROR") enabled = False - # create the object name = fileseq.basename() + "@" + fileseq.extension() mesh = bpy.data.meshes.new(name) object = bpy.data.objects.new(name, mesh) - object.BSEQ.use_relative = use_relative + + # create the object + full_path = str(fileseq) + path = os.path.dirname(full_path) + pattern = os.path.basename(full_path) if use_relative: - if root_path != "": - object.BSEQ.pattern = bpy.path.relpath(str(fileseq), start=root_path) - else: - object.BSEQ.pattern = bpy.path.relpath(str(fileseq)) - else: - object.BSEQ.pattern = str(fileseq) + path = get_relative_path(path, root_path) + # path is only the directory in which the file is located + object.BSEQ.path = path + object.BSEQ.pattern = pattern + object.BSEQ.current_file = filepath object.BSEQ.init = True object.BSEQ.enabled = enabled - # Flatten custom transformation matrix for the property - object.BSEQ.initial_transform_matrix = [transform_matrix[j][i] for i in range(4) for j in range(4)] + object.BSEQ.start_end_frame = (fileseq.start(), fileseq.end()) + object.matrix_world = transform_matrix driver = object.driver_add("BSEQ.frame") driver.driver.expression = 'frame' if enabled: @@ -229,10 +283,10 @@ def create_obj(fileseq, use_relative, root_path, transform_matrix=Matrix([[1, 0, bpy.ops.object.select_all(action="DESELECT") bpy.context.view_layer.objects.active = object - def update_obj(scene, depsgraph=None): - for obj in bpy.data.objects: + start_time = time.perf_counter() + if obj.BSEQ.init == False: continue if obj.BSEQ.enabled == False: @@ -246,17 +300,12 @@ def update_obj(scene, depsgraph=None): show_message_box("Warning: Might not be able load the correct frame because the dependency graph is not available.", "BSEQ Warning") current_frame = obj.BSEQ.frame meshio_mesh = None - pattern = obj.BSEQ.pattern - if obj.BSEQ.use_relative: - if scene.BSEQ.root_path != "": - pattern = bpy.path.abspath(pattern, start=scene.BSEQ.root_path) - else: - pattern = bpy.path.abspath(pattern) - + # in case the blender file was created on windows system, but opened in linux system - pattern = bpy.path.native_pathsep(pattern) - fs = fileseq.FileSequence(pattern) + full_path = get_absolute_path(obj, scene) + fs = fileseq.FileSequence(full_path) + if obj.BSEQ.use_advance and obj.BSEQ.script_name: script = bpy.data.texts[obj.BSEQ.script_name] try: @@ -270,6 +319,7 @@ def update_obj(scene, depsgraph=None): user_process = locals()['process'] try: user_process(fs, current_frame, obj.data) + obj.BSEQ.current_file = "Controlled by user process" except Exception as e: show_message_box("Error when calling user process: " + traceback.format_exc(), icon="ERROR") del locals()['process'] @@ -280,6 +330,7 @@ def update_obj(scene, depsgraph=None): user_preprocess = locals()['preprocess'] try: meshio_mesh = user_preprocess(fs, current_frame) + obj.BSEQ.current_file = "Controlled by user preprocess" except Exception as e: show_message_box("Error when calling user preprocess: " + traceback.format_exc(), icon="ERROR") # this continue means only if error occures, then goes to next bpy.object @@ -287,14 +338,18 @@ def update_obj(scene, depsgraph=None): finally: del locals()['preprocess'] else: - filepath = fs[current_frame % len(fs)] - try: - meshio_mesh = meshio.read(filepath) - except Exception as e: - show_message_box("Error when reading: " + filepath + ",\n" + traceback.format_exc(), - "Meshio Loading Error" + str(e), - icon="ERROR") - continue + if obj.BSEQ.match_frames: + fs_frames = fs.frameSet() + if current_frame in fs_frames: + filepath = fs[fs_frames.index(current_frame)] + filepath = os.path.normpath(filepath) + meshio_mesh = load_meshio_from_path(fs, filepath, obj) + else: + meshio_mesh = meshio.Mesh([], []) + else: + filepath = fs[current_frame % len(fs)] + filepath = os.path.normpath(filepath) + meshio_mesh = load_meshio_from_path(fs, filepath, obj) if not isinstance(meshio_mesh, meshio.Mesh): show_message_box('function preprocess does not return meshio object', "ERROR") @@ -302,4 +357,6 @@ def update_obj(scene, depsgraph=None): update_mesh(meshio_mesh, obj.data) apply_transformation(meshio_mesh, obj, depsgraph) - \ No newline at end of file + + end_time = time.perf_counter() + obj.BSEQ.last_benchmark = (end_time - start_time) * 1000 diff --git a/bseq/messenger.py b/bseq/messenger.py index 507bc49..25cceab 100644 --- a/bseq/messenger.py +++ b/bseq/messenger.py @@ -6,7 +6,10 @@ def selected_callback(): # seems like that this is not necessary # if not bpy.context.view_layer.objects.active: # return - + + if not bpy.context.active_object: + return + name = bpy.context.active_object.name idx = bpy.data.objects.find(name) if idx >= 0: @@ -17,7 +20,8 @@ def selected_callback(): bpy.context.scene.BSEQ.edit_obj = bpy.context.active_object def subscribe_to_selected(): - import bseq + # import bseq + bseq = __loader__ # because current implementation may subscribe twice # so clear once to avoid duplication @@ -34,5 +38,6 @@ def subscribe_to_selected(): def unsubscribe_to_selected(): - import bseq + # import bseq + bseq = __loader__ bpy.msgbus.clear_by_owner(bseq) diff --git a/bseq/operators.py b/bseq/operators.py index 0190329..7168868 100644 --- a/bseq/operators.py +++ b/bseq/operators.py @@ -3,14 +3,29 @@ import fileseq from .messenger import * import traceback -from .utils import refresh_obj, show_message_box +from .utils import refresh_obj, show_message_box, get_relative_path from .importer import create_obj, create_meshio_obj import numpy as np +import os +addon_name = "blendersequenceloader" -# Here are load and delete operations +def relative_path_error(): + show_message_box("When using relative path, please save file before using it", icon="ERROR") + return {"CANCELLED"} + +def get_transform_matrix(importer_prop): + if importer_prop.use_custom_transform: + return Matrix.LocRotScale(importer_prop.custom_location, importer_prop.custom_rotation, importer_prop.custom_scale) + else: + return Matrix.Identity(4) + +def create_obj_wrapper(seq, importer_prop): + create_obj(seq, importer_prop.use_relative, importer_prop.root_path, transform_matrix=get_transform_matrix(importer_prop)) + +# Legacy import operator (this is what the "Import from folder" button does) class BSEQ_OT_load(bpy.types.Operator): - '''This operator loads a sequnce''' + '''Load selected sequence''' bl_label = "Load Sequence" bl_idname = "sequence.load" bl_options = {"UNDO"} @@ -19,10 +34,8 @@ def execute(self, context): scene = context.scene importer_prop = scene.BSEQ - if importer_prop.relative and not bpy.data.is_saved: - # use relative but file not saved - show_message_box("When using relative path, please save file before using it", icon="ERROR") - return {"CANCELLED"} + if importer_prop.use_relative and not bpy.data.is_saved: + return relative_path_error() fs = importer_prop.fileseq use_pattern = importer_prop.use_pattern @@ -37,24 +50,19 @@ def execute(self, context): fs = importer_prop.path + '/' + importer_prop.pattern try: - fs = fileseq.findSequenceOnDisk(fs) + # Call os.path.abspath in addition because findSequenceOnDisk does not support \..\ components on Windows apparently + fs = fileseq.findSequenceOnDisk(os.path.abspath(bpy.path.abspath(fs))) except Exception as e: show_message_box(traceback.format_exc(), "Can't find sequence: " + str(fs), "ERROR") return {"CANCELLED"} - transform_matrix = (Matrix.LocRotScale( - importer_prop.custom_location, - importer_prop.custom_rotation, - importer_prop.custom_scale) - if importer_prop.use_custom_transform else Matrix.Identity(4)) - - create_obj(fs, importer_prop.relative, importer_prop.root_path, transform_matrix=transform_matrix) + create_obj_wrapper(fs, importer_prop) return {"FINISHED"} class BSEQ_OT_edit(bpy.types.Operator): - '''This operator changes a sequnce''' - bl_label = "Edit Sequences Path" + '''Edit Sequence''' + bl_label = "Edit the path of the sequence" bl_idname = "sequence.edit" bl_options = {"UNDO"} @@ -62,10 +70,9 @@ def execute(self, context): scene = context.scene importer_prop = scene.BSEQ - if importer_prop.relative and not bpy.data.is_saved: + if importer_prop.use_relative and not bpy.data.is_saved: # use relative but file not saved - show_message_box("When using relative path, please save file before using it", icon="ERROR") - return {"CANCELLED"} + return relative_path_error() fs = importer_prop.fileseq use_pattern = importer_prop.use_pattern @@ -92,16 +99,19 @@ def execute(self, context): obj = sim_loader.edit_obj if not obj: return {"CANCELLED"} - if importer_prop.relative: - obj.BSEQ.pattern = bpy.path.relpath(str(fs)) + if importer_prop.use_relative: + if importer_prop.root_path != "": + object.BSEQ.pattern = bpy.path.relpath(str(fileseq), start=importer_prop.root_path) + else: + object.BSEQ.pattern = bpy.path.relpath(str(fileseq)) + else: obj.BSEQ.pattern = str(fs) - obj.BSEQ.use_relative = importer_prop.relative return {"FINISHED"} class BSEQ_OT_resetpt(bpy.types.Operator): - '''This operator reset the geometry nodes of the sequence as a point cloud''' + '''This operator resets the geometry nodes of the sequence as a point cloud''' bl_label = "Reset Geometry Nodes as Point Cloud" bl_idname = "bseq.resetpt" bl_options = {"UNDO"} @@ -136,7 +146,7 @@ def execute(self, context): class BSEQ_OT_resetmesh(bpy.types.Operator): - '''This operator reset the geometry nodes of the sequence as a point cloud''' + '''This operator resets the geometry nodes of the sequence as a point cloud''' bl_label = "Reset Geometry Nodes as Mesh" bl_idname = "bseq.resetmesh" bl_options = {"UNDO"} @@ -161,7 +171,7 @@ def execute(self, context): class BSEQ_OT_resetins(bpy.types.Operator): - '''This operator reset the geometry nodes of the sequence as a point cloud''' + '''This operator resets the geometry nodes of the sequence as a point cloud''' bl_label = "Reset Geometry Nodes as Instances" bl_idname = "bseq.resetins" bl_options = {"UNDO"} @@ -209,8 +219,8 @@ def execute(self, context): class BSEQ_OT_set_as_split_norm(bpy.types.Operator): - '''This operator set the vertex attribute as vertex split normals''' - bl_label = "Set as split normal per Vertex" + '''Set vertex attribute as vertex split normals''' + bl_label = "Set as split normal per vertex" bl_idname = "bseq.setsplitnorm" bl_options = {"UNDO"} @@ -228,8 +238,8 @@ def execute(self, context): class BSEQ_OT_remove_split_norm(bpy.types.Operator): - '''This operator remove the vertex attribute as vertex split normals''' - bl_label = "Remove split normal per Vertex" + '''Remove vertex attribute as vertex split normals''' + bl_label = "Remove split normal per vertex" bl_idname = "bseq.removesplitnorm" bl_options = {"UNDO"} @@ -244,8 +254,8 @@ def execute(self, context): class BSEQ_OT_disable_selected(bpy.types.Operator): - '''This operator disable all selected sequence''' - bl_label = "Disable Selected Sequence" + '''Deactivate selected sequences''' + bl_label = "Deactivate sequence" bl_idname = "bseq.disableselected" bl_options = {"UNDO"} @@ -257,8 +267,8 @@ def execute(self, context): class BSEQ_OT_enable_selected(bpy.types.Operator): - '''This operator enable all selected sequence''' - bl_label = "Enable Selected Sequence" + '''Activate selected sequences''' + bl_label = "Activate sequence" bl_idname = "bseq.enableselected" bl_options = {"UNDO"} @@ -270,8 +280,8 @@ def execute(self, context): class BSEQ_OT_refresh_seq(bpy.types.Operator): - '''This operator refresh the sequence''' - bl_label = "Refresh Sequence" + '''Refresh selected sequences''' + bl_label = "Refresh sequence" bl_idname = "bseq.refresh" def execute(self, context): @@ -282,8 +292,8 @@ def execute(self, context): return {"FINISHED"} class BSEQ_OT_disable_all(bpy.types.Operator): - '''This operator disable all selected sequence''' - bl_label = "Disable All Sequences" + '''Deactivate all sequences''' + bl_label = "Deactivate all sequences" bl_idname = "bseq.disableall" bl_options = {"UNDO"} @@ -294,8 +304,8 @@ def execute(self, context): return {"FINISHED"} class BSEQ_OT_enable_all(bpy.types.Operator): - '''This operator enable all selected sequence''' - bl_label = "Enable All Sequences" + '''Activate all sequences''' + bl_label = "Activate all sequences" bl_idname = "bseq.enableall" bl_options = {"UNDO"} @@ -306,33 +316,81 @@ def execute(self, context): return {"FINISHED"} class BSEQ_OT_refresh_sequences(bpy.types.Operator): - '''This operator refreshes all found sequences''' - bl_label = "" #"Refresh Found Sequences" - bl_idname = "bseq.refreshseqs" + '''Refresh all sequences''' + bl_label = "Reloads everything in selected folder" + bl_idname = "bseq.refreshall" bl_options = {"UNDO"} def execute(self, context): scene = context.scene # call the update function of path by setting it to its own value scene.BSEQ.path = scene.BSEQ.path + + return {"FINISHED"} + +class BSEQ_OT_set_start_end_frames(bpy.types.Operator): + '''This operator changes the timeline start and end frames to the length of a specific sequence''' + bl_label = "Set timeline" + bl_idname = "bseq.set_start_end_frames" + bl_options = {"UNDO"} + + def execute(self, context): + scene = context.scene + obj = bpy.data.objects[scene.BSEQ.selected_obj_num] + (start, end) = obj.BSEQ.start_end_frame + scene.frame_start = 0 + scene.frame_end = end - start + return {"FINISHED"} from pathlib import Path import meshio from bpy_extras.io_utils import ImportHelper -class WM_OT_batchSequences(bpy.types.Operator, ImportHelper): - """Batch Import Sequences""" +# This is what the button "Import Sequences" does +class BSEQ_OT_batch_sequences(bpy.types.Operator, ImportHelper): + """Import one or multiple sequences""" bl_idname = "wm.seq_import_batch" - bl_label = "Import multiple sequences" + bl_label = "Import Sequences" bl_options = {'PRESET', 'UNDO'} + def update_filter_glob(self, context): + bpy.ops.wm.seq_import_batch('INVOKE_DEFAULT') + + filter_string: bpy.props.StringProperty( + default="*.obj", + options={'HIDDEN'}, + update=update_filter_glob, + ) + + filename_ext='' + filter_glob: bpy.props.StringProperty( + default='*.obj', + options={'HIDDEN', 'LIBRARY_EDITABLE'}, + ) + files: bpy.props.CollectionProperty(type=bpy.types.PropertyGroup) + + def invoke(self, context, event): + scene = context.scene + if scene.BSEQ.filter_string: + self.filter_glob = scene.BSEQ.filter_string + else: + self.filter_glob = "*" + + context.window_manager.fileselect_add(self) + + return {'RUNNING_MODAL'} def execute(self, context): scene = context.scene importer_prop = scene.BSEQ + if importer_prop.use_relative and not bpy.data.is_saved: + return relative_path_error() + + self.filter_glob = '*' + folder = Path(self.filepath) used_seqs = set() @@ -340,19 +398,225 @@ def execute(self, context): # Check if there exists a matching file sequence for every selection fp = str(Path(folder.parent, selection.name)) seqs = fileseq.findSequencesOnDisk(str(folder.parent)) - matching_seqs = [s for s in seqs if fp in list(s) and s not in used_seqs] + matching_seq = [s for s in seqs if fp in list(s) and str(s) not in used_seqs] + + if matching_seq: + matching_seq = matching_seq[0] + used_seqs.add(str(matching_seq)) + + create_obj_wrapper(matching_seq, importer_prop) + return {'FINISHED'} + + def draw(self, context): + pass + +class BSEQ_PT_batch_sequences_settings(bpy.types.Panel): + bl_space_type = 'FILE_BROWSER' + bl_region_type = 'TOOL_PROPS' + bl_label = "Settings Panel" + bl_options = {'HIDE_HEADER'} + # bl_parent_id = "FILE_PT_operator" # Optional + + @classmethod + def poll(cls, context): + sfile = context.space_data + operator = sfile.active_operator + return operator.bl_idname == "WM_OT_seq_import_batch" + + def draw(self, context): + layout = self.layout + importer_prop = context.scene.BSEQ + + layout.use_property_split = True + layout.use_property_decorate = False # No animation. + + # # sfile = context.space_data + # # operator = sfile.active_operator + + # layout.prop(importer_prop, 'filter_string') + + # layout.alignment = 'LEFT' + # layout.prop(importer_prop, "relative", text="Relative Path") + # if importer_prop.use_relative: + # layout.prop(importer_prop, "root_path", text="Root Directory") + +class BSEQ_addon_preferences(bpy.types.AddonPreferences): + bl_idname = __package__ + + zips_folder: bpy.props.StringProperty( + name="Zips Folder", + subtype='DIR_PATH', + ) + + def draw(self, context): + # layout = self.layout + # layout.label(text="Please set a folder to store the extracted zip files") + # layout.prop(self, "zips_folder", text="Zips Folder") + pass + +zip_folder_name = '/tmp_zips' + +class BSEQ_OT_import_zip(bpy.types.Operator, ImportHelper): + """Import a zip file""" + bl_idname = "bseq.import_zip" + bl_label = "Import Zip" + bl_options = {'PRESET', 'UNDO'} + + filename_ext = ".zip" + filter_glob: bpy.props.StringProperty( + default="*.zip", + options={'HIDDEN', 'LIBRARY_EDITABLE'}, + ) + + files: bpy.props.CollectionProperty(type=bpy.types.PropertyGroup) + + def execute(self, context): + importer_prop = context.scene.BSEQ + + import zipfile + zip_file = zipfile.ZipFile(self.filepath) + + addon_prefs = context.preferences.addons[addon_name].preferences + # Check if a string is empty: + if not addon_prefs.zips_folder: + show_message_box("Please set a folder to store the extracted zip files", icon="ERROR") + return {"CANCELLED"} + zips_folder = addon_prefs.zips_folder + zip_folder_name + + valid_files = [info.filename for info in zip_file.infolist() if not info.filename.startswith('__MACOSX/')] + zip_file.extractall(zips_folder, members=valid_files) + zip_file.close() + + folder = str(zips_folder) + '/' + str(Path(self.filepath).name)[:-4] + print(folder) + + seqs = fileseq.findSequencesOnDisk(str(folder)) + if not seqs: + show_message_box("No sequences found in the zip file", icon="ERROR") + return {"CANCELLED"} + + for s in seqs: + # Import it with absolute paths + create_obj(s, False, folder, transform_matrix=get_transform_matrix(importer_prop)) + + # created_folder = context.scene.BSEQ.imported_zips.add() + # created_folder.path = folder + + return {'FINISHED'} + +class BSEQ_OT_delete_zips(bpy.types.Operator): + """Delete a zip file""" + bl_idname = "bseq.delete_zips" + bl_label = "Delete Zip" + bl_options = {'PRESET', 'UNDO'} + + def execute(self, context): + # folders = context.scene.BSEQ.imported_zips + # for folder in folders: + + addon_prefs = context.preferences.addons[addon_name].preferences + zips_folder = addon_prefs.zips_folder + zip_folder_name + + import shutil + shutil.rmtree(zips_folder) + + return {'FINISHED'} + +class BSEQ_OT_load_all(bpy.types.Operator): + """Load all sequences from selected folder and its subfolders""" + bl_idname = "bseq.load_all" + bl_label = "Load All" + bl_options = {'PRESET', 'UNDO'} + + def execute(self, context): + importer_prop = context.scene.BSEQ + + if importer_prop.use_relative and not bpy.data.is_saved: + return relative_path_error() + + p = importer_prop.path + seqs = fileseq.findSequencesOnDisk(bpy.path.abspath(p)) + + for s in seqs: + print(s) + + for s in seqs: + create_obj_wrapper(s, importer_prop) + return {'FINISHED'} + +class BSEQ_OT_load_all_recursive(bpy.types.Operator): + """Load all sequences from selected folder recursively""" + bl_idname = "bseq.load_all_recursive" + bl_label = "Load All Recursive" + bl_options = {'PRESET', 'UNDO'} + + def execute(self, context): + importer_prop = context.scene.BSEQ + + if importer_prop.use_relative and not bpy.data.is_saved: + return relative_path_error() + + root_dir = bpy.path.abspath(importer_prop.path) + root_coll = bpy.context.scene.collection + root_layer_collection = bpy.context.view_layer.layer_collection + unlinked_collections = [] + # Recurse through directory itself and subdirectories + for current_dir, subdirs, files in os.walk(root_dir): + seqs = fileseq.findSequencesOnDisk(current_dir) + if len(seqs) == 0: + continue + + # Get list of directories from the root_dir to the current directory + coll_list = bpy.path.relpath(current_dir, start=root_dir).strip("//").split("/") + + # Get or create a nested collection starting from the root + last_coll = root_coll + layer_collection = root_layer_collection + for coll in coll_list: + # If it already exists and is not in the children of the last collection, then the prefix has changed + cur_coll = bpy.data.collections.get(coll) + if cur_coll is not None and last_coll is not None: + if cur_coll.name not in last_coll.children: + # Get the old parent of the existing collection and move the children to the old parent + parent = [c for c in bpy.data.collections if bpy.context.scene.user_of_id(cur_coll) and cur_coll.name in c.children] + if len(parent) > 0: + for child in cur_coll.children: + parent[0].children.link(child) + for obj in cur_coll.objects: + parent[0].objects.link(obj) + parent[0].children.unlink(cur_coll) + unlinked_collections.append(cur_coll) + else: + layer_collection = layer_collection.children[cur_coll.name] + last_coll = cur_coll + + + # If it was newly created, link it to the last collection + if cur_coll is None and last_coll is not None: + cur_coll = bpy.data.collections.new(coll) + last_coll.children.link(cur_coll) + layer_collection = layer_collection.children[cur_coll.name] + last_coll = cur_coll + + # Set the last collection as the active collection by recursing through the collections + context.view_layer.active_layer_collection = layer_collection + + # for s in seqs: + # print(s) + + for s in seqs: + create_obj_wrapper(s, importer_prop) - if matching_seqs: - transform_matrix = (Matrix.LocRotScale(importer_prop.custom_location, importer_prop.custom_rotation, importer_prop.custom_scale) - if importer_prop.use_custom_transform else Matrix.Identity(4)) - create_obj(matching_seqs[0], False, importer_prop.root_path, transform_matrix=transform_matrix) - used_seqs.add(matching_seqs[0]) + # Make sure unused datablocks are freed + for coll in unlinked_collections: + bpy.data.collections.remove(coll) return {'FINISHED'} + -class WM_OT_MeshioObject(bpy.types.Operator, ImportHelper): +class BSEQ_OT_meshio_object(bpy.types.Operator, ImportHelper): """Batch Import Meshio Objects""" bl_idname = "wm.meshio_import_batch" - bl_label = "Import multiple Meshio objects" + bl_label = "Import Multiple Meshio Objects" bl_options = {'PRESET', 'UNDO'} files: bpy.props.CollectionProperty(type=bpy.types.PropertyGroup) @@ -367,5 +631,60 @@ def execute(self, context): def menu_func_import(self, context): self.layout.operator( - WM_OT_MeshioObject.bl_idname, + BSEQ_OT_meshio_object.bl_idname, text="MeshIO Object") + +# Default Keymap Configuration +addon_keymaps = [] + +def add_keymap(): + wm = bpy.context.window_manager + + # Add new keymap section for BSEQ + + kc = wm.keyconfigs.addon + if kc: + km = kc.keymaps.new(name='3D View', space_type='VIEW_3D') + kmi = km.keymap_items.new("sequence.load", type='F', value='PRESS', shift=True) + addon_keymaps.append((km, kmi)) + + km = kc.keymaps.new(name='3D View', space_type='VIEW_3D') + kmi = km.keymap_items.new("bseq.disableselected", type='D', value='PRESS', shift=True, ctrl=True) + addon_keymaps.append((km, kmi)) + + km = kc.keymaps.new(name='3D View', space_type='VIEW_3D') + kmi = km.keymap_items.new("bseq.enableselected", type='E', value='PRESS', shift=True, ctrl=True) + addon_keymaps.append((km, kmi)) + + km = kc.keymaps.new(name='3D View', space_type='VIEW_3D') + kmi = km.keymap_items.new("bseq.refresh", type='R', value='PRESS', shift=True, ctrl=True) + addon_keymaps.append((km, kmi)) + + km = kc.keymaps.new(name='3D View', space_type='VIEW_3D') + kmi = km.keymap_items.new("bseq.disableall", type='D', value='PRESS', shift=True, alt=True) + addon_keymaps.append((km, kmi)) + + km = kc.keymaps.new(name='3D View', space_type='VIEW_3D') + kmi = km.keymap_items.new("bseq.enableall", type='E', value='PRESS', shift=True, alt=True) + addon_keymaps.append((km, kmi)) + + km = kc.keymaps.new(name='3D View', space_type='VIEW_3D') + kmi = km.keymap_items.new("bseq.refreshall", type='R', value='PRESS', shift=True, alt=True) + addon_keymaps.append((km, kmi)) + + km = kc.keymaps.new(name='3D View', space_type='VIEW_3D') + kmi = km.keymap_items.new("bseq.set_start_end_frames", type='F', value='PRESS', shift=True, ctrl=True) + addon_keymaps.append((km, kmi)) + + km = kc.keymaps.new(name='3D View', space_type='VIEW_3D') + kmi = km.keymap_items.new("wm.seq_import_batch", type='I', value='PRESS', shift=True, ctrl=True) + addon_keymaps.append((km, kmi)) + + km = kc.keymaps.new(name='3D View', space_type='VIEW_3D') + kmi = km.keymap_items.new("wm.meshio_import_batch", type='M', value='PRESS', shift=True, ctrl=True) + addon_keymaps.append((km, kmi)) + +def delete_keymap(): + for km, kmi in addon_keymaps: + km.keymap_items.remove(kmi) + addon_keymaps.clear() diff --git a/bseq/panels.py b/bseq/panels.py index c35ec7a..5c9484e 100644 --- a/bseq/panels.py +++ b/bseq/panels.py @@ -13,7 +13,7 @@ def filter_items(self, context, data, property): # not sure if I understand correctly about this # see reference from https://docs.blender.org/api/current/bpy.types.UIList.html#advanced-uilist-example-filtering-and-reordering for o in objs: - if o.BSEQ.init: + if o.BSEQ.init and len(o.users_collection)>0 and len(o.users_scene)>0: flt_flags.append(self.bitflag_filter_item) else: flt_flags.append(0) @@ -22,19 +22,32 @@ def filter_items(self, context, data, property): def draw_item(self, context, layout, data, item, icon, active_data, active_propname): if item: - row = layout.row() - row.prop(item, "name", text='Name ', emboss=False) + split = layout.split(factor=0.4) + col1 = split.column() + col2 = split.column() + split2 = col2.split(factor=0.25) + col2 = split2.column() + col3 = split2.column() + split3 = col3.split(factor=0.5) + col3 = split3.column() + col4 = split3.column() + col4.alignment = 'EXPAND' + start_frame = item.BSEQ.start_end_frame[0] + end_frame = item.BSEQ.start_end_frame[1] + + col1.prop(item, "name", text='', emboss=False) if item.BSEQ.enabled: - row.prop(item.BSEQ, "enabled", text = "ENABLED", icon="PLAY") - row.prop(item.BSEQ, "frame", text = "Current Frame:") + col2.prop(item.BSEQ, "enabled", text="", icon="PLAY") + col3.prop(item.BSEQ, "frame", text="") + col4.label(text=str(start_frame) + '-' + str(end_frame)) else: - row.prop(item.BSEQ, "enabled", text = "DISABLED", icon="PAUSE") - row.label(text = "Animation Stopped") + col2.prop(item.BSEQ, "enabled", text ="", icon="PAUSE") + col3.label(text="", icon="BLANK1") + col4.label(text=str(start_frame) + '-' + str(end_frame)) else: # actually, I guess this line of code won't be executed? layout.label(text="", translate=False, icon_value=icon) - class BSEQ_UL_Att_List(bpy.types.UIList): ''' This controls the list of attributes available for this sequence @@ -43,81 +56,69 @@ class BSEQ_UL_Att_List(bpy.types.UIList): def draw_item(self, context, layout, data, item, icon, active_data, active_propname): if item: layout.enabled = False - layout.prop(item, "name", text='Name ', emboss=False) + layout.prop(item, "name", text='', emboss=False) obj = bpy.data.objects[context.scene.BSEQ.selected_obj_num] mesh = obj.data if mesh.BSEQ.split_norm_att_name and mesh.BSEQ.split_norm_att_name == item.name: - layout.label(text="using as split norm") + layout.label(text="Use as split norm.") else: # actually, I guess this line of code won't be executed? layout.label(text="", translate=False, icon_value=icon) - -class BSEQ_List_Panel(bpy.types.Panel): - ''' - This is the panel of imported sequences, bottom part of images/9.png - ''' - bl_label = "Imported Sequences" - bl_idname = "BSEQ_PT_list" +class BSEQ_Panel: bl_space_type = 'VIEW_3D' bl_region_type = "UI" bl_category = "Sequence Loader" bl_context = "objectmode" +class BSEQ_Globals_Panel(BSEQ_Panel, bpy.types.Panel): + bl_label = "Global Settings" + bl_idname = "BSEQ_PT_global" + bl_options = {'DEFAULT_CLOSED'} + def draw(self, context): layout = self.layout sim_loader = context.scene.BSEQ - row = layout.row() - row.template_list("BSEQ_UL_Obj_List", "", bpy.data, "objects", sim_loader, "selected_obj_num", rows=2) - row = layout.row() - row.operator("bseq.enableselected", text="Enable Selected") - row.operator("bseq.disableselected", text="Disable Selected") - row.operator("bseq.refresh", text="Refresh") - row = layout.row() - row.operator("bseq.enableall", text="Enable All") - row.operator("bseq.disableall", text="Disable All") + split = layout.split() + col1 = split.column() + col1.alignment = 'RIGHT' + col2 = split.column() + col1.label(text="Root Directory") + col2.prop(sim_loader, "root_path", text="") + col1.label(text="Print Sequence Information") + col2.prop(sim_loader, "print", text="") + col1.label(text="Auto Refresh Active") + col2.prop(sim_loader, "auto_refresh_active", text="") + col1.label(text="Auto Refresh All") + col2.prop(sim_loader, "auto_refresh_all", text="") - -class BSEQ_Settings(bpy.types.Panel): - ''' - This is the panel of settings of selected sequence - ''' - bl_label = "Sequence Settings" - bl_idname = "BSEQ_PT_settings" - bl_space_type = 'VIEW_3D' - bl_region_type = "UI" - bl_category = "Sequence Loader" - bl_context = "objectmode" - bl_options = {"DEFAULT_CLOSED"} +class BSEQ_Advanced_Panel(BSEQ_Panel, bpy.types.Panel): + bl_label = "Advanced Settings" + bl_idname = "BSEQ_PT_advanced" + bl_options = {'DEFAULT_CLOSED'} def draw(self, context): layout = self.layout sim_loader = context.scene.BSEQ + + split = layout.split() + col1 = split.column() + col2 = split.column() + if sim_loader.selected_obj_num >= len(bpy.data.objects): return obj = bpy.data.objects[sim_loader.selected_obj_num] if not obj.BSEQ.init: return - # path settings - layout.label(text="Sequence Information (read-only)") - box = layout.box() - - split = box.split() - col1 = split.column() - col1.alignment = 'RIGHT' - col2 = split.column(align=False) - - col2.enabled = False - col1.label(text='Relative') - col2.prop(obj.BSEQ, 'use_relative', text="") - col1.label(text='Pattern') - col2.prop(obj.BSEQ, 'pattern', text="") + col1.label(text='Script') + col2.prop_search(obj.BSEQ, 'script_name', bpy.data, 'texts', text="") # geometry nodes settings - layout.label(text="Geometry Nodes") + layout.label(text="Geometry Nodes (select sequence first)") + box = layout.box() box.label(text="Point Cloud and Instances Material") split = box.split() @@ -137,6 +138,70 @@ def draw(self, context): col3.operator('bseq.resetins', text="Instances") +class BSEQ_List_Panel(BSEQ_Panel, bpy.types.Panel): + ''' + This is the panel of imported sequences, bottom part of images/9.png + ''' + bl_label = "Sequences" + bl_idname = "BSEQ_PT_list" + bl_options = {'DEFAULT_CLOSED'} + + def draw(self, context): + layout = self.layout + sim_loader = context.scene.BSEQ + row = layout.row() + row.template_list("BSEQ_UL_Obj_List", "", bpy.data, "objects", sim_loader, "selected_obj_num", rows=2) + row = layout.row() + row.operator("bseq.enableselected", text="Activate") + row.operator("bseq.disableselected", text="Deactivate") + row.operator("bseq.refresh", text="Refresh") + row = layout.row() + row.operator("bseq.enableall", text="Activate All") + row.operator("bseq.disableall", text="Deactivate All") + row.operator("bseq.set_start_end_frames", text="Set timeline") + +class BSEQ_Settings(BSEQ_Panel, bpy.types.Panel): + ''' + This is the panel of settings of selected sequence + ''' + bl_label = "Sequence Properties" + bl_idname = "BSEQ_PT_settings" + bl_options = {"DEFAULT_CLOSED"} + + def draw(self, context): + layout = self.layout + sim_loader = context.scene.BSEQ + importer_prop = context.scene.BSEQ + + if sim_loader.selected_obj_num >= len(bpy.data.objects): + return + obj = bpy.data.objects[sim_loader.selected_obj_num] + if not obj.BSEQ.init: + return + + split = layout.split() + col1 = split.column() + col1.alignment = 'RIGHT' + col2 = split.column(align=False) + + col1.label(text='Match Blender frame numbers') + col2.prop(obj.BSEQ, 'match_frames', text="") + + col1.label(text='Path') + col2.prop(obj.BSEQ, 'path', text="") + col1.label(text='Pattern') + col2.prop(obj.BSEQ, 'pattern', text="") + # Read-only + col1.label(text='Current File') + # make it read-only + row1 = col2.row() + row1.enabled = False + row1.prop(obj.BSEQ, 'current_file', text="") + col1.label(text='Last loading time (ms)') + row2 = col2.row() + row2.enabled = False + row2.prop(obj.BSEQ, 'last_benchmark', text="", ) + # attributes settings layout.label(text="Attributes") box = layout.box() @@ -145,39 +210,74 @@ def draw(self, context): box.operator("bseq.setsplitnorm", text="Set selected as normal") box.operator("bseq.removesplitnorm", text="Clear normal") - # advance settings - layout.label(text="Advanced") - box = layout.box() - split = box.split() +class BSEQ_PT_Import(BSEQ_Panel, bpy.types.Panel): + ''' + This is the panel of main addon interface. see images/1.jpg + ''' + bl_label = "Import" + bl_idname = "BSEQ_PT_panel" + + def draw(self, context): + layout = self.layout + scene = context.scene + importer_prop = scene.BSEQ + + row = layout.row() + + row.scale_y = 1.5 + row.operator("wm.seq_import_batch") + + split = layout.split() + col1 = split.column() + col2 = split.column() + + split = layout.split(factor=0.5) col1 = split.column() col1.alignment = 'RIGHT' col2 = split.column(align=False) - col1.label(text="Show Settings") - col2.prop(obj.BSEQ, 'use_advance', text="") - if obj.BSEQ.use_advance: - col1.label(text='Script') - col2.prop_search(obj.BSEQ, 'script_name', bpy.data, 'texts', text="") + # col2.prop(importer_prop, "filter_string", text="Filter String") -class BSEQ_Import(bpy.types.Panel): - ''' - This is the panel of main addon interface. see images/1.jpg - ''' - bl_label = "Sequence Loader" - bl_idname = "BSEQ_PT_panel" - bl_space_type = "VIEW_3D" - bl_region_type = "UI" - bl_category = "Sequence Loader" - bl_context = "objectmode" + col1.label(text="Relative Paths") + col2.prop(importer_prop, "use_relative", text="") + + if importer_prop.use_relative: + col1.label(text="Relative Root") + col2.prop(importer_prop, "root_path", text="") + + + col1.label(text="Import Normals") + col2.prop(importer_prop, "use_imported_normals", text="") + + col1.label(text="Custom Transform") + col2.prop(importer_prop, "use_custom_transform", text="") + + if importer_prop.use_custom_transform: + split = layout.split(factor=0.33) + box_col1 = split.column() + box_col2 = split.column() + box_col3 = split.column() + + box_col1.label(text="Location:") + box_col1.prop(importer_prop, "custom_location", text="") + + box_col2.label(text="Rotation:") + box_col2.prop(importer_prop, "custom_rotation", text="") + + box_col3.label(text="Scale:") + box_col3.prop(importer_prop, "custom_scale", text="") + +class BSEQ_PT_Import_Child1(BSEQ_Panel, bpy.types.Panel): + bl_parent_id = "BSEQ_PT_panel" + bl_label = "Import from folder" + bl_options = {'DEFAULT_CLOSED'} def draw(self, context): layout = self.layout scene = context.scene importer_prop = scene.BSEQ - layout.label(text="Basic Import Settings") - box = layout.box() - split = box.split() + split = layout.split() col1 = split.column() col1.alignment = 'RIGHT' col2 = split.column(align=False) @@ -185,7 +285,7 @@ def draw(self, context): col1.label(text="Directory") col2.prop(importer_prop, "path", text="") - col1.label(text="Use Custom Pattern") + col1.label(text="Custom Pattern") col2.prop(importer_prop, "use_pattern", text="") col1.label(text="Sequence Pattern") if importer_prop.use_pattern: @@ -195,58 +295,37 @@ def draw(self, context): col3 = split2.column() col4 = split2.column() col3.prop(importer_prop, "fileseq", text="") - col4.operator("bseq.refreshseqs", icon="FILE_REFRESH") - - col1.label(text="Use Relative Path") - col2.prop(importer_prop, "relative", text="") - - if importer_prop.relative: - col1.label(text="Root Directory") - col2.prop(importer_prop, "root_path", text="") - - layout.operator("sequence.load") + col4.operator("bseq.refreshall", text='', icon="FILE_REFRESH") - layout.operator("wm.seq_import_batch") - - split = layout.split() + split = layout.split(factor=0.5) col1 = split.column() col2 = split.column() + col1.operator("sequence.load") + row = col2.row() + row.operator("bseq.load_all") + row.operator("bseq.load_all_recursive") - # check if edit_obj exist - # if not exist any more, then delete the object manually - # see here https://blender.stackexchange.com/a/164835 for more details - # I personally think this implementation is not a good design, - # but can't think of any better ways now - if importer_prop.edit_obj and context.scene.objects.get(importer_prop.edit_obj.name) == None: - bpy.data.objects.remove(importer_prop.edit_obj) + # split = layout.split(factor=0.5) + # col1 = split.column() + # col2 = split.column() - col1.prop_search(importer_prop, 'edit_obj', bpy.data, 'objects', text="") - col2.operator("sequence.edit") + # col1.operator("bseq.import_zip", text="Import from zip") + # col2.operator("bseq.delete_zips", text="Delete created folders") - layout.label(text="Global Settings") - box = layout.box() - split = box.split() - col1 = split.column() - col1.alignment = 'RIGHT' - col2 = split.column(align=False) - - col1.label(text="Print Sequence Information on Render") - col2.prop(importer_prop, "print", text="") - col1.label(text="Auto refresh all the sequence every frame") - col2.prop(importer_prop, "auto_refresh", text="") - col1.label(text="Use custom transformation matrix") - col2.prop(importer_prop, "use_custom_transform", text="") - if importer_prop.use_custom_transform: - box.label(text="Location:") - box.prop(importer_prop, "custom_location", text="") +class BSEQ_PT_Import_Child2(BSEQ_Panel, bpy.types.Panel): + bl_parent_id = "BSEQ_PT_panel" + bl_label = "Test" + bl_options = {'HIDE_HEADER'} - box.label(text="Rotation:") - box.prop(importer_prop, "custom_rotation", text="") + def draw(self, context): + layout = self.layout + scene = context.scene + importer_prop = scene.BSEQ - box.label(text="Scale:") - box.prop(importer_prop, "custom_scale", text="") - + split = layout.split() + col1 = split.column() + col2 = split.column() class BSEQ_Templates(bpy.types.Menu): ''' diff --git a/bseq/properties.py b/bseq/properties.py index d839791..c99903e 100644 --- a/bseq/properties.py +++ b/bseq/properties.py @@ -5,37 +5,55 @@ class BSEQ_scene_property(bpy.types.PropertyGroup): path: bpy.props.StringProperty(name="Directory", subtype="DIR_PATH", - description="You need to go to the folder with the sequence, then click \"Accept\". ", - update=update_path) - relative: bpy.props.BoolProperty(name='Use relative path', description="whether or not to use reletive path", default=False) + description="You need to go to the folder with the sequence, then click \"Accept\"", + update=update_path, + ) + + use_relative: bpy.props.BoolProperty(name='Relative Paths', + description="Toggle relative paths on/off", + default=False, + ) + + use_imported_normals: bpy.props.BoolProperty(name='Import Normals', + description="Use normals from imported mesh (see README for details)", + default=False, + ) + root_path: bpy.props.StringProperty(name="Root Directory", subtype="DIR_PATH", - description="Select a root folder for all relative paths. When not set the current filename is used.", - update=update_path) + description="Select root folder for all relative paths. If empty, root is folder of the Blender file", + update=update_path, + default="", + ) + fileseq: bpy.props.EnumProperty( name="File Sequences", - description="Please choose the file sequences you want", + description="Select a file sequence", items=item_fileseq, ) - use_pattern: bpy.props.BoolProperty(name='Use pattern', - description="whether or not to use manually typed pattern", - default=False) + + use_pattern: bpy.props.BoolProperty(name='Custom Pattern', + description="Use manually typed pattern. Useful if the sequence can't be deteced", + default=False, + ) + pattern: bpy.props.StringProperty(name="Pattern", - description="You can specify the pattern here, in case the sequence can't be deteced.") + description="Custom pattern. Use @ for frame number. Example: file_@.obj", + ) - file_paths: bpy.props.StringProperty(name="File", - subtype="FILE_PATH", - description="Select a root folder for all relative paths. When not set the current filename is used.") - selected_obj_deselectall_flag: bpy.props.BoolProperty(default=True, - description="the flag to determine whether call deselect all or not ") - selected_obj_num: bpy.props.IntProperty(name='imported count', - description='the number of imported sequence, when selecting from ui list', + description="Flag that determines whether to deselect all items or not", + ) + + selected_obj_num: bpy.props.IntProperty(name='Sequences List', default=0, - update=update_selected_obj_num) - selected_attribute_num: bpy.props.IntProperty(default=0) + update=update_selected_obj_num, + ) + + selected_attribute_num: bpy.props.IntProperty(name="Select Vertex Attribute",default=0) material: bpy.props.PointerProperty( + name="Material", type=bpy.types.Material, poll=poll_material, ) @@ -45,48 +63,73 @@ class BSEQ_scene_property(bpy.types.PropertyGroup): poll=poll_edit_obj, ) - print: bpy.props.BoolProperty(name='print', - description="whether or not to print additional information when rendering", - default=True) + print: bpy.props.BoolProperty(name='Print Sequence Information', + description="Print useful information during rendering to file in same folder as render output", + default=True, + ) - auto_refresh: bpy.props.BoolProperty(name='auto refresh', - description="whether or not to auto refresh all the sequence every frame", - default=False) - - use_custom_transform: bpy.props.BoolProperty(name='Use custom transformation matrix', - description="Whether or not to use a custom transformation matrix", - default=False) + auto_refresh_active: bpy.props.BoolProperty(name='Auto Refresh Active Sequences', + description="Auto refresh all active sequences every frame", + default=False, + ) + + auto_refresh_all: bpy.props.BoolProperty(name='Auto Refresh All Sequences', + description="Auto refresh all sequences every frame", + default=False, + ) + + use_custom_transform: bpy.props.BoolProperty(name='Custom Transform', + description="Use a custom transformation matrix when importing", + default=False, + ) custom_location: bpy.props.FloatVectorProperty(name='Custom Location', description='Set custom location vector', size=3, - subtype="TRANSLATION") + subtype="TRANSLATION", + ) custom_rotation: bpy.props.FloatVectorProperty(name='Custom Rotation', - description='Set custom rotation vector', + description='Set custom Euler angles', size=3, subtype="EULER", - default=[0,0,0]) + default=[0,0,0], + ) custom_scale: bpy.props.FloatVectorProperty(name='Custom Scale', description='Set custom scaling vector', size=3, subtype="COORDINATES", - default=[1,1,1]) - + default=[1,1,1], + ) + + use_blender_obj_import: bpy.props.BoolProperty(name='Blender .obj import', + description="Use Blender's built-in .obj import function (or meshio's .obj import function)", + default=True, + ) + + filter_string: bpy.props.StringProperty(name='Filter String', + description='Filter string for file sequences', + default='', + ) + class BSEQ_obj_property(bpy.types.PropertyGroup): init: bpy.props.BoolProperty(default=False) enabled: bpy.props.BoolProperty(default=True, - description="When disbaled, the sequence won't be updated at each frame. Enabled by default") + name="Activate/Deactivate", + description="If deactivated, sequence won't be updated each frame") use_advance: bpy.props.BoolProperty(default=False) - script_name: bpy.props.StringProperty() - use_relative: bpy.props.BoolProperty(default=False) - pattern: bpy.props.StringProperty() - frame: bpy.props.IntProperty() - initial_transform_matrix: bpy.props.FloatVectorProperty(name='Custom Transformation Matrix', - description='Set custom transformation', - size=16, - subtype="MATRIX") + script_name: bpy.props.StringProperty(name="Script name") + path: bpy.props.StringProperty(name="Path of sequence", subtype="DIR_PATH") + pattern: bpy.props.StringProperty(name="Pattern of sequence") + current_file: bpy.props.StringProperty(description="File of sequence that is currently loaded") + frame: bpy.props.IntProperty(name="Frame") + start_end_frame: bpy.props.IntVectorProperty(name="Start and end frames", size=2, default=(0, 0)) + match_frames: bpy.props.BoolProperty(default=False, + name="Match Blender frame numbers", + description="Show only frames that match the current frame number", + ) + last_benchmark: bpy.props.FloatProperty(name="Last loading time") # set this property for mesh, not object (maybe change later?) class BSEQ_mesh_property(bpy.types.PropertyGroup): diff --git a/bseq/utils.py b/bseq/utils.py index af686b6..161542c 100644 --- a/bseq/utils.py +++ b/bseq/utils.py @@ -1,5 +1,8 @@ import bpy import fileseq +import os +import meshio +import traceback def show_message_box(message="", title="Message Box", icon="INFO"): ''' @@ -18,21 +21,57 @@ def draw(self, context): stop_animation() bpy.context.window_manager.popup_menu(draw, title=title, icon=icon) - def stop_animation(): if bpy.context.screen.is_animation_playing: # if playing animation, then stop it, otherwise it will keep showing message box bpy.ops.screen.animation_cancel() +def get_relative_path(path, root_path): + if root_path != "": + rel_path = bpy.path.relpath(path, start=bpy.path.abspath(root_path)) + else: + rel_path = bpy.path.relpath(path) + return rel_path + +# convert relative path to absolute path +def convert_to_absolute_path(path, root_path): + # Additional call to os.path.abspath removes any "/../"" in the path (can be a problem on Windows) + if root_path != "": + path = os.path.abspath(bpy.path.abspath(path, start=bpy.path.abspath(root_path))) + else: + path = os.path.abspath(bpy.path.abspath(path)) + return path +def get_absolute_path(obj, scene): + full_path = os.path.join(bpy.path.native_pathsep(obj.BSEQ.path), obj.BSEQ.pattern) + full_path = convert_to_absolute_path(full_path, scene.BSEQ.root_path) + return full_path def refresh_obj(obj, scene): - fs = obj.BSEQ.pattern - if obj.BSEQ.use_relative: - fs = bpy.path.abspath(fs, start=scene.BSEQ.root_path) + is_relative = obj.BSEQ.path.startswith("//") + fs = get_absolute_path(obj, scene) fs = fileseq.findSequenceOnDisk(fs) - fs = fileseq.findSequenceOnDisk(fs.dirname() + fs.basename() + "@" + fs.extension()) - fs = str(fs) - if obj.BSEQ.use_relative: - fs = bpy.path.relpath(fs, start=scene.BSEQ.root_path) - obj.BSEQ.pattern = fs \ No newline at end of file + #fs = fileseq.findSequenceOnDisk(fs.dirname() + fs.basename() + "@" + fs.extension()) + + full_path = str(fs) + path = os.path.dirname(full_path) + pattern = os.path.basename(full_path) + if is_relative: + path = get_relative_path(path, scene.BSEQ.root_path) + + obj.BSEQ.path = path + obj.BSEQ.pattern = pattern + obj.BSEQ.start_end_frame = (fs.start(), fs.end()) + +def load_meshio_from_path(fileseq, filepath, obj = None): + try: + meshio_mesh = meshio.read(filepath) + if obj is not None: + obj.BSEQ.current_file = filepath + except Exception as e: + show_message_box("Error when reading: " + filepath + ",\n" + traceback.format_exc(), + "Meshio Loading Error" + str(e), + icon="ERROR") + meshio_mesh = meshio.Mesh([], []) + return meshio_mesh + diff --git a/docs/conf.py b/docs/conf.py index e11683c..d4e3eb7 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -7,9 +7,9 @@ # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information project = 'blender-sequence-loader' -copyright = '2022, InteractiveComputerGraphics' +copyright = '2025, InteractiveComputerGraphics' author = 'InteractiveComputerGraphics' -release = '0.1.3' +release = '0.3.4' # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration diff --git a/download_wheels.sh b/download_wheels.sh new file mode 100755 index 0000000..1abd6b0 --- /dev/null +++ b/download_wheels.sh @@ -0,0 +1,4 @@ +pip wheel fileseq==1.15.2 -w ./wheels --no-deps +pip wheel meshio==5.3.4 -w ./wheels --no-deps +pip wheel future==0.18.3 -w ./wheels --no-deps +pip wheel rich==13.7.0 -w ./wheels --no-deps \ No newline at end of file diff --git a/extern/fileseq b/extern/fileseq index 9ec0493..584ee22 160000 --- a/extern/fileseq +++ b/extern/fileseq @@ -1 +1 @@ -Subproject commit 9ec049373af37ec21a21d2a5564deb344a96f97f +Subproject commit 584ee2218b74a9c7f4127c922cc2c33dc5a706b4 diff --git a/extern/meshio b/extern/meshio index a6175e0..0138cc8 160000 --- a/extern/meshio +++ b/extern/meshio @@ -1 +1 @@ -Subproject commit a6175e0d9dfb2aa274392d1cd396e991f0487cbc +Subproject commit 0138cc8692b806b44b32d344f7961e8370121ff7 diff --git a/extern/python-future b/extern/python-future index 80523f3..af1db97 160000 --- a/extern/python-future +++ b/extern/python-future @@ -1 +1 @@ -Subproject commit 80523f383fbba1c6de0551e19d0277e73e69573c +Subproject commit af1db970b0879b59e7aeb798c27a623144561cff diff --git a/extern/rich b/extern/rich index 3734ff4..fd98182 160000 --- a/extern/rich +++ b/extern/rich @@ -1 +1 @@ -Subproject commit 3734ff45d7b30541aabdd656efb80c9896d445b3 +Subproject commit fd981823644ccf50d685ac9c0cfe8e1e56c9dd35 diff --git a/images/drag.png b/images/drag.png index 9277da2..39fae42 100644 Binary files a/images/drag.png and b/images/drag.png differ diff --git a/images/list.png b/images/list.png index 09f119c..9e37f7f 100644 Binary files a/images/list.png and b/images/list.png differ diff --git a/images/location.png b/images/location.png index 074a05a..8b148ab 100644 Binary files a/images/location.png and b/images/location.png differ diff --git a/images/sequence.png b/images/sequence.png index a32bdcd..173eca0 100644 Binary files a/images/sequence.png and b/images/sequence.png differ diff --git a/template/Comparison Render.py b/template/Comparison Render.py new file mode 100644 index 0000000..f8b3e57 --- /dev/null +++ b/template/Comparison Render.py @@ -0,0 +1,64 @@ +import bpy + +# Utilities for comparison rendering +def toggle_on_single(obj): + obj.hide_render = False + if isinstance(obj, bpy.types.Object) and obj.BSEQ.init: + obj.BSEQ.enabled = True + for child in obj.children: + toggle_on_single(child) + elif isinstance(obj, bpy.types.Collection): + for child in obj.objects: + toggle_on_single(child) + for child in obj.children: + toggle_on_single(child) + +def toggle_on(objs): + if type(objs) == list: + for obj in objs: + toggle_on_single(obj) + else: + toggle_on_single(objs) + +def toggle_off_single(obj): + obj.hide_render = True + if isinstance(obj, bpy.types.Object) and obj.BSEQ.init: + obj.BSEQ.enabled = False + for child in obj.children: + toggle_off_single(child) + elif isinstance(obj, bpy.types.Collection): + for child in obj.objects: + toggle_off_single(child) + for child in obj.children: + toggle_off_single(child) + +def toggle_off(objs): + if type(objs) == list: + for obj in objs: + toggle_off_single(obj) + else: + toggle_off_single(objs) + +def toggle_off_all(): + for obj in bpy.data.objects: + toggle_off_single(obj) + +def toggle_on_all(): + for obj in bpy.data.objects: + toggle_on_single(obj) + +# Declare which collection to render comparison for +# Change this to the name of the collection you want to render +comparison_collection = "Sequences" + +# Iterate over children in the collection +comparison_objects = list(bpy.data.collections[comparison_collection].children) + list(bpy.data.collections[comparison_collection].objects) +orig_path = bpy.context.scene.render.filepath +for obj in comparison_objects: + toggle_off(comparison_objects) + toggle_on(obj) + bpy.context.scene.render.filepath = f"{orig_path}/{obj.name}/" +# bpy.ops.render.render(write_still=True) + bpy.ops.render.render(animation=True) + +bpy.context.scene.render.filepath = orig_path \ No newline at end of file