0
$\begingroup$

I want to import stl files using file browser (by using 'INVOKE_DEFAULT' on import stl operator). It seems that join() operator gets called before importing is finished. Does Blender import the objects in some kind of seperate thread to prevent a potential freeze?

I also tried macros but I'm getting the same result. join() operator gets called before the import is finished. I came across this method of window manager window_manager.fileselect_add() but couldn't get it to work. Sure, I can import the objects if that's finished, the user can join them but the client requires these two steps to be done using one single button.

import bpy


def main(context):
    for ob in context.scene.objects:
        print(ob)


class SimpleOperator(bpy.types.Operator):
    """Tooltip"""
    bl_idname = "object.simple_operator"
    bl_label = "Simple Object Operator"

    @classmethod
    def poll(cls, context):
        return context.active_object is not None

    def execute(self, context):
        main(context)
        return {'FINISHED'}
    
    def invoke(self,context,event):
        return context.window_manager.fileselect_add(self)


def register():
    bpy.utils.register_class(SimpleOperator)


def unregister():
    bpy.utils.unregister_class(SimpleOperator)


if __name__ == "__main__":
    register()

Q: Is there any way I can import and join the objects in one go?

$\endgroup$
3
  • 1
    $\begingroup$ Umm... can you just exactly tell what you want to achieve here. It is a bit confusing. $\endgroup$ Feb 21, 2021 at 9:01
  • $\begingroup$ @Aster17 I want a operator that imports stl files and join all imported models. $\endgroup$
    – Reigen
    Feb 21, 2021 at 9:35
  • 3
    $\begingroup$ This appears to be little more than pasting the simple operator template. Would say comment re joining finishing before import is akin to blender.stackexchange.com/questions/212179/… $\endgroup$
    – batFINGER
    Feb 21, 2021 at 12:22

1 Answer 1

2
$\begingroup$

Similar to Import STL via python, you can use the ImportHelper class if you'd like to import and modify objects. Have a look into the Operator File Import template that comes with Blender.

In order to join the objects, see @batFINGERs answer on: How to join objects with Python? How to import multiple objects using the file browser, you can find here: How to batch import Wavefront OBJ files?

# ##### BEGIN GPL LICENSE BLOCK #####
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2
#  of the License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software Foundation,
#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# <pep8 compliant>


bl_info = {
    "name": "Custom Batch Import Stl (.stl)",
    "author": "brockmann",
    "version": (0, 1, 0),
    "blender": (2, 80, 0),
    "location": "File > Import-Export",
    "description": "Import Stl files and join them",
    "warning": "",
    "wiki_url": "",
    "tracker_url": "",
    "category": "Import-Export"}


import bpy
import os

from bpy_extras.io_utils import ImportHelper
from bpy.types import PropertyGroup
from bpy.props import StringProperty, CollectionProperty


class ImportSomeData(bpy.types.Operator, ImportHelper):
    """Batch Import Stl files and join them"""
    bl_idname = "import_scene.custom_stls"
    bl_label = "Import multiple OBJ's"
    bl_options = {'PRESET', 'UNDO'}

    # ImportHelper mixin class uses this
    filename_ext = ".stl"

    filter_glob: StringProperty(
            default="*.stl",
            options={'HIDDEN'},
            )

    # Selected files
    files: CollectionProperty(type=PropertyGroup)

    def execute(self, context):

        # Get the folder
        folder = os.path.dirname(self.filepath)
        
        obs = []
        # Iterate through the selected files
        for i in self.files:

            # Generate full path to file
            path_to_file = (os.path.join(folder, i.name))
            bpy.ops.import_mesh.stl(filepath=path_to_file)
            # Append Object(s) to the list
            obs.append(context.selected_objects[:])
            # Print the imported object reference
            print ("Imported object:", context.object)
        
        # Join the objects based on: 
        # https://blender.stackexchange.com/a/133024/
        obs = [x for sublist in obs for x in sublist]
        c = {}
        c["object"] = c["active_object"] = context.object
        c["selected_objects"] = c["selected_editable_objects"] = obs
        bpy.ops.object.join(c)

        return {'FINISHED'}


# Only needed if you want to add into a dynamic menu
def menu_func_import(self, context):
    self.layout.operator(ImportSomeData.bl_idname, text="Stl Batch & Join (.stl)")


def register():
    bpy.utils.register_class(ImportSomeData)
    bpy.types.TOPBAR_MT_file_import.append(menu_func_import)


def unregister():
    bpy.utils.unregister_class(ImportSomeData)
    bpy.types.TOPBAR_MT_file_import.remove(menu_func_import)


if __name__ == "__main__":
    register()

    # test call
    bpy.ops.import_scene.custom_stls('INVOKE_DEFAULT')

Note: If you get paid for that and my code got your job done, please consider making a donation here: https://www.blender.org/foundation/donation-payment/ to make up for that.

$\endgroup$
4
  • 2
    $\begingroup$ Very altruistic of you Mr Brockman. May be interested in Updated version of multi file import helper blender.stackexchange.com/questions/30678/… obs.extend(sublist) ?` $\endgroup$
    – batFINGER
    Feb 21, 2021 at 14:04
  • $\begingroup$ I guess this won't happen anyway @batFINGER Nice, thanks for the link! I'll leave up any improvement to the OP... $\endgroup$
    – brockmann
    Feb 21, 2021 at 14:14
  • $\begingroup$ @brockmann That is just magic. Script works like charms. And As soon as i get paid i'll definitely make a donation. $\endgroup$
    – Reigen
    Feb 21, 2021 at 14:27
  • 2
    $\begingroup$ Cool, keep us posted @PavanBhadaja $\endgroup$
    – brockmann
    Feb 21, 2021 at 14:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .