Python bpy.props.EnumProperty() Examples

The following are 17 code examples of bpy.props.EnumProperty(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bpy.props , or try the search function .
Example #1
Source File: render_auto_save.py    From Fluid-Designer with GNU General Public License v3.0 7 votes vote down vote up
def register():
    bpy.types.Scene.save_after_render = BoolProperty(
                    name='Save after render',
                    default=True,
                    description='Automatically save rendered images into: //auto_save/')
    bpy.types.Scene.save_blend = BoolProperty(
		    name = 'with .blend',
                    default=True,
                    description='Also save .blend file into: //auto_save/')	
    bpy.types.Scene.auto_save_format = EnumProperty(
                    name='Auto Save File Format',
                    description='File Format for the auto saves.',
                    items={
                    ('PNG', 'png', 'Save as png'),
                    ('JPEG', 'jpg', 'Save as jpg'),
                    ('OPEN_EXR_MULTILAYER', 'exr', 'Save as multilayer exr')},
                    default='PNG')
    bpy.types.Scene.auto_save_subfolders = BoolProperty(
                    name='subfolder',
                    default=False,
                    description='Save into individual subfolders per blend name')
    bpy.app.handlers.render_post.append(auto_save_render)
    bpy.types.RENDER_PT_render.append(auto_save_UI) 
Example #2
Source File: nodes_terrain_analysis_reclassify.py    From BlenderGIS with GNU General Public License v3.0 6 votes vote down vote up
def register():
	for cls in classes:
		try:
			bpy.utils.register_class(cls)
		except ValueError as e:
			log.warning('{} is already registered, now unregister and retry... '.format(cls))
			bpy.utils.unregister_class(cls)
			bpy.utils.register_class(cls)
	#Create uilist collections
	bpy.types.Scene.uiListCollec = CollectionProperty(type=RECLASS_PG_color)
	bpy.types.Scene.uiListIndex = IntProperty() #used to store the index of the selected item in the uilist
	bpy.types.Scene.colorRampPreview = CollectionProperty(type=RECLASS_PG_color_preview)
	#Add handlers
	bpy.app.handlers.depsgraph_update_post.append(scene_update)
	#
	bpy.types.Scene.analysisMode = EnumProperty(
		name = "Mode",
		description = "Choose the type of analysis this material do",
		items = [('HEIGHT', 'Height', "Height analysis"),
		('SLOPE', 'Slope', "Slope analysis"),
		('ASPECT', 'Aspect', "Aspect analysis")],
		update = updateAnalysisMode
		) 
Example #3
Source File: property.py    From BlenderTools with GNU General Public License v2.0 6 votes vote down vote up
def get_filebrowser_display_type(is_image=False):
    """Gets enum property for specifying display type of file browser.
    If is_image argument is not passed or is False default display type is used.

    :param is_image: flag specifying if display type shall be image preview
    :type is_image: bool
    :return: enum property of display type for Blender file browser
    :rtype: bpy.types.EnumProperty
    """

    default_value = "FILE_IMGDISPLAY" if is_image else "FILE_DEFAULTDISPLAY"

    return EnumProperty(
        items=[
            ("FILE_DEFAULTDISPLAY", "", ""),
            ("FILE_SHORTDISPLAY", "", ""),
            ("FILE_LONGDISPLAY", "", ""),
            ("FILE_IMGDISPLAY", "", "")
        ],
        default=default_value,
        options={'HIDDEN'}
    ) 
Example #4
Source File: prefs.py    From BlenderGIS with GNU General Public License v3.0 5 votes vote down vote up
def getEnumItems(cls):
		'''Return a list of predefined crs usable to fill a bpy EnumProperty'''
		crsItems = []
		data = cls.getData()
		for srid, name in data.items():
			#put each item in a tuple (key, label, tooltip)
			crsItems.append( (srid, name, srid) )
		return crsItems


#################
# Collection of operators to manage predefinates CRS 
Example #5
Source File: muv_props.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def init_props(scene):
    scene.muv_props = MUV_Properties()
    scene.muv_uvbb_cp_size = FloatProperty(
        name="Size",
        description="Control Point Size",
        default=6.0,
        min=3.0,
        max=100.0)
    scene.muv_uvbb_cp_react_size = FloatProperty(
        name="React Size",
        description="Size event fired",
        default=10.0,
        min=3.0,
        max=100.0)
    scene.muv_uvbb_uniform_scaling = BoolProperty(
        name="Uniform Scaling",
        description="Enable Uniform Scaling",
        default=False)
    scene.muv_texproj_tex_magnitude = FloatProperty(
        name="Magnitude",
        description="Texture Magnitude.",
        default=0.5,
        min=0.0,
        max=100.0)
    scene.muv_texproj_tex_image = EnumProperty(
        name="Image",
        description="Texture Image.",
        items=get_loaded_texture_name)
    scene.muv_texproj_tex_transparency = FloatProperty(
        name="Transparency",
        description="Texture Transparency.",
        default=0.2,
        min=0.0,
        max=1.0) 
Example #6
Source File: ior_presets.py    From BlendLuxCore with GNU General Public License v3.0 5 votes vote down vote up
def get_sorted_list(cls, sort="name"):
        # Make a deep copy of the ior_values dict
        ior_values = copy.deepcopy(cls._ior_values)
        # Append a unique integer index to each tuple. The EnumProperty needs
        # this to determine a default item (index 0) when using a callback.
        # Failure to do so results in a random item becoming the default.
        ior_values[cls.default_key].append(0)
        index = 1
        for ior in ior_values:
            if ior != cls.default_key:
                ior_values[ior].append(index)
                index += 1
        # Convert the dict to a sorted list of tuples
        if sort == "value":
            index = 1
        else:
            index = 0
        preset_list = []
        for item in sorted(ior_values.items(),
                           key=lambda e: e[1][index]):
            text = "{} ({:f})".format(item[1][0], item[1][1])
            preset_list.append((item[0], text, text, item[1][2]))
        return preset_list 
Example #7
Source File: light_preview_list.py    From leomoon-lightstudio with GNU General Public License v3.0 5 votes vote down vote up
def register():
    from bpy.types import WindowManager
    from bpy.props import EnumProperty

    WindowManager.lls_tex_previews = EnumProperty(
            items=enum_previews_from_directory_items,
            get=preview_enum_get,
            set=preview_enum_set,
            )
    import bpy.utils.previews
    pcoll = bpy.utils.previews.new()
    pcoll.lls_tex_previews = ()
    pcoll.initiated = False
    pcoll.dir_update_time = os.path.getmtime(directory)

    preview_collections["main"] = pcoll 
Example #8
Source File: material.py    From blender2ogre with GNU Lesser General Public License v2.1 5 votes vote down vote up
def reset_rna(self, callback=None):
        bpy.types.Material.ogre_parent_material = EnumProperty(
            name="Script Inheritence",
            description='ogre parent material class',
            items=self.ENUM_ITEMS,
            #update=callback
        ) 
Example #9
Source File: ui.py    From coa_tools with GNU General Public License v3.0 5 votes vote down vote up
def enum_sprite_previews(self, context):
    """EnumProperty callback"""
    enum_items = []
    if context is None:
        return enum_items
    if self.coa_type == "MESH":

        # Get the preview collection (defined in register func).
        coa_pcoll = preview_collections["coa_thumbs"]
        
        #thumb_dir_path = bpy.utils.user_resource("DATAFILES","coa_thumbs")
        thumb_dir_path = os.path.join(context.user_preferences.filepaths.temporary_directory,"coa_thumbs")
        
        if os.path.exists(thumb_dir_path):
            # Scan the directory for png files
            image_paths = []
            for fn in os.listdir(thumb_dir_path):
                if fn.lower().endswith(".png") and self.name in fn:
                    image_paths.append(fn)      
            for i, name in enumerate(image_paths):
                if i < self.coa_tiles_x * self.coa_tiles_y:
                    filepath = os.path.join(thumb_dir_path, name)

                    if name in coa_pcoll:
                        thumb = coa_pcoll[name]
                    else:    
                        thumb = coa_pcoll.load(name, filepath, 'IMAGE')
                    enum_items.append((str(i), name, "", thumb.icon_id, i))
    elif self.coa_type == "SLOT":
        for i,slot in enumerate(self.coa_slot):
            if slot.mesh != None:
                img = slot.mesh.materials[0].texture_slots[0].texture.image
                icon = bpy.types.UILayout.icon(img)
                enum_items.append((str(i), slot.mesh.name, "", icon, i))
 
    return enum_items 
Example #10
Source File: mechanisms.py    From phobos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def register():
    """TODO Missing documentation"""
    from bpy.types import WindowManager
    from bpy.props import EnumProperty

    WindowManager.mechanismpreview = EnumProperty(
        items=getMechanismListForEnumProperty, name='Mechanism'
    )
    compileMechanismList() 
Example #11
Source File: models.py    From phobos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getCategoriesForEnumProperty(self, context):
    """Returns a list of categories for an EnumProperty.
    
    The categories are based on the ``categories`` variable in the current namespace.
    
    If there are no categories return ('-', '-', '-').

    Args:
      context: 

    Returns:
      list: available category in the model library.

    """
    if not categories:
        return [('-',) * 3]
    return sorted([(item,) * 3 for item in categories]) 
Example #12
Source File: models.py    From phobos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def register():
    """TODO Missing documentation"""
    from bpy.types import WindowManager
    from bpy.props import StringProperty, EnumProperty, BoolProperty

    WindowManager.modelpreview = EnumProperty(items=getModelListForEnumProperty, name='Model')
    WindowManager.category = EnumProperty(items=getCategoriesForEnumProperty, name='Category')
    compileModelList() 
Example #13
Source File: mechanisms.py    From phobos with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def compileMechanismList():
    """TODO Missing documentation"""
    from bpy.types import WindowManager
    from bpy.props import EnumProperty

    # DOCU missing some docstring

    global mechanismpreviewcollection

    log("Compiling mechanism list from local library...", "INFO")

    try:
        phobosconfig = bUtils.getPhobosConfigPath()
    except KeyError:
        log('Can not create mechanism preview. Phobos not registered.', 'DEBUG')
        return

    imagefolderpath = os.path.join(phobosconfig, 'images', 'mechanisms')
    if imagefolderpath == '' or not os.path.exists(imagefolderpath):
        log('Visual mechanism representations could not be found.')
        return

    # read in mechanism thumbnails
    mechanismpreviewcollection = bpy.utils.previews.new()
    enum_items = []
    defaultimagepath = os.path.join(imagefolderpath, 'undefined.png')
    defaultpreview = mechanismpreviewcollection.load('undefined', defaultimagepath, 'IMAGE')

    i = 1
    for mechanism in defs.definitions['submechanisms']:
        size = len(defs.definitions['submechanisms'][mechanism]['joints']['spanningtree'])
        imagepath = os.path.join(imagefolderpath, mechanism + '.png')
        if not (os.path.exists(imagepath) and os.path.isfile(imagepath)):
            log("No preview found, using default.", 'DEBUG')
            enum_items.append(
                (mechanism, mechanism + ' [{0}] '.format(size), "", defaultpreview.icon_id, i)
            )
        else:
            log("Adding mechanism preview: " + imagepath, 'DEBUG')
            preview = mechanismpreviewcollection.load(mechanism, imagepath, 'IMAGE')
            enum_items.append(
                (mechanism, mechanism + '[ {0}]'.format(size), "", preview.icon_id, i)
            )
        i += 1
    mechanismpreviewcollection.enum_items = enum_items

    # reregister the enumproperty to ensure new items are displayed
    WindowManager.mechanismpreview = EnumProperty(
        items=getMechanismListForEnumProperty, name='Mechanism'
    ) 
Example #14
Source File: models.py    From phobos with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def compileModelList():
    """TODO Missing documentation"""
    from bpy.props import EnumProperty
    from bpy.types import WindowManager

    # DOCU missing some docstring
    log("Compiling model list from local library...", "INFO")

    # clear old preview collections
    for previews in model_previews.values():
        bpy.utils.previews.remove(previews)
    model_previews.clear()
    model_data.clear()

    try:
        rootpath = bUtils.getPhobosPreferences().modelsfolder
    except KeyError:
        log('Can not create mechanism preview. Phobos not registered.', 'DEBUG')
        return

    if rootpath == '' or not os.path.exists(rootpath):
        log('Model library folder does not exist.')
        return

    # parse the model folder
    i = 0
    for category in os.listdir(rootpath):
        categorypath = os.path.join(rootpath, category)
        # skip all non folders
        if not os.path.isdir(categorypath):
            continue

        # initialise new dictionaries
        model_data[category] = {}
        newpreviewcollection = bpy.utils.previews.new()
        enum_items = []

        # parse category folder
        for modelname in os.listdir(categorypath):
            modelpath = os.path.join(categorypath, modelname)

            # check for valid blender savefile in the model folder
            if os.path.exists(os.path.join(modelpath, 'blender', modelname + '.blend')):
                model_data[category][modelname] = {'path': modelpath}

                # use existing thumbnail if available
                if os.path.exists(os.path.join(modelpath, 'thumbnails')):
                    previewpath = os.path.join(modelpath, 'thumbnails', modelname + '.png')
                    preview = newpreviewcollection.load(modelname, previewpath, 'IMAGE')
                # otherwise create one from the blend file
                else:
                    previewpath = os.path.join(modelpath, 'blender', modelname + '.blend')
                    preview = newpreviewcollection.load(modelname, previewpath, 'BLEND')
                log("Adding model to preview: " + previewpath, 'DEBUG')
                enum_items.append((modelname, modelname, "", preview.icon_id, i))
                i += 1
                categories.add(category)
        # save the category
        newpreviewcollection.enum_items = enum_items
        model_previews[category] = newpreviewcollection
        log("Finished parsing model folder. Imported {0} models.".format(i), 'INFO') 
Example #15
Source File: light_preview_list.py    From leomoon-lightstudio with GNU General Public License v3.0 4 votes vote down vote up
def enum_previews_from_directory_items(self, context):
    """EnumProperty callback"""
    enum_items = []

    if context is None:
        return enum_items

    wm = context.window_manager
    
    script_file = os.path.realpath(__file__)
    dir = os.path.dirname(script_file)
    directory=os.path.join(dir,"textures_real_lights"+_)

    # Get the preview collection (defined in register func).
    pcoll = preview_collections["main"]
    
    dir_up = os.path.getmtime(directory)
    if pcoll.initiated and dir_up <= pcoll.dir_update_time:
        return pcoll.tex_previews
    pcoll.dir_update_time = dir_up
    
    pcoll.clear()

    print("Scanning directory: %s" % directory)

    if directory and os.path.exists(directory):
        # Scan the directory for png files
        image_paths = []
        for fn in os.listdir(directory):
            if os.path.splitext(fn)[1] in (".tif", ".exr", ".hdr"):
                image_paths.append(fn)

        for i, name in enumerate(image_paths):
            # generates a thumbnail preview for a file.
            filepath = os.path.join(directory, name)
            thumb = pcoll.load(filepath, filepath, 'IMAGE', True)
            basename = os.path.splitext(name)[0]
            enum_items.append((name, basename, name, thumb.icon_id, i))

    pcoll.tex_previews = enum_items
    pcoll.initiated = True
    return pcoll.tex_previews


# We can store multiple preview collections here,
# however in this example we only store "main" 
Example #16
Source File: __init__.py    From Fluid-Designer with GNU General Public License v3.0 4 votes vote down vote up
def register():
    from bpy.utils import register_class
    for mod in _modules_loaded:
        for cls in mod.classes:
            register_class(cls)

    # space_userprefs.py
    from bpy.props import StringProperty, EnumProperty
    from bpy.types import WindowManager

    def addon_filter_items(self, context):
        import addon_utils

        items = [('All', "All", "All Add-ons"),
                 ('User', "User", "All Add-ons Installed by User"),
                 ('Enabled', "Enabled", "All Enabled Add-ons"),
                 ('Disabled', "Disabled", "All Disabled Add-ons"),
                 ]

        items_unique = set()

        for mod in addon_utils.modules(refresh=False):
            info = addon_utils.module_bl_info(mod)
            items_unique.add(info["category"])

        items.extend([(cat, cat, "") for cat in sorted(items_unique)])
        return items

    WindowManager.addon_search = StringProperty(
            name="Search",
            description="Search within the selected filter",
            options={'TEXTEDIT_UPDATE'},
            )
    WindowManager.addon_filter = EnumProperty(
            items=addon_filter_items,
            name="Category",
            description="Filter add-ons by category",
            )

    WindowManager.addon_support = EnumProperty(
            items=[('OFFICIAL', "Official", "Officially supported"),
                   ('COMMUNITY', "Community", "Maintained by community developers"),
                   ('TESTING', "Testing", "Newly contributed scripts (excluded from release builds)")
                   ],
            name="Support",
            description="Display support level",
            default={'OFFICIAL', 'COMMUNITY'},
            options={'ENUM_FLAG'},
            )
    # done... 
Example #17
Source File: __init__.py    From Fluid-Designer with GNU General Public License v3.0 4 votes vote down vote up
def register():
    bpy.utils.register_module(__name__)

    # space_userprefs.py
    from bpy.props import StringProperty, EnumProperty
    from bpy.types import WindowManager

    def addon_filter_items(self, context):
        import addon_utils

        items = [('All', "All", "All Add-ons"),
                 ('User', "User", "All Add-ons Installed by User"),
                 ('Enabled', "Enabled", "All Enabled Add-ons"),
                 ('Disabled', "Disabled", "All Disabled Add-ons"),
                 ]

        items_unique = set()

        for mod in addon_utils.modules(refresh=False):
            info = addon_utils.module_bl_info(mod)
            items_unique.add(info["category"])

        items.extend([(cat, cat, "") for cat in sorted(items_unique)])
        return items

    WindowManager.addon_search = StringProperty(
            name="Search",
            description="Search within the selected filter",
            options={'TEXTEDIT_UPDATE'},
            )
    WindowManager.addon_filter = EnumProperty(
            items=addon_filter_items,
            name="Category",
            description="Filter add-ons by category",
            )

    WindowManager.addon_support = EnumProperty(
            items=[('OFFICIAL', "Official", "Officially supported"),
                   ('COMMUNITY', "Community", "Maintained by community developers"),
                   ('TESTING', "Testing", "Newly contributed scripts (excluded from release builds)")
                   ],
            name="Support",
            description="Display support level",
            default={'OFFICIAL', 'COMMUNITY'},
            options={'ENUM_FLAG'},
            )
    # done...