id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
20,087
import bpy from bpy.types import Context import bpy from bpy.types import Context, Object The provided code snippet includes necessary dependencies for implementing the `show_ui_message_popup` function. Write a Python function `def show_ui_message_popup( message: str = "", title: str = "Sketcher Warning", icon: str = "INFO" )` to solve the following problem: Trigger a ui popup message NOTE: Perhaps better located in ui.py, but would currently require circular dependency with operators.py Here is the function: def show_ui_message_popup( message: str = "", title: str = "Sketcher Warning", icon: str = "INFO" ): """ Trigger a ui popup message NOTE: Perhaps better located in ui.py, but would currently require circular dependency with operators.py """ lines = message.split("\n") def draw(self, context: Context): layout = self.layout for line_str in lines: row = layout.row() row.label(text=line_str) bpy.context.window_manager.popup_menu(draw, title=title, icon=icon)
Trigger a ui popup message NOTE: Perhaps better located in ui.py, but would currently require circular dependency with operators.py
20,088
from typing import Tuple from bpy.types import Context, RegionView3D from mathutils import Vector from mathutils.geometry import intersect_line_plane from bpy_extras.view3d_utils import ( location_3d_to_region_2d, region_2d_to_location_3d, region_2d_to_vector_3d, region_2d_to_origin_3d, ) def get_picking_origin_dir(context: Context, coords: Vector) -> Tuple[Vector, Vector]: scene = context.scene region = context.region rv3d = context.region_data viewlayer = context.view_layer # get the ray from the viewport and mouse view_vector = region_2d_to_vector_3d(region, rv3d, coords) ray_origin = region_2d_to_origin_3d(region, rv3d, coords) return ray_origin, view_vector
null
20,089
from typing import Tuple from bpy.types import Context, RegionView3D from mathutils import Vector from mathutils.geometry import intersect_line_plane from bpy_extras.view3d_utils import ( location_3d_to_region_2d, region_2d_to_location_3d, region_2d_to_vector_3d, region_2d_to_origin_3d, ) def get_placement_pos(context: Context, coords: Vector) -> Vector: region = context.region rv3d = context.region_data view_vector = region_2d_to_vector_3d(region, rv3d, coords) return region_2d_to_location_3d(region, rv3d, coords, view_vector)
null
20,090
from typing import Tuple from bpy.types import Context, RegionView3D from mathutils import Vector from mathutils.geometry import intersect_line_plane from bpy_extras.view3d_utils import ( location_3d_to_region_2d, region_2d_to_location_3d, region_2d_to_vector_3d, region_2d_to_origin_3d, ) def get_picking_origin_end(context: Context, coords: Vector) -> Tuple[Vector, Vector]: scene = context.scene region = context.region rv3d = context.region_data viewlayer = context.view_layer # get the ray from the viewport and mouse view_vector = region_2d_to_vector_3d(region, rv3d, coords) ray_origin = region_2d_to_origin_3d(region, rv3d, coords) # view vector needs to be scaled and translated end_point = view_vector * context.space_data.clip_end + ray_origin return ray_origin, end_point The provided code snippet includes necessary dependencies for implementing the `get_pos_2d` function. Write a Python function `def get_pos_2d(context: Context, wp, coords: Vector) -> Vector` to solve the following problem: Returns the coordinates on the workplane the mouse points at Here is the function: def get_pos_2d(context: Context, wp, coords: Vector) -> Vector: """Returns the coordinates on the workplane the mouse points at""" origin, end_point = get_picking_origin_end(context, coords) pos = intersect_line_plane(origin, end_point, wp.p1.location, wp.normal) if pos is None: return None pos = wp.matrix_basis.inverted() @ pos return Vector(pos[:-1])
Returns the coordinates on the workplane the mouse points at
20,091
from typing import Tuple from bpy.types import Context, RegionView3D from mathutils import Vector from mathutils.geometry import intersect_line_plane from bpy_extras.view3d_utils import ( location_3d_to_region_2d, region_2d_to_location_3d, region_2d_to_vector_3d, region_2d_to_origin_3d, ) def get_2d_coords(context, pos: Vector) -> Vector: region = context.region rv3d = context.space_data.region_3d return location_3d_to_region_2d(region, rv3d, pos)
null
20,092
from typing import Tuple from bpy.types import Context, RegionView3D from mathutils import Vector from mathutils.geometry import intersect_line_plane from bpy_extras.view3d_utils import ( location_3d_to_region_2d, region_2d_to_location_3d, region_2d_to_vector_3d, region_2d_to_origin_3d, ) def get_scale_from_pos(co: Vector, rv3d: RegionView3D) -> Vector: if rv3d.view_perspective == "ORTHO": scale = rv3d.view_distance else: scale = (rv3d.perspective_matrix @ co.to_4d())[3] return scale
null
20,093
from typing import Tuple from bpy.types import Context, RegionView3D from mathutils import Vector from mathutils.geometry import intersect_line_plane from bpy_extras.view3d_utils import ( location_3d_to_region_2d, region_2d_to_location_3d, region_2d_to_vector_3d, region_2d_to_origin_3d, ) The provided code snippet includes necessary dependencies for implementing the `refresh` function. Write a Python function `def refresh(context: Context)` to solve the following problem: Update gizmos Here is the function: def refresh(context: Context): """Update gizmos""" if context.space_data and context.space_data.type == "VIEW_3D": context.space_data.show_gizmo = True if context.area and context.area.type == "VIEW_3D": context.area.tag_redraw()
Update gizmos
20,094
from typing import Tuple from bpy.types import Context, RegionView3D from mathutils import Vector from mathutils.geometry import intersect_line_plane from bpy_extras.view3d_utils import ( location_3d_to_region_2d, region_2d_to_location_3d, region_2d_to_vector_3d, region_2d_to_origin_3d, ) def update_cb(self, context: Context): if not context.space_data: return # update gizmos! if context.space_data.type == "VIEW_3D": context.space_data.show_gizmo = True
null
20,095
import re from typing import Any, Sequence, Union import bpy from bpy.types import Context, Object from mathutils import Vector def unique_attribute_setter(self, name: str, value: Any): def collection_from_element(self): """Get the collection containing the element""" path = self.path_from_id() match = re.match("(.*)\[\d*\]", path) parent = self.id_data try: coll_path = match.group(1) except AttributeError: raise TypeError("Property not element in a collection.") else: return parent.path_resolve(coll_path) def new_val(stem, nbr): """Simply for formatting""" return "{st}.{nbr:03d}".format(st=stem, nbr=nbr) property_func = getattr(self.__class__, name, None) if property_func and isinstance(property_func, property): # check if name is a property super(self.__class__, self).__setattr__(name, value) return if name not in self.unique_names: # don't handle self[name] = value return if value == getattr(self, name): # check for assignment of current value return coll = collection_from_element(self) if value not in coll: # if value is not in the collection, just assign self[name] = value return # see if value is already in a format like 'name.012' match = re.match(r"(.*)\.(\d{3,})", value) if match is None: stem, nbr = value, 1 else: stem, nbr = match.groups() # check for each value if in collection new_value = new_val(stem, nbr) while new_value in coll: nbr += 1 new_value = new_val(stem, nbr) self[name] = new_value
null
20,096
import re from typing import Any, Sequence, Union import bpy from bpy.types import Context, Object from mathutils import Vector import bpy from bpy.types import Context, Object The provided code snippet includes necessary dependencies for implementing the `add_new_empty` function. Write a Python function `def add_new_empty(context: Context, location: Vector, name="") -> Object` to solve the following problem: Places an empty at given location, useful for testing Here is the function: def add_new_empty(context: Context, location: Vector, name="") -> Object: """Places an empty at given location, useful for testing""" data = bpy.data empty = data.objects.new(name, None) empty.location = location context.collection.objects.link(empty) return empty
Places an empty at given location, useful for testing
20,097
import re from typing import Any, Sequence, Union import bpy from bpy.types import Context, Object from mathutils import Vector The provided code snippet includes necessary dependencies for implementing the `setprop` function. Write a Python function `def setprop(data, key, value)` to solve the following problem: Set an id prop without triggering it's update mehtod Here is the function: def setprop(data, key, value): """Set an id prop without triggering it's update mehtod""" prop = data.rna_type.properties[key] # Handle Enums which have to be set by the item's id rather than identifier if prop.type == "ENUM": value = prop.enum_items[value].value data[key] = value
Set an id prop without triggering it's update mehtod
20,098
import getpass import logging from tempfile import gettempdir from pathlib import Path from .register import get_name import logging def get_name(): return __package__.partition('.')[0] The provided code snippet includes necessary dependencies for implementing the `setup_logger` function. Write a Python function `def setup_logger(logger)` to solve the following problem: Configures a logger, this is intended to be run on the root logger Here is the function: def setup_logger(logger): """Configures a logger, this is intended to be run on the root logger""" # Clear handlers if logger.hasHandlers(): logger.handlers.clear() logger.setLevel(logging.DEBUG) formatter = logging.Formatter("%(name)s:{%(levelname)s}: %(message)s") stream_handler = logging.StreamHandler() stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) filepath = Path(gettempdir()) / (get_name() + f"-{getpass.getuser()}" + ".log") logger.info("Logging into: " + str(filepath)) # Add file handler try: file_handler = logging.FileHandler(filepath, mode="w") file_handler.setFormatter(formatter) logger.addHandler(file_handler) except: logger.warning(f"Cannot use logger file at: {filepath}")
Configures a logger, this is intended to be run on the root logger
20,099
import getpass import logging from tempfile import gettempdir from pathlib import Path from .register import get_name def get_prefs(): def update_logger(logger): from .preferences import get_prefs prefs = get_prefs() logger.setLevel(prefs.logging_level)
null
20,100
from collections import deque from math import sin, cos from typing import List from mathutils import Vector, Matrix from .. import global_data from .constants import FULL_TURN def draw_rect_2d(cx: float, cy: float, width: float, height: float): # NOTE: this currently returns xyz coordinates, might make sense to return 2d coords ox = cx - (width / 2) oy = cy - (height / 2) cz = 0 return ( (ox, oy, cz), (ox + width, oy, cz), (ox + width, oy + height, cz), (ox, oy + height, cz), ) def draw_rect_3d(origin: Vector, orientation: Vector, width: float) -> List[Vector]: mat_rot = global_data.Z_AXIS.rotation_difference(orientation).to_matrix() mat = Matrix.Translation(origin) @ mat_rot.to_4x4() coords = draw_rect_2d(0, 0, width, width) coords = [(mat @ Vector(co))[:] for co in coords] return coords
null
20,101
from collections import deque from math import sin, cos from typing import List from mathutils import Vector, Matrix from .. import global_data from .constants import FULL_TURN def draw_quad_3d(cx: float, cy: float, cz: float, width: float): half_width = width / 2 coords = ( (cx - half_width, cy - half_width, cz), (cx + half_width, cy - half_width, cz), (cx + half_width, cy + half_width, cz), (cx - half_width, cy + half_width, cz), ) indices = ((0, 1, 2), (2, 3, 0)) return coords, indices
null
20,102
from collections import deque from math import sin, cos from typing import List from mathutils import Vector, Matrix from .. import global_data from .constants import FULL_TURN def tris_from_quad_ids(id0: int, id1: int, id2: int, id3: int): return (id0, id1, id2), (id1, id2, id3) def draw_cube_3d(cx: float, cy: float, cz: float, width: float): half_width = width / 2 coords = [] for x in (cx - half_width, cx + half_width): for y in (cy - half_width, cy + half_width): for z in (cz - half_width, cz + half_width): coords.append((x, y, z)) # order: ((-x, -y, -z), (-x, -y, +z), (-x, +y, -z), ...) indices = ( *tris_from_quad_ids(0, 1, 2, 3), *tris_from_quad_ids(0, 1, 4, 5), *tris_from_quad_ids(1, 3, 5, 7), *tris_from_quad_ids(2, 3, 6, 7), *tris_from_quad_ids(0, 2, 4, 6), *tris_from_quad_ids(4, 5, 6, 7), ) return coords, indices
null
20,103
from collections import deque from math import sin, cos from typing import List from mathutils import Vector, Matrix from .. import global_data from .constants import FULL_TURN FULL_TURN = tau def coords_circle_2d(x: float, y: float, radius: float, segments: int): coords = [] m = (1.0 / (segments - 1)) * FULL_TURN for p in range(segments): p1 = x + cos(m * p) * radius p2 = y + sin(m * p) * radius coords.append((p1, p2)) return coords
null
20,104
from collections import deque from math import sin, cos from typing import List from mathutils import Vector, Matrix from .. import global_data from .constants import FULL_TURN FULL_TURN = tau def coords_arc_2d( x: float, y: float, radius: float, segments: int, angle=FULL_TURN, offset: float = 0.0, type="LINE_STRIP", ): coords = deque() segments = max(segments, 1) m = (1.0 / segments) * angle prev_point = None for p in range(segments + 1): co_x = x + cos(m * p + offset) * radius co_y = y + sin(m * p + offset) * radius if type == "LINES": if prev_point: coords.append(prev_point) coords.append((co_x, co_y)) prev_point = co_x, co_y else: coords.append((co_x, co_y)) return coords
null
20,105
from bpy.types import Context from ..solver import solve_system def solve_system(context, sketch=None): solver = Solver(context, sketch) return solver.solve() The provided code snippet includes necessary dependencies for implementing the `update_system_cb` function. Write a Python function `def update_system_cb(self, context: Context)` to solve the following problem: Update scene and re-run the solver, used as a property update callback Here is the function: def update_system_cb(self, context: Context): """Update scene and re-run the solver, used as a property update callback""" sketch = context.scene.sketcher.active_sketch solve_system(context, sketch=sketch)
Update scene and re-run the solver, used as a property update callback
20,106
import site import sys import importlib import subprocess from importlib import reload from .. import global_data The provided code snippet includes necessary dependencies for implementing the `check_module` function. Write a Python function `def check_module(package)` to solve the following problem: Note: Blender might be installed in a directory that needs admin rights and thus defaulting to a user installation. That path however might not be in sys.path Here is the function: def check_module(package): """ Note: Blender might be installed in a directory that needs admin rights and thus defaulting to a user installation. That path however might not be in sys.path """ p = site.USER_SITE if p not in sys.path: sys.path.append(p) try: importlib.import_module(package) except ModuleNotFoundError as e: raise e
Note: Blender might be installed in a directory that needs admin rights and thus defaulting to a user installation. That path however might not be in sys.path
20,107
import site import sys import importlib import subprocess from importlib import reload from .. import global_data def update_pip(): cmd = [global_data.PYPATH, "-m", "pip", "install", "--upgrade", "pip"] return not subprocess.call(cmd) def refresh_path(): """refresh path to packages found after install""" reload(site) def install_package(package: str, no_deps: bool = True): update_pip() base_call = [global_data.PYPATH, "-m", "pip", "install"] args = ["--upgrade"] if no_deps: args += ["--no-deps"] cmd = base_call + args + package.split(" ") ret_val = subprocess.call(cmd) refresh_path() return ret_val == 0
null
20,108
import site import sys import importlib import subprocess from importlib import reload from .. import global_data def install_pip(): """Subprocess call ensurepip module""" cmd = [global_data.PYPATH, "-m", "ensurepip", "--upgrade"] return not subprocess.call(cmd) def ensure_pip(): if subprocess.call([global_data.PYPATH, "-m", "pip", "--version"]): return install_pip() return True
null
20,109
import site import sys import importlib import subprocess from importlib import reload from .. import global_data def show_package_info(package: str): try: subprocess.call([global_data.PYPATH, "-m", "pip", "show", package]) except Exception as e: print(e) pass
null
20,110
import logging from bpy.props import EnumProperty from bpy.types import Context from .. import global_data from ..utilities.data_handling import entities_3d logger = logging.getLogger(__name__) def entities_3d(context: Context) -> Generator[SlvsGenericEntity, None, None]: for entity in context.scene.sketcher.entities.all: if hasattr(entity, "sketch"): continue yield entity def select_all(context: Context): sketch = context.scene.sketcher.active_sketch if sketch: logger.debug( f"Selecting all sketcher entities in sketch : {sketch.name} (slvs_index: {sketch.slvs_index})" ) generator = sketch.sketch_entities(context) else: logger.debug(f"Selecting all sketcher entities") generator = entities_3d(context) for e in generator: if e.selected: continue if not e.is_selectable(context): continue e.selected = True
null
20,111
import logging from bpy.props import EnumProperty from bpy.types import Context from .. import global_data from ..utilities.data_handling import entities_3d logger = logging.getLogger(__name__) def deselect_all(context: Context): logger.debug("Deselecting all sketcher entities") global_data.selected.clear()
null
20,112
import bpy from .register import get_name def get_prefs(): return bpy.context.preferences.addons[get_name()].preferences import bpy from bpy.types import Context, Object def get_scale(): return bpy.context.preferences.system.ui_scale * get_prefs().entity_scale
null
20,113
from enum import Enum from typing import Callable, Tuple from mathutils.geometry import ( intersect_line_line_2d as intersect_segment_segment_2d, intersect_line_sphere_2d as intersect_segment_sphere_2d, intersect_sphere_sphere_2d, ) from .geometry import intersect_line_line_2d, intersect_line_sphere_2d from ..model.base_entity import SlvsGenericEntity from .data_handling import to_list class ElementTypes(str, Enum): Line = "LINE" Sphere = "Sphere" def _get_offset_line(line, offset): normal = line.normal() offset_vec = normal * offset return (line.p1.co + offset_vec, line.p2.co + offset_vec) def _get_offset_sphere(arc, offset): """Return sphere_co and sphere_radius of offset sphere""" return arc.ct.co, arc.radius + offset class SlvsGenericEntity: def entity_name_getter(self): return self.get("name", str(self)) def entity_name_setter(self, new_name): self["name"] = new_name slvs_index: IntProperty(name="Global Index", default=-1) name: StringProperty( name="Name", get=entity_name_getter, set=entity_name_setter, options={"SKIP_SAVE"}, ) fixed: BoolProperty(name="Fixed", update=update_system_cb) visible: BoolProperty(name="Visible", default=True, update=update_cb) origin: BoolProperty(name="Origin") construction: BoolProperty(name="Construction") props = () dirty: BoolProperty(name="Needs Update", default=True, options={"SKIP_SAVE"}) def type(cls) -> str: return cls.__name__ def is_dirty(self) -> bool: if self.dirty: return True if not hasattr(self, "dependencies"): return False deps = self.dependencies() for e in deps: # NOTE: might has to ckech through deps recursively -> e.is_dirty if e.dirty: return True return False def is_dirty(self, value: bool): self.dirty = value def _shader(self): if self.is_point(): return Shaders.uniform_color_3d() return Shaders.uniform_color_line_3d() def _id_shader(self): if self.is_point(): return Shaders.id_shader_3d() return Shaders.id_line_3d() def point_size(self): return 5 * preferences.get_scale() def point_size_select(self): return 20 * preferences.get_scale() def line_width(self): scale = preferences.get_scale() if self.construction: return 1.5 * scale return 2 * scale def line_width_select(self): return 4 * preferences.get_scale() def __str__(self): _, local_index = breakdown_index(self.slvs_index) return "{}({})".format(self.__class__.__name__, str(local_index)) def py_data(self): return global_data.entities[self.slvs_index] def py_data(self, handle): global_data.entities[self.slvs_index] = handle # NOTE: It's not possible to store python runtime data on an instance of a PropertyGroup, # workaround this by saving python objects in a global list def _batch(self): index = self.slvs_index if index not in global_data.batches: return None return global_data.batches[index] def _batch(self, value): global_data.batches[self.slvs_index] = value # NOTE: hover and select could be replaced by actual props with getter and setter funcs # selected: BoolProperty(name="Selected") def hover(self): return global_data.hover == self.slvs_index def hover(self, value): if value: global_data.hover = self.slvs_index else: global_data.hover = -1 def selected(self): return self.slvs_index in global_data.selected def selected(self, value): slvs_index = self.slvs_index list = global_data.selected if slvs_index in list: i = list.index(slvs_index) if not value: list.pop(i) elif value: list.append(slvs_index) def is_active(self, active_sketch): if hasattr(self, "sketch"): return self.sketch == active_sketch else: return not active_sketch def is_selectable(self, context: Context): if not self.is_visible(context): return False if preferences.use_experimental("all_entities_selectable", False): return True active_sketch = context.scene.sketcher.active_sketch if active_sketch and hasattr(self, "sketch"): # Allow to select entities that share the active sketch's wp return active_sketch.wp == self.sketch.wp return self.is_active(active_sketch) def is_highlight(self): return self.hover or self in global_data.highlight_entities def color(self, context: Context): prefs = get_prefs() ts = prefs.theme_settings active = self.is_active(context.scene.sketcher.active_sketch) highlight = self.is_highlight() fixed = self.fixed origin = self.origin if not active: if highlight: return ts.entity.highlight if self.selected: return ts.entity.inactive_selected return ts.entity.inactive elif self.selected: if highlight: return ts.entity.selected_highlight return ts.entity.selected elif highlight: return ts.entity.highlight if fixed and not origin: return ts.entity.fixed return ts.entity.default def restore_opengl_defaults(): gpu.state.line_width_set(1) gpu.state.point_size_set(1) gpu.state.blend_set("NONE") def is_visible(self, context: Context) -> bool: if self.origin: return context.scene.sketcher.show_origin if hasattr(self, "sketch"): return self.sketch.is_visible(context) and self.visible return self.visible def is_dashed(self): return False def draw(self, context): if not self.is_visible(context): return None batch = self._batch if not batch: return shader = self._shader shader.bind() gpu.state.blend_set("ALPHA") gpu.state.point_size_set(self.point_size) col = self.color(context) shader.uniform_float("color", col) if not self.is_point(): shader.uniform_bool("dashed", (self.is_dashed(),)) shader.uniform_float("dash_width", 0.05) shader.uniform_float("dash_factor", 0.3) gpu.state.line_width_set(self.line_width) batch.draw(shader) gpu.shader.unbind() self.restore_opengl_defaults() def draw_id(self, context): # Note: Design Question, should it be possible to select elements that are not active?! # e.g. to activate a sketch # maybe it should be dynamically defined what is selectable (points only, lines only, ...) batch = self._batch if not batch: return shader = self._id_shader shader.bind() gpu.state.point_size_set(self.point_size_select) shader.uniform_float("color", (*index_to_rgb(self.slvs_index), 1.0)) if not self.is_point(): # viewport = [context.area.width, context.area.height] # shader.uniform_float("Viewport", viewport) shader.uniform_bool("dashed", (False,)) gpu.state.line_width_set(self.line_width_select) batch.draw(shader) gpu.shader.unbind() self.restore_opengl_defaults() def create_slvs_data(self, solvesys): """Create a solvespace entity from parameters""" raise NotImplementedError def update_from_slvs(self, solvesys): """Update parameters from the solvespace entity""" pass def update_pointers(self, index_old, index_new): def _update(name): prop = getattr(self, name) if prop == index_old: logger.debug( "Update reference {} of {} to {}: ".format(name, self, index_new) ) setattr(self, name, index_new) for prop_name in dir(self): if not prop_name.endswith("_i"): continue _update(prop_name) if hasattr(self, "target_object") and self.target_object: ob = self.target_object if ob.sketch_index == index_old: ob.sketch_index = index_new def connection_points(self): return [] def dependencies(self) -> List["SlvsGenericEntity"]: return [] def draw_props(self, layout): is_experimental = preferences.is_experimental() # Header layout.prop(self, "name", text="") # Info block layout.separator() layout.label(text="Type: " + type(self).__name__) layout.label(text="Is Origin: " + str(self.origin)) if is_experimental: sub = layout.column() sub.scale_y = 0.8 sub.label(text="Index: " + str(self.slvs_index)) sub.label(text="Dependencies:") for e in self.dependencies(): sub.label(text=str(e)) # General props layout.separator() layout.prop(self, "visible") layout.prop(self, "fixed") layout.prop(self, "construction") # Specific prop layout.separator() sub = layout.column() # Delete layout.separator() layout.operator(Operators.DeleteEntity, icon="X").index = self.slvs_index return sub def tag_update(self, _context=None): # context argument ignored if not self.is_dirty: self.is_dirty = True def new(self, context: Context, **kwargs): """Create new entity based on this instance""" raise NotImplementedError def is_3d(cls): return True def is_2d(cls): return False def is_point(cls): return False def is_path(cls): return False def is_line(cls): return False def is_curve(cls): return False def is_closed(cls): return False def is_segment(cls): return False def is_sketch(cls): return False def get_offset_elements( entity: SlvsGenericEntity, offset: float ) -> Tuple[ElementTypes, Callable]: t = ElementTypes.Line if entity.type == "SlvsLine2D" else ElementTypes.Sphere func = _get_offset_sphere if t == ElementTypes.Sphere else _get_offset_line return (t, func(entity, offset))
null
20,114
from enum import Enum from typing import Callable, Tuple from mathutils.geometry import ( intersect_line_line_2d as intersect_segment_segment_2d, intersect_line_sphere_2d as intersect_segment_sphere_2d, intersect_sphere_sphere_2d, ) from .geometry import intersect_line_line_2d, intersect_line_sphere_2d from ..model.base_entity import SlvsGenericEntity from .data_handling import to_list def _get_intersection_func(type_a, type_b, segment=False): if all([t == ElementTypes.Line for t in (type_a, type_b)]): return intersect_line_line_2d if not segment else intersect_segment_segment_2d if all([t == ElementTypes.Sphere for t in (type_a, type_b)]): return intersect_sphere_sphere_2d return intersect_line_sphere_2d if not segment else intersect_segment_sphere_2d def _order_intersection_args(arg1, arg2): if arg1[0] == ElementTypes.Sphere and arg2[0] == ElementTypes.Line: return arg2, arg1 return arg1, arg2 def to_list(value): """Ensure value is of type list""" if value is None: return [] if type(value) in (list, tuple): return list(value) return [ value, ] The provided code snippet includes necessary dependencies for implementing the `get_intersections` function. Write a Python function `def get_intersections(*element_list, segment=False)` to solve the following problem: Find all intersections between all combinations of elements, (type, element) Here is the function: def get_intersections(*element_list, segment=False): """Find all intersections between all combinations of elements, (type, element)""" intersections = [] lenght = len(element_list) for i, elem_a in enumerate(element_list): if i + 1 == lenght: break for elem_b in element_list[i + 1 :]: a, b = _order_intersection_args(elem_a, elem_b) func = _get_intersection_func(a[0], b[0], segment=segment) retval = to_list(func(*a[1], *b[1])) for intr in retval: if not intr: continue intersections.append(intr) return intersections
Find all intersections between all combinations of elements, (type, element)
20,115
def index_to_rgb(i: int): r = (i & int("0x000000FF", 16)) / 255 g = ((i & int("0x0000FF00", 16)) >> 8) / 255 b = ((i & int("0x00FF0000", 16)) >> 16) / 255 return r, g, b
null
20,116
def rgb_to_index(r: int, g: int, b: int) -> int: i = int(r * 255 + g * 255 * 256 + b * 255 * 256 * 256) return i
null
20,117
import os import sys import importlib from typing import List from traceback import print_exc The provided code snippet includes necessary dependencies for implementing the `cleanse_modules` function. Write a Python function `def cleanse_modules(parent_module_name)` to solve the following problem: search for your plugin modules in blender python sys.modules and remove them Here is the function: def cleanse_modules(parent_module_name): """search for your plugin modules in blender python sys.modules and remove them""" for module_name in list(sys.modules.keys()): if module_name.startswith(parent_module_name): del sys.modules[module_name]
search for your plugin modules in blender python sys.modules and remove them
20,118
import os import sys import importlib from typing import List from traceback import print_exc def module_register_factory(parent_module_name: str, module_names: List[str]): modules = [ importlib.import_module(f"{parent_module_name}.{name}") for name in module_names ] def register(): for m in modules: try: m.register() except Exception: print_exc() def unregister(): for m in reversed(modules): try: m.unregister() except Exception: print_exc() return register, unregister
null
20,119
import math from statistics import mean from typing import Tuple import mathutils from mathutils import Vector def get_face_orientation(mesh, face): # returns quaternion describing the face orientation in objectspace normal = mathutils.geometry.normal([mesh.vertices[i].co for i in face.vertices]) return normal.to_track_quat("Z", "X")
null
20,120
import math from statistics import mean from typing import Tuple import mathutils from mathutils import Vector The provided code snippet includes necessary dependencies for implementing the `get_face_midpoint` function. Write a Python function `def get_face_midpoint(quat, ob, face)` to solve the following problem: Average distance from origin to face vertices. Here is the function: def get_face_midpoint(quat, ob, face): """Average distance from origin to face vertices.""" mesh = ob.data coords = [mesh.vertices[i].co.copy() for i in face.vertices] quat_inv = quat.inverted() for v in coords: v.rotate(quat_inv) dist = mean([co[2] for co in coords]) # offset origin along normal by average distance pos = Vector((0, 0, dist)) pos.rotate(quat) return ob.matrix_world @ pos
Average distance from origin to face vertices.
20,121
import math from statistics import mean from typing import Tuple import mathutils from mathutils import Vector def nearest_point_line_line(p1: Vector, d1: Vector, p2: Vector, d2: Vector) -> Vector: n = d1.cross(d2) n2 = d2.cross(n) return p1 + ((p2 - p1).dot(n2) / d1.dot(n2)) * d1
null
20,122
import shutil import sys import logging from os import path import bpy from .register import get_path logger = logging.getLogger(__name__) import bpy from bpy.types import Context, Object def get_path(): def ensure_addon_presets(force_write=False): scripts_folder = bpy.utils.user_resource("SCRIPTS") presets_dir = path.join(scripts_folder, "presets", "bgs") is_existing = True if not path.isdir(presets_dir): is_existing = False if force_write or not is_existing: bundled_presets = path.join(get_path(), "resources", "presets") kwargs = {} if sys.version_info >= (3, 8): kwargs = {"dirs_exist_ok": True} shutil.copytree(bundled_presets, presets_dir, **kwargs) logger.info("Copy addon presets to: " + presets_dir)
null
20,123
def set_handles(point): point.handle_left_type = "FREE" point.handle_right_type = "FREE"
null
20,124
from collections import deque from typing import Generator, Deque, List, Sequence from bpy.types import Scene, Context from ..model.types import SlvsGenericEntity, SlvsSketch, GenericConstraint def get_flat_deps(entity: SlvsGenericEntity): """Return flattened list of entities given entity depends on""" list = [] def walker(entity, is_root=False): if entity in list: return if not is_root: list.append(entity) if not hasattr(entity, "dependencies"): return for e in entity.dependencies(): if e in list: continue walker(e) walker(entity, is_root=True) return list The provided code snippet includes necessary dependencies for implementing the `get_collective_dependencies` function. Write a Python function `def get_collective_dependencies( entities: Sequence[SlvsGenericEntity], ) -> List[SlvsGenericEntity]` to solve the following problem: Returns a list of entities along with their dependencies Here is the function: def get_collective_dependencies( entities: Sequence[SlvsGenericEntity], ) -> List[SlvsGenericEntity]: """Returns a list of entities along with their dependencies""" deps = entities for entity in entities: for dep in get_flat_deps(entity): if dep in deps: continue deps.append(dep) return deps
Returns a list of entities along with their dependencies
20,125
from collections import deque from typing import Generator, Deque, List, Sequence from bpy.types import Scene, Context from ..model.types import SlvsGenericEntity, SlvsSketch, GenericConstraint def get_scene_constraints(scene: Scene): return scene.sketcher.constraints.all
null
20,126
from collections import deque from typing import Generator, Deque, List, Sequence from bpy.types import Scene, Context from ..model.types import SlvsGenericEntity, SlvsSketch, GenericConstraint def _is_referenced_by_constraint(entity, context): for c in context.scene.sketcher.constraints.all: if entity in c.dependencies(): return True return False def is_entity_dependency(entity: SlvsGenericEntity, context: Context) -> bool: """Check if entity is a dependency of another entity""" deps = get_entity_deps(entity, context) try: next(deps) except StopIteration: return False return True The provided code snippet includes necessary dependencies for implementing the `is_entity_referenced` function. Write a Python function `def is_entity_referenced(entity: SlvsGenericEntity, context: Context) -> bool` to solve the following problem: Checks if the entity is referenced from anywhere Here is the function: def is_entity_referenced(entity: SlvsGenericEntity, context: Context) -> bool: """Checks if the entity is referenced from anywhere""" if is_entity_dependency(entity, context): return True if _is_referenced_by_constraint(entity, context): return True return False
Checks if the entity is referenced from anywhere
20,127
from collections import deque from typing import Generator, Deque, List, Sequence from bpy.types import Scene, Context from ..model.types import SlvsGenericEntity, SlvsSketch, GenericConstraint def get_scene_entities(scene: Scene): return scene.sketcher.entities.all def get_sketch_deps_indicies(sketch: SlvsSketch, context: Context): deps = deque() for entity in get_scene_entities(context.scene): if not hasattr(entity, "sketch_i"): continue if sketch.slvs_index != entity.sketch.slvs_index: continue deps.append(entity.slvs_index) return deps
null
20,128
from collections import deque from typing import Generator, Deque, List, Sequence from bpy.types import Scene, Context from ..model.types import SlvsGenericEntity, SlvsSketch, GenericConstraint def get_constraint_local_indices( entity: SlvsGenericEntity, context: Context ) -> Deque[int]: constraints = context.scene.sketcher.constraints ret_list = deque() for data_coll in constraints.get_lists(): indices = deque() for c in data_coll: if entity in c.dependencies(): indices.append(constraints.get_index(c)) ret_list.append((data_coll, indices)) return ret_list
null
20,129
from collections import deque from typing import Generator, Deque, List, Sequence from bpy.types import Scene, Context from ..model.types import SlvsGenericEntity, SlvsSketch, GenericConstraint The provided code snippet includes necessary dependencies for implementing the `get_scoped_constraints` function. Write a Python function `def get_scoped_constraints( context: Context, entities: List[SlvsGenericEntity] ) -> List[GenericConstraint]` to solve the following problem: Return a list of constraints that are in the scope of a set of entities Here is the function: def get_scoped_constraints( context: Context, entities: List[SlvsGenericEntity] ) -> List[GenericConstraint]: """Return a list of constraints that are in the scope of a set of entities""" constraints = [] for constraint in context.scene.sketcher.constraints.all: if not all([e in entities for e in constraint.entities()]): continue constraints.append(constraint) return constraints
Return a list of constraints that are in the scope of a set of entities
20,130
from ..constants import Operators, numeric_events, unit_key_types from bpy.types import KeyMapItem, Context, Event from typing import List def _get_key_hint(kmi: KeyMapItem) -> List[str]: """ Returns a string representing the keymap item in the form: "ctrl + alt + shift + key" """ modifiers = {"ctrl": "Ctrl", "alt": "Alt", "shift": "Shift"} elements = [] for m in modifiers.keys(): if not getattr(kmi, m): continue elements.append(modifiers[m]) elements.append(kmi.type) return " + ".join(elements) def _get_matching_kmi( context: Context, id_name: str, filter_func=None ) -> List[KeyMapItem]: """ Returns a list of keymap items that act on given operator. Optionally filtered by filter_func. """ wm = context.window_manager kc = wm.keyconfigs.addon km_items = [] for km in kc.keymaps: for kmi in km.keymap_items: if not kmi.idname == id_name: continue if kmi.type in ("LEFTMOUSE", "MIDDLEMOUSE", "RIGHTMOUSE"): continue if kmi.type in numeric_events: continue if filter_func and not filter_func(kmi): continue km_items.append(kmi) return km_items class Operators(str, Enum): InvokeTool = "view3d.invoke_tool" Test = "view3d.stateop_test" The provided code snippet includes necessary dependencies for implementing the `get_key_map_desc` function. Write a Python function `def get_key_map_desc(context: Context, id_name: str) -> str` to solve the following problem: Returns a list of shortcut hints to operator with given idname. Looks through keymaps in addon keyconfig. Here is the function: def get_key_map_desc(context: Context, id_name: str) -> str: """ Returns a list of shortcut hints to operator with given idname. Looks through keymaps in addon keyconfig. """ km_items = _get_matching_kmi(context, id_name) km_items.extend( _get_matching_kmi( context, Operators.InvokeTool, filter_func=lambda kmi: kmi.properties["operator"] == id_name, ) ) if not len(km_items): return "" hints = [] for kmi in km_items: hint = _get_key_hint(kmi) if hint in hints: continue hints.append(hint) return "({})".format(", ".join(hints))
Returns a list of shortcut hints to operator with given idname. Looks through keymaps in addon keyconfig.
20,131
from ..constants import Operators, numeric_events, unit_key_types from bpy.types import KeyMapItem, Context, Event from typing import List def _tool_numeric_invoke_km(operator: str): km = [] for event in numeric_events: km.append( ( operator, {"type": event, "value": "PRESS"}, None, ) ) return km def operator_access(operator: str): return ( *_tool_numeric_invoke_km(operator), ( operator, {"type": "LEFTMOUSE", "value": "PRESS", "any": True}, {"properties": [("wait_for_input", False)]}, ), )
null
20,132
from ..constants import Operators, numeric_events, unit_key_types from bpy.types import KeyMapItem, Context, Event from typing import List class Operators(str, Enum): InvokeTool = "view3d.invoke_tool" Test = "view3d.stateop_test" def tool_invoke_kmi(button: str, tool: str, operator: str): return ( Operators.InvokeTool, {"type": button, "value": "PRESS"}, {"properties": [("tool_name", tool), ("operator", operator)]}, )
null
20,133
from ..constants import Operators, numeric_events, unit_key_types from bpy.types import KeyMapItem, Context, Event from typing import List numeric_events = ( "ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "PERIOD", "NUMPAD_0", "NUMPAD_1", "NUMPAD_2", "NUMPAD_3", "NUMPAD_4", "NUMPAD_5", "NUMPAD_6", "NUMPAD_7", "NUMPAD_8", "NUMPAD_9", "NUMPAD_PERIOD", "MINUS", "NUMPAD_MINUS", ) def is_numeric_input(event: Event): return event.type in (*numeric_events, "BACK_SPACE")
null
20,134
from ..constants import Operators, numeric_events, unit_key_types from bpy.types import KeyMapItem, Context, Event from typing import List unit_key_types = ( "M", "K", "D", "C", "U", "A", "H", "I", "L", "N", "F", "T", "Y", "U", "R", "E", "G", ) def is_unit_input(event: Event): return event.type in unit_key_types
null
20,135
from ..constants import Operators, numeric_events, unit_key_types from bpy.types import KeyMapItem, Context, Event from typing import List def get_unit_value(event: Event): type = event.type return type.lower()
null
20,136
from ..constants import Operators, numeric_events, unit_key_types from bpy.types import KeyMapItem, Context, Event from typing import List def get_value_from_event(event: Event): type = event.type if type in ("ZERO", "NUMPAD_0"): return "0" if type in ("ONE", "NUMPAD_1"): return "1" if type in ("TWO", "NUMPAD_2"): return "2" if type in ("THREE", "NUMPAD_3"): return "3" if type in ("FOUR", "NUMPAD_4"): return "4" if type in ("FIVE", "NUMPAD_5"): return "5" if type in ("SIX", "NUMPAD_6"): return "6" if type in ("SEVEN", "NUMPAD_7"): return "7" if type in ("EIGHT", "NUMPAD_8"): return "8" if type in ("NINE", "NUMPAD_9"): return "9" if type in ("PERIOD", "NUMPAD_PERIOD"): return "."
null
20,137
import bpy import bmesh from bpy.types import Object from mathutils.bvhtree import BVHTree def to_list(val): if val is None: return [] if type(val) in (list, tuple): return list(val) return [ val, ]
null
20,138
import bpy import bmesh from bpy.types import Object from mathutils.bvhtree import BVHTree def get_pointer_get_set(index: int): @property def func(self): return self.get_state_pointer(index=index) @func.setter def setter(self, value): self.set_state_pointer(value, index=index) return func, setter
null
20,139
import bpy import bmesh from bpy.types import Object from mathutils.bvhtree import BVHTree class StatefulOperatorLogic: """Base class which implements the behaviour logic""" state_index: IntProperty(options={"HIDDEN", "SKIP_SAVE"}) wait_for_input: BoolProperty(options={"HIDDEN", "SKIP_SAVE"}, default=True) continuous_draw: BoolProperty(name="Continuous Draw", default=False) executed = False # Stores the returned value of state_func the first time it runs per state state_init_coords = None _state_data = {} _last_coords = Vector((0, 0)) _numeric_input = {} _undo = False def get_property(self, index: Optional[int] = None): if index is None: index = self.state_index state = self.get_states()[index] if state.property is None: return None if callable(state.property): props = state.property(self, index) elif state.property: if callable(getattr(self, state.property)): props = getattr(self, state.property)(index) else: props = state.property elif hasattr(self, "state_property") and callable(self.state_property): props = self.state_property(index) else: return None retval = to_list(props) return retval def get_states_definition(cls): if callable(cls.states): return cls.states() return cls.states def get_states(self): if callable(self.states): return self.states(operator=self) return self.states def state(self): return self.get_states()[self.state_index] def _index_from_state(self, state): return [e.name for e in self.get_states()].index(state) def state(self, state): self.state_index = self._index_from_state(state) def set_state(self, context: Context, index: int): self.state_index = index self.init_numeric(False) self.set_status_text(context) def next_state(self, context: Context): self._undo = False self.state_init_coords = None i = self.state_index if (i + 1) >= len(self.get_states()): return False self.set_state(context, i + 1) return True def set_status_text(self, context: Context): # Setup state state = self.state desc = ( state.description(self, state) if callable(state.description) else state.description ) msg = state_desc(state.name, desc, state.types) if self.state_data.get("is_numeric_edit", False): index = self._substate_index prop = self._stateprop type = prop.type array_length = prop.array_length if prop.array_length else 1 if type == "FLOAT": input = [0.0] * array_length for key, val in self._numeric_input.items(): input[key] = val input[index] = "*" + str(input[index]) input = str(input).replace('"', "").replace("'", "") elif type == "INT": input = self.numeric_input msg += " {}: {}".format(prop.subtype, input) context.workspace.status_text_set(msg) def check_numeric(self): """Check if the state supports numeric edit""" # TODO: Allow to define custom logic state = self.state props = self.get_property() # Disable for multi props if not props or len(props) > 1: return False prop_name = props[0] if not prop_name: return False prop = self.properties.rna_type.properties.get(prop_name) if not prop: return False if prop.type not in ("INT", "FLOAT"): return False return True def init_numeric(self, is_numeric): self._numeric_input = {} self._substate_index = 0 ok = False if is_numeric: ok = self.check_numeric() # TODO: not when iterating substates self.state_data["is_numeric_edit"] = is_numeric and ok self.init_substate() return ok def init_substate(self): # Reset self._substate_count = None self._stateprop = None props = self.get_property() if not props: return if not props[0]: return prop_name = props[0] prop = self.properties.rna_type.properties.get(prop_name) if not prop: return self._substate_count = prop.array_length self._stateprop = prop def iterate_substate(self): i = self._substate_index if i + 1 >= self._substate_count: i = 0 else: i += 1 self._substate_index = i def numeric_input(self): return self._numeric_input.get(self._substate_index, "") def numeric_input(self, value): self._numeric_input[self._substate_index] = value def check_event(self, event): state = self.state is_confirm_button = event.type in ("LEFTMOUSE", "RET", "NUMPAD_ENTER") if is_confirm_button and event.value == "PRESS": return True if self.state_index == 0 and not self.wait_for_input: # Trigger the first state return not self.state_data.get("is_numeric_edit", False) if state.no_event: return True return False def evaluate_numeric_event(self, event: Event): type = event.type if type == "BACK_SPACE": input = self.numeric_input if len(input): self.numeric_input = input[:-1] return if type in ("MINUS", "NUMPAD_MINUS"): input = self.numeric_input if input.startswith("-"): input = input[1:] else: input = "-" + input self.numeric_input = input return if is_unit_input(event): self.numeric_input += get_unit_value(event) return value = get_value_from_event(event) self.numeric_input += self.validate_numeric_input(value) def validate_numeric_input(self, value): """Check if existing input is valid after appending value""" num_input = self.numeric_input separators = (".", ",") if value in separators: if any([char in num_input for char in separators]): return "" if not len(num_input) or not num_input[-1].isdigit(): return "0." return value def is_in_previous_states(self, entity): i = self.state_index - 1 while True: if i < 0: break state = self.get_states()[i] if state.pointer and entity == getattr(self, state.pointer): return True i -= 1 return False def prefill_state_props(self, context: Context): selected = self.gather_selection(context) states = self.get_states_definition() # Iterate states and try to prefill state props while True: index = self.state_index result = None state = self.state data = self.get_state_data(index) coords = None if not state.allow_prefill: break func = self.get_func(state, "parse_selection") result = func(context, selected, index=index) if result: if not self.next_state(context): return {"FINISHED"} continue break return {"RUNNING_MODAL"} def state_data(self): return self._state_data.setdefault(self.state_index, {}) def get_state_data(self, index): if not self._state_data.get(index): self._state_data[index] = {} return self._state_data[index] def get_func(self, state, name): # fallback to operator method if function isn't specified by state func = getattr(state, name, None) if func: if isinstance(func, str): # callback can be specified by function name return getattr(self, func) return func if hasattr(self, name): return getattr(self, name) return None def has_func(self, state, name): return self.get_func(state, name) is not None def state_func(self, context, coords): return NotImplementedError def invoke(self, context: Context, event: Event): self._state_data.clear() if hasattr(self, "init"): if not self.init(context, event): return self._end(context, False) retval = {"RUNNING_MODAL"} go_modal = True if is_numeric_input(event): if self.init_numeric(True): self.evaluate_numeric_event(event) retval = {"RUNNING_MODAL"} self.evaluate_state(context, event, False) # NOTE: This allows to start the operator but waits for action (LMB event). # Try to fill states based on selection only when this is True since it doesn't # make senese to respect selection when the user interactivley starts the operator. elif self.wait_for_input: retval = self.prefill_state_props(context) if retval == {"FINISHED"}: go_modal = False # NOTE: It might make sense to cancel Operator if no prop could be filled # Otherwise it might not be obvious that an operator is running # if self.state_index == 0: # return self._end(context, False) if not self.executed and self.check_props(): self.run_op(context) self.executed = True context.area.tag_redraw() # doesn't seem to work... self.set_status_text(context) if go_modal: context.window.cursor_modal_set("CROSSHAIR") context.window_manager.modal_handler_add(self) return retval succeede = retval == {"FINISHED"} if succeede: # NOTE: It seems like there's no undo step pushed if an operator finishes from invoke # could push an undo_step here however this causes duplicated constraints after redo, # disable for now # bpy.ops.ed.undo_push() pass return self._end(context, succeede) def run_op(self, context: Context): if not hasattr(self, "main"): raise NotImplementedError( "StatefulOperators need to have a main method defined!" ) retval = self.main(context) self.executed = True return retval # Creates non-persistent data def redo_states(self, context: Context): for i, state in enumerate(self.get_states()): if i > self.state_index: # TODO: don't depend on active state, idealy it's possible to go back break if state.pointer: data = self._state_data.get(i, {}) is_existing_entity = data["is_existing_entity"] props = self.get_property(index=i) if props and not is_existing_entity: create = self.get_func(state, "create_element") ret_values = create( context, [getattr(self, p) for p in props], state, data ) values = to_list(ret_values) self.set_state_pointer(values, index=i, implicit=True) def execute(self, context: Context): self.redo_states(context) ok = self.main(context) return self._end(context, ok, skip_undo=True) # maybe allow to be modal again? def get_numeric_value(self, context: Context, coords): state = self.state prop_name = self.get_property()[0] prop = self.properties.rna_type.properties[prop_name] def parse_input(prop, input): units = context.scene.unit_settings unit = prop.unit type = prop.type value = None if input == "-": pass elif unit != "NONE": try: value = bpy.utils.units.to_value(units.system, unit, input) except ValueError: return prop.default if type == "INT": value = int(value) elif type == "FLOAT": value = float(input) elif type == "INT": value = int(input) if value is None: return prop.default return value size = max(1, self._substate_count) def to_iterable(item): if hasattr(item, "__iter__") or hasattr(item, "__getitem__"): return list(item) return [ item, ] # TODO: Don't evaluate if not needed interactive_val = self._get_state_values(context, state, coords) if interactive_val is None: interactive_val = [None] * size else: interactive_val = to_iterable(interactive_val) storage = [None] * size result = [None] * size for sub_index in range(size): num = None input = self._numeric_input.get(sub_index) if input: num = parse_input(prop, input) result[sub_index] = num storage[sub_index] = num elif interactive_val[sub_index] is not None: result[sub_index] = interactive_val[sub_index] else: result[sub_index] = prop.default self.state_data["numeric_input"] = storage if not self._substate_count: return result[0] return result def _handle_pass_through(self, context: Context, event: Event): # Only pass through navigation events if event.type in {"MIDDLEMOUSE", "WHEELUPMOUSE", "WHEELDOWNMOUSE", "MOUSEMOVE"}: return {"PASS_THROUGH"} return {"RUNNING_MODAL"} def modal(self, context: Context, event: Event): state = self.state event_triggered = self.check_event(event) coords = Vector((event.mouse_region_x, event.mouse_region_y)) is_numeric_edit = self.state_data.get("is_numeric_edit", False) is_numeric_event = event.value == "PRESS" and is_numeric_input(event) if is_numeric_edit: if is_unit_input(event) and event.value == "PRESS": is_numeric_event = True elif event.type == "TAB" and event.value == "PRESS": self.iterate_substate() self.set_status_text(context) elif is_numeric_event: # Initialize is_numeric_edit = self.init_numeric(True) if event.type in {"RIGHTMOUSE", "ESC"}: return self._end(context, False) # HACK: when calling ops.ed.undo() inside an operator a mousemove event # is getting triggered. manually check if there's a mousemove... mousemove_threshold = 0.1 is_mousemove = (coords - self._last_coords).length > mousemove_threshold self._last_coords = coords if not event_triggered: if is_numeric_event: pass elif is_mousemove and is_numeric_edit: event_triggered = False pass elif not state.interactive: return self._handle_pass_through(context, event) elif not is_mousemove: return self._handle_pass_through(context, event) # TODO: Disable numeric input when no state.property if is_numeric_event: self.evaluate_numeric_event(event) self.set_status_text(context) return self.evaluate_state(context, event, event_triggered) def _get_state_values(self, context: Context, state, coords): # Get values of state_func, can be none position_cb = self.get_func(state, "state_func") if not position_cb: return None pos_val = position_cb(context, coords) return pos_val def evaluate_state(self, context: Context, event, triggered): state = self.state data = self.state_data is_numeric = self.state_data.get("is_numeric_edit", False) coords = Vector((event.mouse_region_x, event.mouse_region_y)) if self.state_init_coords is None: self.state_init_coords = coords # Pick hovered element hovered = None is_picked = False if not is_numeric and state.pointer: pick = self.get_func(state, "pick_element") pick_retval = pick(context, coords) if pick_retval is not None: is_picked = True pointer_values = to_list(pick_retval) # Set state property ok = False values = [] use_create = state.use_create and self.has_func(state, "create_element") if use_create and not is_picked: if is_numeric: # numeric edit is supported for one property only values = [ self.get_numeric_value(context, coords), ] elif not is_picked: values = to_list(self._get_state_values(context, state, coords)) if values: props = self.get_property() if props: for i, v in enumerate(values): setattr(self, props[i], v) self._undo = True ok = not state.pointer # Set state pointer pointer = None if state.pointer: if is_picked: pointer = pointer_values self.state_data["is_existing_entity"] = True elif values: # Let pointer be filled from redo_states self.state_data["is_existing_entity"] = False ok = True if pointer: self.set_state_pointer(pointer, implicit=True) ok = True if self._undo: bpy.ops.ed.undo_push(message="Redo: " + self.bl_label) bpy.ops.ed.undo() global_data.ignore_list.clear() self.redo_states(context) self._undo = False succeede = False if self.check_props(): succeede = self.run_op(context) self._undo = True # Iterate state if triggered and ok: if not self.next_state(context): if self.check_continuous_draw(): self.do_continuous_draw(context) else: return self._end(context, succeede) if is_numeric: # NOTE: Run next state already once even if there's no mousemove yet, # This is needed in order for the geometry to update self.evaluate_state(context, event, False) context.area.tag_redraw() if triggered and not ok: # Event was triggered on non-valid selection, cancel operator to avoid confusion return self._end(context, False) if triggered or is_numeric: return {"RUNNING_MODAL"} return self._handle_pass_through(context, event) def check_continuous_draw(self): if self.continuous_draw: if not hasattr(self, "continue_draw") or self.continue_draw(): return True return False def _reset_op(self): self.executed = False for i, s in enumerate(self.get_states()): if not s.pointer: continue self.set_state_pointer(None, index=i) self._state_data.clear() def do_continuous_draw(self, context): # end operator self._end(context, True) bpy.ops.ed.undo_push(message=self.bl_label) # save last prop last_pointer = None for i, s in reversed(list(enumerate(self.get_states()))): if not s.pointer: continue last_index = i last_pointer = getattr(self, s.pointer) break values = to_list(self.get_state_pointer(index=last_index, implicit=True)) # reset operator self._reset_op() data = {} self._state_data[0] = data data["is_existing_entity"] = True data["type"] = type(last_pointer) # set first pointer self.set_state_pointer(values, index=0, implicit=True) self.set_state(context, 1) def _end(self, context, succeede, skip_undo=False): context.window.cursor_modal_restore() if hasattr(self, "fini"): self.fini(context, succeede) global_data.ignore_list.clear() context.workspace.status_text_set(None) if not succeede and not skip_undo: bpy.ops.ed.undo_push(message="Cancelled: " + self.bl_label) bpy.ops.ed.undo() retval = {"FINISHED"} if succeede else {"CANCELLED"} return retval def check_props(self): for i, state in enumerate(self.get_states()): if state.optional: continue props = self.get_property(index=i) if state.pointer: if not bool(self.get_state_pointer(index=i)): return False elif props: for p in props: if not self.properties.is_property_set(p): return False return True def description(cls, context, _properties): states = [ state_desc(s.name, s.description, s.types) for s in cls.get_states_definition() ] descs = [] hint = get_key_map_desc(context, cls.bl_idname) if hint: descs.append(hint) if cls.__doc__: descs.append(cls.__doc__) return stateful_op_desc(" ".join(descs), *states) # Dummy methods def gather_selection(self, context: Context): raise NotImplementedError The provided code snippet includes necessary dependencies for implementing the `get_subclasses` function. Write a Python function `def get_subclasses()` to solve the following problem: Get all classes that inherit from StatefulOperatorLogic Here is the function: def get_subclasses(): """Get all classes that inherit from StatefulOperatorLogic""" from ..logic import StatefulOperatorLogic def _get_classes(cls_list): ret = [] for c in cls_list: sub_classes = c.__subclasses__() if not len(sub_classes): continue ret.extend(_get_classes(sub_classes)) return cls_list + ret return _get_classes(StatefulOperatorLogic.__subclasses__())
Get all classes that inherit from StatefulOperatorLogic
20,140
def _format_types(types): entity_names = ", ".join([e.__name__ for e in types]) return "[" + entity_names + "]" def state_desc(name, desc, types): type_desc = "" if types: type_desc = "Types: " + _format_types(types) return " ".join((name + ":", desc, type_desc))
null
20,141
def stateful_op_desc(base, *state_descs): states = "" length = len(state_descs) for i, state in enumerate(state_descs): states += " - {}{}".format(state, (" \n" if i < length - 1 else "")) desc = "{} \n \nStates: \n{}".format(base, states) return desc
null
20,142
from typing import Type, List from bpy.utils import register_class, unregister_class from ..logic import StatefulOperatorLogic def _register_stateop(cls: Type[StatefulOperatorLogic]): if hasattr(cls, "register_properties"): cls.register_properties() register_class(cls) class StatefulOperatorLogic: """Base class which implements the behaviour logic""" state_index: IntProperty(options={"HIDDEN", "SKIP_SAVE"}) wait_for_input: BoolProperty(options={"HIDDEN", "SKIP_SAVE"}, default=True) continuous_draw: BoolProperty(name="Continuous Draw", default=False) executed = False # Stores the returned value of state_func the first time it runs per state state_init_coords = None _state_data = {} _last_coords = Vector((0, 0)) _numeric_input = {} _undo = False def get_property(self, index: Optional[int] = None): if index is None: index = self.state_index state = self.get_states()[index] if state.property is None: return None if callable(state.property): props = state.property(self, index) elif state.property: if callable(getattr(self, state.property)): props = getattr(self, state.property)(index) else: props = state.property elif hasattr(self, "state_property") and callable(self.state_property): props = self.state_property(index) else: return None retval = to_list(props) return retval def get_states_definition(cls): if callable(cls.states): return cls.states() return cls.states def get_states(self): if callable(self.states): return self.states(operator=self) return self.states def state(self): return self.get_states()[self.state_index] def _index_from_state(self, state): return [e.name for e in self.get_states()].index(state) def state(self, state): self.state_index = self._index_from_state(state) def set_state(self, context: Context, index: int): self.state_index = index self.init_numeric(False) self.set_status_text(context) def next_state(self, context: Context): self._undo = False self.state_init_coords = None i = self.state_index if (i + 1) >= len(self.get_states()): return False self.set_state(context, i + 1) return True def set_status_text(self, context: Context): # Setup state state = self.state desc = ( state.description(self, state) if callable(state.description) else state.description ) msg = state_desc(state.name, desc, state.types) if self.state_data.get("is_numeric_edit", False): index = self._substate_index prop = self._stateprop type = prop.type array_length = prop.array_length if prop.array_length else 1 if type == "FLOAT": input = [0.0] * array_length for key, val in self._numeric_input.items(): input[key] = val input[index] = "*" + str(input[index]) input = str(input).replace('"', "").replace("'", "") elif type == "INT": input = self.numeric_input msg += " {}: {}".format(prop.subtype, input) context.workspace.status_text_set(msg) def check_numeric(self): """Check if the state supports numeric edit""" # TODO: Allow to define custom logic state = self.state props = self.get_property() # Disable for multi props if not props or len(props) > 1: return False prop_name = props[0] if not prop_name: return False prop = self.properties.rna_type.properties.get(prop_name) if not prop: return False if prop.type not in ("INT", "FLOAT"): return False return True def init_numeric(self, is_numeric): self._numeric_input = {} self._substate_index = 0 ok = False if is_numeric: ok = self.check_numeric() # TODO: not when iterating substates self.state_data["is_numeric_edit"] = is_numeric and ok self.init_substate() return ok def init_substate(self): # Reset self._substate_count = None self._stateprop = None props = self.get_property() if not props: return if not props[0]: return prop_name = props[0] prop = self.properties.rna_type.properties.get(prop_name) if not prop: return self._substate_count = prop.array_length self._stateprop = prop def iterate_substate(self): i = self._substate_index if i + 1 >= self._substate_count: i = 0 else: i += 1 self._substate_index = i def numeric_input(self): return self._numeric_input.get(self._substate_index, "") def numeric_input(self, value): self._numeric_input[self._substate_index] = value def check_event(self, event): state = self.state is_confirm_button = event.type in ("LEFTMOUSE", "RET", "NUMPAD_ENTER") if is_confirm_button and event.value == "PRESS": return True if self.state_index == 0 and not self.wait_for_input: # Trigger the first state return not self.state_data.get("is_numeric_edit", False) if state.no_event: return True return False def evaluate_numeric_event(self, event: Event): type = event.type if type == "BACK_SPACE": input = self.numeric_input if len(input): self.numeric_input = input[:-1] return if type in ("MINUS", "NUMPAD_MINUS"): input = self.numeric_input if input.startswith("-"): input = input[1:] else: input = "-" + input self.numeric_input = input return if is_unit_input(event): self.numeric_input += get_unit_value(event) return value = get_value_from_event(event) self.numeric_input += self.validate_numeric_input(value) def validate_numeric_input(self, value): """Check if existing input is valid after appending value""" num_input = self.numeric_input separators = (".", ",") if value in separators: if any([char in num_input for char in separators]): return "" if not len(num_input) or not num_input[-1].isdigit(): return "0." return value def is_in_previous_states(self, entity): i = self.state_index - 1 while True: if i < 0: break state = self.get_states()[i] if state.pointer and entity == getattr(self, state.pointer): return True i -= 1 return False def prefill_state_props(self, context: Context): selected = self.gather_selection(context) states = self.get_states_definition() # Iterate states and try to prefill state props while True: index = self.state_index result = None state = self.state data = self.get_state_data(index) coords = None if not state.allow_prefill: break func = self.get_func(state, "parse_selection") result = func(context, selected, index=index) if result: if not self.next_state(context): return {"FINISHED"} continue break return {"RUNNING_MODAL"} def state_data(self): return self._state_data.setdefault(self.state_index, {}) def get_state_data(self, index): if not self._state_data.get(index): self._state_data[index] = {} return self._state_data[index] def get_func(self, state, name): # fallback to operator method if function isn't specified by state func = getattr(state, name, None) if func: if isinstance(func, str): # callback can be specified by function name return getattr(self, func) return func if hasattr(self, name): return getattr(self, name) return None def has_func(self, state, name): return self.get_func(state, name) is not None def state_func(self, context, coords): return NotImplementedError def invoke(self, context: Context, event: Event): self._state_data.clear() if hasattr(self, "init"): if not self.init(context, event): return self._end(context, False) retval = {"RUNNING_MODAL"} go_modal = True if is_numeric_input(event): if self.init_numeric(True): self.evaluate_numeric_event(event) retval = {"RUNNING_MODAL"} self.evaluate_state(context, event, False) # NOTE: This allows to start the operator but waits for action (LMB event). # Try to fill states based on selection only when this is True since it doesn't # make senese to respect selection when the user interactivley starts the operator. elif self.wait_for_input: retval = self.prefill_state_props(context) if retval == {"FINISHED"}: go_modal = False # NOTE: It might make sense to cancel Operator if no prop could be filled # Otherwise it might not be obvious that an operator is running # if self.state_index == 0: # return self._end(context, False) if not self.executed and self.check_props(): self.run_op(context) self.executed = True context.area.tag_redraw() # doesn't seem to work... self.set_status_text(context) if go_modal: context.window.cursor_modal_set("CROSSHAIR") context.window_manager.modal_handler_add(self) return retval succeede = retval == {"FINISHED"} if succeede: # NOTE: It seems like there's no undo step pushed if an operator finishes from invoke # could push an undo_step here however this causes duplicated constraints after redo, # disable for now # bpy.ops.ed.undo_push() pass return self._end(context, succeede) def run_op(self, context: Context): if not hasattr(self, "main"): raise NotImplementedError( "StatefulOperators need to have a main method defined!" ) retval = self.main(context) self.executed = True return retval # Creates non-persistent data def redo_states(self, context: Context): for i, state in enumerate(self.get_states()): if i > self.state_index: # TODO: don't depend on active state, idealy it's possible to go back break if state.pointer: data = self._state_data.get(i, {}) is_existing_entity = data["is_existing_entity"] props = self.get_property(index=i) if props and not is_existing_entity: create = self.get_func(state, "create_element") ret_values = create( context, [getattr(self, p) for p in props], state, data ) values = to_list(ret_values) self.set_state_pointer(values, index=i, implicit=True) def execute(self, context: Context): self.redo_states(context) ok = self.main(context) return self._end(context, ok, skip_undo=True) # maybe allow to be modal again? def get_numeric_value(self, context: Context, coords): state = self.state prop_name = self.get_property()[0] prop = self.properties.rna_type.properties[prop_name] def parse_input(prop, input): units = context.scene.unit_settings unit = prop.unit type = prop.type value = None if input == "-": pass elif unit != "NONE": try: value = bpy.utils.units.to_value(units.system, unit, input) except ValueError: return prop.default if type == "INT": value = int(value) elif type == "FLOAT": value = float(input) elif type == "INT": value = int(input) if value is None: return prop.default return value size = max(1, self._substate_count) def to_iterable(item): if hasattr(item, "__iter__") or hasattr(item, "__getitem__"): return list(item) return [ item, ] # TODO: Don't evaluate if not needed interactive_val = self._get_state_values(context, state, coords) if interactive_val is None: interactive_val = [None] * size else: interactive_val = to_iterable(interactive_val) storage = [None] * size result = [None] * size for sub_index in range(size): num = None input = self._numeric_input.get(sub_index) if input: num = parse_input(prop, input) result[sub_index] = num storage[sub_index] = num elif interactive_val[sub_index] is not None: result[sub_index] = interactive_val[sub_index] else: result[sub_index] = prop.default self.state_data["numeric_input"] = storage if not self._substate_count: return result[0] return result def _handle_pass_through(self, context: Context, event: Event): # Only pass through navigation events if event.type in {"MIDDLEMOUSE", "WHEELUPMOUSE", "WHEELDOWNMOUSE", "MOUSEMOVE"}: return {"PASS_THROUGH"} return {"RUNNING_MODAL"} def modal(self, context: Context, event: Event): state = self.state event_triggered = self.check_event(event) coords = Vector((event.mouse_region_x, event.mouse_region_y)) is_numeric_edit = self.state_data.get("is_numeric_edit", False) is_numeric_event = event.value == "PRESS" and is_numeric_input(event) if is_numeric_edit: if is_unit_input(event) and event.value == "PRESS": is_numeric_event = True elif event.type == "TAB" and event.value == "PRESS": self.iterate_substate() self.set_status_text(context) elif is_numeric_event: # Initialize is_numeric_edit = self.init_numeric(True) if event.type in {"RIGHTMOUSE", "ESC"}: return self._end(context, False) # HACK: when calling ops.ed.undo() inside an operator a mousemove event # is getting triggered. manually check if there's a mousemove... mousemove_threshold = 0.1 is_mousemove = (coords - self._last_coords).length > mousemove_threshold self._last_coords = coords if not event_triggered: if is_numeric_event: pass elif is_mousemove and is_numeric_edit: event_triggered = False pass elif not state.interactive: return self._handle_pass_through(context, event) elif not is_mousemove: return self._handle_pass_through(context, event) # TODO: Disable numeric input when no state.property if is_numeric_event: self.evaluate_numeric_event(event) self.set_status_text(context) return self.evaluate_state(context, event, event_triggered) def _get_state_values(self, context: Context, state, coords): # Get values of state_func, can be none position_cb = self.get_func(state, "state_func") if not position_cb: return None pos_val = position_cb(context, coords) return pos_val def evaluate_state(self, context: Context, event, triggered): state = self.state data = self.state_data is_numeric = self.state_data.get("is_numeric_edit", False) coords = Vector((event.mouse_region_x, event.mouse_region_y)) if self.state_init_coords is None: self.state_init_coords = coords # Pick hovered element hovered = None is_picked = False if not is_numeric and state.pointer: pick = self.get_func(state, "pick_element") pick_retval = pick(context, coords) if pick_retval is not None: is_picked = True pointer_values = to_list(pick_retval) # Set state property ok = False values = [] use_create = state.use_create and self.has_func(state, "create_element") if use_create and not is_picked: if is_numeric: # numeric edit is supported for one property only values = [ self.get_numeric_value(context, coords), ] elif not is_picked: values = to_list(self._get_state_values(context, state, coords)) if values: props = self.get_property() if props: for i, v in enumerate(values): setattr(self, props[i], v) self._undo = True ok = not state.pointer # Set state pointer pointer = None if state.pointer: if is_picked: pointer = pointer_values self.state_data["is_existing_entity"] = True elif values: # Let pointer be filled from redo_states self.state_data["is_existing_entity"] = False ok = True if pointer: self.set_state_pointer(pointer, implicit=True) ok = True if self._undo: bpy.ops.ed.undo_push(message="Redo: " + self.bl_label) bpy.ops.ed.undo() global_data.ignore_list.clear() self.redo_states(context) self._undo = False succeede = False if self.check_props(): succeede = self.run_op(context) self._undo = True # Iterate state if triggered and ok: if not self.next_state(context): if self.check_continuous_draw(): self.do_continuous_draw(context) else: return self._end(context, succeede) if is_numeric: # NOTE: Run next state already once even if there's no mousemove yet, # This is needed in order for the geometry to update self.evaluate_state(context, event, False) context.area.tag_redraw() if triggered and not ok: # Event was triggered on non-valid selection, cancel operator to avoid confusion return self._end(context, False) if triggered or is_numeric: return {"RUNNING_MODAL"} return self._handle_pass_through(context, event) def check_continuous_draw(self): if self.continuous_draw: if not hasattr(self, "continue_draw") or self.continue_draw(): return True return False def _reset_op(self): self.executed = False for i, s in enumerate(self.get_states()): if not s.pointer: continue self.set_state_pointer(None, index=i) self._state_data.clear() def do_continuous_draw(self, context): # end operator self._end(context, True) bpy.ops.ed.undo_push(message=self.bl_label) # save last prop last_pointer = None for i, s in reversed(list(enumerate(self.get_states()))): if not s.pointer: continue last_index = i last_pointer = getattr(self, s.pointer) break values = to_list(self.get_state_pointer(index=last_index, implicit=True)) # reset operator self._reset_op() data = {} self._state_data[0] = data data["is_existing_entity"] = True data["type"] = type(last_pointer) # set first pointer self.set_state_pointer(values, index=0, implicit=True) self.set_state(context, 1) def _end(self, context, succeede, skip_undo=False): context.window.cursor_modal_restore() if hasattr(self, "fini"): self.fini(context, succeede) global_data.ignore_list.clear() context.workspace.status_text_set(None) if not succeede and not skip_undo: bpy.ops.ed.undo_push(message="Cancelled: " + self.bl_label) bpy.ops.ed.undo() retval = {"FINISHED"} if succeede else {"CANCELLED"} return retval def check_props(self): for i, state in enumerate(self.get_states()): if state.optional: continue props = self.get_property(index=i) if state.pointer: if not bool(self.get_state_pointer(index=i)): return False elif props: for p in props: if not self.properties.is_property_set(p): return False return True def description(cls, context, _properties): states = [ state_desc(s.name, s.description, s.types) for s in cls.get_states_definition() ] descs = [] hint = get_key_map_desc(context, cls.bl_idname) if hint: descs.append(hint) if cls.__doc__: descs.append(cls.__doc__) return stateful_op_desc(" ".join(descs), *states) # Dummy methods def gather_selection(self, context: Context): raise NotImplementedError def register_stateops_factory(classes: List[Type[StatefulOperatorLogic]]): def register(): for cls in classes: _register_stateop(cls) def unregister(): for cls in reversed(classes): unregister_class(cls) return register, unregister
null
20,143
from bpy.types import Context, Object, RegionView3D from bpy_extras import view3d_utils from mathutils import Vector from bpy_extras.view3d_utils import region_2d_to_location_3d, region_2d_to_vector_3d from ..utilities.generic import bvhtree_from_object from typing import Optional def get_placement_pos(context: Context, coords: Vector) -> Vector: region = context.region rv3d = context.region_data view_vector = region_2d_to_vector_3d(region, rv3d, coords) return region_2d_to_location_3d(region, rv3d, coords, view_vector)
null
20,144
from bpy.types import Context, Object, RegionView3D from bpy_extras import view3d_utils from mathutils import Vector from bpy_extras.view3d_utils import region_2d_to_location_3d, region_2d_to_vector_3d from ..utilities.generic import bvhtree_from_object from typing import Optional def get_scale_from_pos(co: Vector, rv3d: RegionView3D) -> Vector: if rv3d.view_perspective == "ORTHO": scale = rv3d.view_distance else: scale = (rv3d.perspective_matrix @ co.to_4d())[3] return scale
null
20,145
from bpy.types import Context, Object, RegionView3D from bpy_extras import view3d_utils from mathutils import Vector from bpy_extras.view3d_utils import region_2d_to_location_3d, region_2d_to_vector_3d from ..utilities.generic import bvhtree_from_object from typing import Optional def get_evaluated_obj(context: Context, object: Object): return object.evaluated_get(context.evaluated_depsgraph_get()) def bvhtree_from_object(object: Object) -> BVHTree: depsgraph = bpy.context.evaluated_depsgraph_get() object_eval = object.evaluated_get(depsgraph) mesh = object_eval.to_mesh() bm = bmesh.new() bm.from_mesh(mesh) bm.transform(object.matrix_world) bvhtree = BVHTree.FromBMesh(bm) object_eval.to_mesh_clear() bm.free() return bvhtree def get_mesh_element( context: Context, coords, vertex=False, edge=False, face=False, threshold=0.5, object: Optional[Object] = None, ): # get the ray from the viewport and mouse region = context.region rv3d = context.region_data view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, coords) ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, coords) depsgraph = context.view_layer.depsgraph scene = context.scene if not object: result, loc, _normal, face_index, ob, _matrix = scene.ray_cast( depsgraph, ray_origin, view_vector ) else: # Alternatively do a object raycast if we know the object already tree = bvhtree_from_object(object) loc, _normal, face_index, _distance = tree.ray_cast(ray_origin, view_vector) result = loc is not None ob = object if not result: return None, None, None obj_eval = get_evaluated_obj(context, ob) closest_type = "" closest_dist = None loc = obj_eval.matrix_world.inverted() @ loc me = obj_eval.data polygon = me.polygons[face_index] def get_closest(deltas): index_min = min(range(len(deltas)), key=deltas.__getitem__) if deltas[index_min] > threshold: return None, None return index_min, deltas[index_min] def is_closer(distance, min_distance): if min_distance is None: return True if distance < min_distance: return True return False if vertex: i, dist = get_closest( [(me.vertices[i].co - loc).length for i in polygon.vertices] ) if i is not None: closest_type = "VERTEX" closest_index = polygon.vertices[i] closest_dist = dist if edge: face_edge_map = {ek: me.edges[i] for i, ek in enumerate(me.edge_keys)} i, dist = get_closest( [ (((me.vertices[start].co + me.vertices[end].co) / 2) - loc).length for start, end in polygon.edge_keys ] ) if i is not None and is_closer(dist, closest_dist): closest_type = "EDGE" closest_index = face_edge_map[polygon.edge_keys[i]].index closest_dist = dist if face: # Check if face midpoint is closest if is_closer((polygon.center - loc).length, closest_dist): closest_type = "FACE" closest_index = face_index if closest_type: return ob, closest_type, closest_index return ob, Object, None
null
20,146
from collections import namedtuple OperatorState = namedtuple( "OperatorState", ( "name", # The name to display in the interface "description", # Text to be displayed in statusbar # Operator property this state acts upon # Can also be a list of property names or a callback that returns # a set of properties dynamically. When not explicitly set to None the # operators state_property function will be called. "property", # Optional: A state can reference an element, pointer attribute set the name of property function # if set this will be passed to main func, # state_func should fill main property and create_element should fill this property # maybe this could just store it in a normal attr, should work as long as the same operator instance is used, test! "pointer", "types", # Types the pointer property can accept "no_event", # Trigger state without an event "interactive", # Always evaluate state and confirm by user input "use_create", # Enables or Disables creation of the element "state_func", # Function to get the state property value from mouse coordinates "allow_prefill", # Define if state should be filled from selected entities when invoked "parse_selection", # Prefill Function which chooses entity to use for this stat "pick_element", "create_element", # TODO: Implement! "use_interactive_placemenet", # Create new state element based on mouse coordinates "check_pointer", "optional", # Operator can be run before this state's pointer/property is submitted ), ) The provided code snippet includes necessary dependencies for implementing the `state_from_args` function. Write a Python function `def state_from_args(name: str, **kwargs)` to solve the following problem: Use so each state can avoid defining all members of the named tuple. Here is the function: def state_from_args(name: str, **kwargs): """ Use so each state can avoid defining all members of the named tuple. """ kw = { "name": name, "description": "", "property": "", "pointer": None, "types": (), "no_event": False, "interactive": False, "use_create": True, "state_func": None, "allow_prefill": True, "parse_selection": None, "pick_element": None, "create_element": None, "use_interactive_placemenet": True, "check_pointer": None, "optional": False, } kw.update(kwargs) return OperatorState(**kw)
Use so each state can avoid defining all members of the named tuple.
20,147
import bpy from . import assets_manager, global_data def startup_cb(*args): bpy.ops.view3d.slvs_register_draw_cb() assets_manager.load() return None def register(): bpy.app.timers.register(startup_cb, first_interval=1, persistent=True)
null
20,148
import bpy from . import assets_manager, global_data def unregister(): handle = global_data.draw_handle if handle: bpy.types.SpaceView3D.draw_handler_remove(handle, "WINDOW")
null
20,149
import glob import bpy from bpy.types import Operator, Object, Context, MeshEdge, MeshPolygon from bpy.props import FloatProperty, IntProperty, FloatVectorProperty from mathutils import Vector from .base_3d import Operator3d from ..global_data import LIB_NAME from ..declarations import Operators from ..utilities.view import get_placement_pos from ..stateful_operator.utilities.register import register_stateops_factory from ..stateful_operator.state import state_from_args from ..model.types import SlvsLine3D, SlvsLine2D, SlvsWorkplane The provided code snippet includes necessary dependencies for implementing the `load_asset` function. Write a Python function `def load_asset(library, asset_type, asset)` to solve the following problem: Loads an asset of given type from a specified library Returns True if it is loaded or already present in file Here is the function: def load_asset(library, asset_type, asset): """Loads an asset of given type from a specified library Returns True if it is loaded or already present in file""" # Check if the asset is already present in file if asset in [a.name for a in getattr(bpy.data, asset_type)]: return True prefs = bpy.context.preferences fp = prefs.filepaths.asset_libraries[library].path for file in glob.glob(fp + "/*.blend"): with bpy.data.libraries.load(file, assets_only=True) as (data_from, data_to): coll = getattr(data_from, asset_type) if not asset in coll: continue getattr(data_to, asset_type).append(asset) group = getattr(bpy.data, "node_groups").get(asset) group.use_fake_user = True return True return False
Loads an asset of given type from a specified library Returns True if it is loaded or already present in file
20,150
import logging from bpy.types import Operator, Context from bpy.props import FloatProperty from ..model.utilities import update_pointers from ..solver import solve_system from ..declarations import Operators from ..stateful_operator.utilities.register import register_stateops_factory from .base_constraint import GenericConstraintOp from ..utilities.select import deselect_all from ..utilities.view import refresh from ..solver import solve_system def update_pointers(scene, index_old, index_new): """Replaces all references to an entity index with its new index""" logger.debug("Update references {} -> {}".format(index_old, index_new)) # NOTE: this should go through all entity pointers and update them if necessary. # It might be possible to use the msgbus to notify and update the IntProperty pointers if scene.sketcher.active_sketch_i == index_old: logger.debug( "Update reference {} of {} to {}: ".format( "active_sketch", scene.sketcher, index_new ) ) scene.sketcher.active_sketch_i = index_new for o in scene.sketcher.all: if not hasattr(o, "update_pointers"): continue o.update_pointers(index_old, index_new) scene.sketcher.purge_stale_data() def merge_points(context, duplicate, target): update_pointers(context.scene, duplicate.slvs_index, target.slvs_index) context.scene.sketcher.entities.remove(duplicate.slvs_index)
null
20,151
import logging from bpy.types import Operator, Context from bpy.props import FloatProperty, BoolProperty from ..utilities.constants import HALF_TURN from ..declarations import Operators from ..stateful_operator.utilities.register import register_stateops_factory from .base_constraint import GenericConstraintOp def invert_angle_getter(self): return self.get("setting", self.bl_rna.properties["setting"].default)
null
20,152
import logging from bpy.types import Operator, Context from bpy.props import FloatProperty, BoolProperty from ..utilities.constants import HALF_TURN from ..declarations import Operators from ..stateful_operator.utilities.register import register_stateops_factory from .base_constraint import GenericConstraintOp HALF_TURN = tau / 2 def invert_angle_setter(self, setting): self["value"] = HALF_TURN - self.value self["setting"] = setting
null
20,153
import logging import bpy from bpy.types import Context, Operator from mathutils import Matrix from .. import global_data from ..declarations import GizmoGroups, WorkSpaceTools from ..converters import update_convertor_geometry from ..utilities.preferences import use_experimental, get_prefs from ..utilities.data_handling import entities_3d logger = logging.getLogger(__name__) def entities_3d(context: Context) -> Generator[SlvsGenericEntity, None, None]: for entity in context.scene.sketcher.entities.all: if hasattr(entity, "sketch"): continue yield entity def select_invert(context: Context): sketch = context.scene.sketcher.active_sketch if sketch: logger.debug( f"Inverting selection of sketcher entities in sketch : {sketch.name} (slvs_index: {sketch.slvs_index})" ) generator = sketch.sketch_entities(context) else: logger.debug(f"Inverting selection of sketcher entities") generator = entities_3d(context) for e in generator: e.selected = not e.selected
null
20,154
import logging import bpy from bpy.types import Context, Operator from mathutils import Matrix from .. import global_data from ..declarations import GizmoGroups, WorkSpaceTools from ..converters import update_convertor_geometry from ..utilities.preferences import use_experimental, get_prefs from ..utilities.data_handling import entities_3d logger = logging.getLogger(__name__) def entities_3d(context: Context) -> Generator[SlvsGenericEntity, None, None]: for entity in context.scene.sketcher.entities.all: if hasattr(entity, "sketch"): continue yield entity def select_extend(context: Context): sketch = context.scene.sketcher.active_sketch if sketch: logger.debug( f"Extending chain selection of sketcher entities in sketch : {sketch.name} (slvs_index: {sketch.slvs_index})" ) generator = sketch.sketch_entities(context) else: logger.debug(f"Extending chain selection of sketcher entities") generator = entities_3d(context) to_select = [] for e in generator: if not e.is_point(): if e.selected: to_select.extend(e.connection_points()) elif any(p.selected for p in e.connection_points()): to_select.append(e) for coincident in context.scene.sketcher.constraints.coincident: if any(entity.selected for entity in coincident.entities()): to_select.extend(coincident.entities()) is_something_to_select = not all(e.selected for e in to_select) for entity in to_select: entity.selected = True return is_something_to_select
null
20,155
import logging import bpy from bpy.types import Context, Operator from mathutils import Matrix from .. import global_data from ..declarations import GizmoGroups, WorkSpaceTools from ..converters import update_convertor_geometry from ..utilities.preferences import use_experimental, get_prefs from ..utilities.data_handling import entities_3d def ignore_hover(entity): ignore_list = global_data.ignore_list index = entity if isinstance(entity, int) else entity.slvs_index ignore_list.append(index)
null
20,156
import logging import bpy from bpy.types import Context, Operator from mathutils import Matrix from .. import global_data from ..declarations import GizmoGroups, WorkSpaceTools from ..converters import update_convertor_geometry from ..utilities.preferences import use_experimental, get_prefs from ..utilities.data_handling import entities_3d def get_hovered(context: Context, *types): hovered = global_data.hover entity = None if hovered != -1: entity = context.scene.sketcher.entities.get(hovered) if type(entity) in types: return entity return None
null
20,157
import logging import bpy from bpy.types import Context, Operator from mathutils import Matrix from .. import global_data from ..declarations import GizmoGroups, WorkSpaceTools from ..converters import update_convertor_geometry from ..utilities.preferences import use_experimental, get_prefs from ..utilities.data_handling import entities_3d logger = logging.getLogger(__name__) def align_view(rv3d, mat_start, mat_end): global SMOOTHVIEW_FACTOR SMOOTHVIEW_FACTOR = 0 time_step = 0.01 increment = 0.01 def move_view(): global SMOOTHVIEW_FACTOR SMOOTHVIEW_FACTOR += increment mat = mat_start.lerp(mat_end, SMOOTHVIEW_FACTOR) rv3d.view_matrix = mat if SMOOTHVIEW_FACTOR < 1: return time_step bpy.app.timers.register(move_view) # rv3d.view_distance = 6 def switch_sketch_mode(self, context: Context, to_sketch_mode: bool): if to_sketch_mode: tool = context.workspace.tools.from_space_view3d_mode(context.mode) if tool.widget != GizmoGroups.Preselection: bpy.ops.wm.tool_set_by_id(name=WorkSpaceTools.Select) return True bpy.ops.wm.tool_set_by_index(index=0, expand=False) return True def select_target_ob(context, sketch): mode = sketch.convert_type target_ob = sketch.target_object if mode == "MESH" else sketch.target_curve_object bpy.ops.object.select_all(action="DESELECT") if not target_ob: return if target_ob.name in context.view_layer.objects: target_ob.select_set(True) context.view_layer.objects.active = target_ob def update_convertor_geometry(scene: Scene, sketch=None): coll = (sketch,) if sketch else scene.sketcher.entities.sketches for sketch in coll: mode = sketch.convert_type if sketch.convert_type == "NONE": _cleanup_data(sketch, mode) continue data = bpy.data name = sketch.name # Create curve object if not sketch.target_curve_object: curve = bpy.data.objects.data.curves.new(name, "CURVE") object = bpy.data.objects.new(name, curve) sketch.target_curve_object = object else: # Clear curve data sketch.target_curve_object.data.splines.clear() # Convert geometry to curve data conv = BezierConverter(scene, sketch) # TODO: Avoid re-converting sketches where nothing has changed! logger.info("Convert sketch {} to {}: ".format(sketch, mode.lower())) curve_data = sketch.target_curve_object.data conv.to_bezier(curve_data) data = curve_data # Link / unlink curve object _link_unlink_object(scene, sketch.target_curve_object, mode == "BEZIER") if mode == "MESH": # Set curve resolution for spline in sketch.target_curve_object.data.splines: spline.resolution_u = sketch.curve_resolution # Create mesh data temp_mesh = sketch.target_curve_object.to_mesh() mesh = mesh_from_temporary( temp_mesh, name, existing_mesh=( sketch.target_object.data if sketch.target_object else None ), ) sketch.target_curve_object.to_mesh_clear() # Create mesh object if not sketch.target_object: mesh_object = bpy.data.objects.new(name, mesh) scene.collection.objects.link(mesh_object) sketch.target_object = mesh_object else: sketch.target_object.data = mesh _cleanup_data(sketch, mode) target_ob = ( sketch.target_object if mode == "MESH" else sketch.target_curve_object ) target_ob.matrix_world = sketch.wp.matrix_basis target_ob.sketch_index = sketch.slvs_index # Update object name target_ob.name = sketch.name def get_prefs(): return bpy.context.preferences.addons[get_name()].preferences def use_experimental(setting, fallback): """Ensure experimental setting is unused when not in experimental mode""" if not is_experimental(): return fallback prefs = get_prefs() return getattr(prefs, setting) def activate_sketch(context: Context, index: int, operator: Operator): space_data = context.space_data rv3d = context.region_data props = context.scene.sketcher if index == props.active_sketch_i: return {"CANCELLED"} sketch_mode = index != -1 switch_sketch_mode(self=operator, context=context, to_sketch_mode=sketch_mode) sk = None do_align_view = use_experimental("use_align_view", False) if sketch_mode: sk = context.scene.sketcher.entities.get(index) if not sk: operator.report({"ERROR"}, "Invalid index: {}".format(index)) return {"CANCELLED"} # Align view to normal of wp if do_align_view: matrix_target = sk.wp.matrix_basis.inverted() matrix_start = rv3d.view_matrix align_view(rv3d, matrix_start, matrix_target) rv3d.view_perspective = "ORTHO" else: # Reset view if do_align_view: rv3d.view_distance = 18 matrix_start = rv3d.view_matrix matrix_default = Matrix( ( ( 0.4100283980369568, 0.9119764566421509, -0.013264661654829979, 0.0, ), (-0.4017425775527954, 0.19364342093467712, 0.8950449228286743, 0.0), ( 0.8188283443450928, -0.36166495084762573, 0.44577890634536743, -17.986562728881836, ), (0.0, 0.0, 0.0, 1.0), ) ) align_view(rv3d, matrix_start, matrix_default) rv3d.view_perspective = "PERSP" # Hide objects fade_objects = get_prefs().auto_hide_objects if fade_objects: space_data.shading.show_xray = sketch_mode last_sketch = context.scene.sketcher.active_sketch logger.debug("Activate: {}".format(sk)) props.active_sketch_i = index context.area.tag_redraw() if index != -1: return {"FINISHED"} if context.mode != "OBJECT": return {"FINISHED"} update_convertor_geometry(context.scene, sketch=last_sketch) select_target_ob(context, last_sketch) return {"FINISHED"}
null
20,158
from bpy.types import Macro from bpy.utils import register_class, unregister_class from ..declarations import Macros class View3D_OT_slvs_duplicate_move(Macro): """Duplicate selected entities""" bl_idname = Macros.DuplicateMove bl_label = "Duplicate" bl_options = {"UNDO"} def register(): register_class(View3D_OT_slvs_duplicate_move) View3D_OT_slvs_duplicate_move.define("VIEW3D_OT_slvs_copy") View3D_OT_slvs_duplicate_move.define("VIEW3D_OT_slvs_paste")
null
20,159
from bpy.types import Macro from bpy.utils import register_class, unregister_class from ..declarations import Macros class View3D_OT_slvs_duplicate_move(Macro): """Duplicate selected entities""" bl_idname = Macros.DuplicateMove bl_label = "Duplicate" bl_options = {"UNDO"} def unregister(): unregister_class(View3D_OT_slvs_duplicate_move)
null
20,160
import bpy, gpu from bpy.types import Operator, Context, Event from bpy.utils import register_classes_factory from mathutils import Vector from gpu_extras.batch import batch_for_shader from .. import global_data from ..declarations import Operators from ..utilities.index import rgb_to_index from ..utilities.view import refresh from ..utilities.select import mode_property, deselect_all def get_start_dist(value1, value2, invert: bool = False): values = [value1, value2] values.sort(reverse=invert) start = values[0] return int(start), int(abs(value2 - value1))
null
20,161
import bpy, gpu from bpy.types import Operator, Context, Event from bpy.utils import register_classes_factory from mathutils import Vector from gpu_extras.batch import batch_for_shader from .. import global_data from ..declarations import Operators from ..utilities.index import rgb_to_index from ..utilities.view import refresh from ..utilities.select import mode_property, deselect_all def draw_callback_px(self, context): shader = gpu.shader.from_builtin("UNIFORM_COLOR") gpu.state.blend_set("ALPHA") gpu.state.line_width_set(2.0) start = self.start_coords end = self.mouse_pos box_path = (start, (end.x, start.y), end, (start.x, end.y), start) batch = batch_for_shader(shader, "LINE_STRIP", {"pos": box_path}) shader.bind() shader.uniform_float("color", (0.0, 0.0, 0.0, 0.5)) batch.draw(shader) # restore opengl defaults gpu.state.line_width_set(1.0) gpu.state.blend_set("NONE")
null
20,162
from copy import deepcopy from typing import Any, List, Sequence, Tuple import bpy from bpy.utils import register_classes_factory from bpy.types import Operator, Context from .. import global_data from ..declarations import Operators from ..serialize import paste from ..utilities.select import deselect_all from ..utilities.data_handling import ( get_collective_dependencies, get_scoped_constraints, ) from ..serialize import iter_elements_dict The provided code snippet includes necessary dependencies for implementing the `_filter_elements_dict` function. Write a Python function `def _filter_elements_dict( data, dict_elements: Sequence[tuple[str, list]], whitelist: Sequence[Any] ) -> List[tuple[str, list]]` to solve the following problem: Returns filtered list of elements based on whitelist dict_elements must be the dictionary representation of whats stored in data without any modifications Here is the function: def _filter_elements_dict( data, dict_elements: Sequence[tuple[str, list]], whitelist: Sequence[Any] ) -> List[tuple[str, list]]: """ Returns filtered list of elements based on whitelist dict_elements must be the dictionary representation of whats stored in data without any modifications """ filtered_elements_dict = {} for collection_name, elements in dict_elements.items(): if not isinstance(elements, list): continue # Get the actual element corresponding to the dict representation for i, element_dict in enumerate(elements): element_collection = getattr(data, collection_name) element = element_collection[i] if element not in whitelist: continue filtered_elements_dict.setdefault(collection_name, []).append(element_dict) return filtered_elements_dict
Returns filtered list of elements based on whitelist dict_elements must be the dictionary representation of whats stored in data without any modifications
20,163
from bpy.types import Operator from bpy.props import BoolProperty, StringProperty from bpy.utils import register_class, unregister_class from ..declarations import Operators from ..utilities.view import refresh class View3D_OT_slvs_batch_set(Operator): """Batch set a property on all items in a given sequence""" bl_idname = Operators.BatchSet bl_label = "Batch Set" bl_options = {"UNDO"} data_path: StringProperty( name="Data Path", description="Data path to resolve from the context e.g. 'context.scene'", ) sequence: StringProperty(name="Sequence") property: StringProperty(name="Property") value: BoolProperty(name="Value") def execute(self, context): data_path = context.path_resolve(self.data_path) for entity in getattr(data_path, self.sequence): setattr(entity, self.property, self.value) refresh(context) return {"FINISHED"} def register(): register_class(View3D_OT_slvs_batch_set)
null
20,164
from bpy.types import Operator from bpy.props import BoolProperty, StringProperty from bpy.utils import register_class, unregister_class from ..declarations import Operators from ..utilities.view import refresh class View3D_OT_slvs_batch_set(Operator): def execute(self, context): def unregister(): unregister_class(View3D_OT_slvs_batch_set)
null
20,165
import bpy import gpu from bpy.types import Operator, Context from bpy.utils import register_classes_factory from .. import global_data from ..declarations import Operators def write_selection_buffer_image(image_name: str): offscreen = global_data.offscreen width, height = offscreen.width, offscreen.height with offscreen.bind(): fb = gpu.state.active_framebuffer_get() buffer = fb.read_color(0, 0, width, height, 4, 0, "FLOAT") buffer.dimensions = width * height * 4 if image_name not in bpy.data.images: bpy.data.images.new(image_name, width, height) image = bpy.data.images[image_name] image.scale(width, height) image.pixels = buffer return image
null
20,166
import logging import math from bpy.types import Operator, Context from bpy.props import FloatProperty from ..model.categories import SEGMENT from ..model.identifiers import is_line, is_circle from ..declarations import Operators from ..stateful_operator.utilities.register import register_stateops_factory from ..stateful_operator.state import state_from_args from ..utilities.view import refresh from ..utilities.walker import EntityWalker from ..utilities.intersect import get_offset_elements, get_intersections from ..model.utilities import get_connection_point from .base_2d import Operator2d from .utilities import ignore_hover def _get_offset_co(point, normal, distance): # For start or endpoint: get point translated by distance along normal return point.co + normal * distance
null
20,167
import logging import math from bpy.types import Operator, Context from bpy.props import FloatProperty from ..model.categories import SEGMENT from ..model.identifiers import is_line, is_circle from ..declarations import Operators from ..stateful_operator.utilities.register import register_stateops_factory from ..stateful_operator.state import state_from_args from ..utilities.view import refresh from ..utilities.walker import EntityWalker from ..utilities.intersect import get_offset_elements, get_intersections from ..model.utilities import get_connection_point from .base_2d import Operator2d from .utilities import ignore_hover def _bool_to_signed_int(invert): return -1 if invert else 1 def _inverted_dist(invert, distance): sign = _bool_to_signed_int(invert) * _bool_to_signed_int(distance < 0) return math.copysign(distance, sign)
null
20,168
from bpy.types import Operator, Context, Event from mathutils import Vector from bpy.props import FloatVectorProperty from ..declarations import Operators from .base_2d import Operator2d from ..stateful_operator.state import state_from_args from ..stateful_operator.utilities.register import register_stateops_factory from ..utilities.data_handling import get_flat_deps from ..solver import solve_system from ..utilities.view import get_pos_2d def get_flat_deps(entity: SlvsGenericEntity): """Return flattened list of entities given entity depends on""" list = [] def walker(entity, is_root=False): if entity in list: return if not is_root: list.append(entity) if not hasattr(entity, "dependencies"): return for e in entity.dependencies(): if e in list: continue walker(e) walker(entity, is_root=True) return list The provided code snippet includes necessary dependencies for implementing the `get_points` function. Write a Python function `def get_points(context: Context)` to solve the following problem: Return a list of points that are either selected or a dependency of a selected entity Here is the function: def get_points(context: Context): """Return a list of points that are either selected or a dependency of a selected entity""" entities = context.scene.sketcher.entities.selected_active points = [] def add(p): if p in points: return points.append(p) def is_point2d(e): if not e.is_2d(): return False if not e.is_point(): return False return True for entity in entities: if not entity: continue if is_point2d(entity): add(entity) continue dependencies = get_flat_deps(entity) for e in dependencies: if not is_point2d(e): continue add(e) return points
Return a list of points that are either selected or a dependency of a selected entity
20,169
import bpy from bpy.types import Operator from .. import global_data from ..declarations import Operators from ..utilities.install import check_module from ..utilities.install import install_package, ensure_pip, show_package_info class View3D_OT_slvs_install_package(Operator): """Install module from local .whl file or from PyPi""" bl_idname = Operators.InstallPackage bl_label = "Install" package: bpy.props.StringProperty(subtype="FILE_PATH") def poll(cls, context): return not global_data.registered def execute(self, context): if not ensure_pip(): self.report( {"WARNING"}, "PIP is not available and cannot be installed, please install PIP manually", ) return {"CANCELLED"} if not self.package: self.report({"WARNING"}, "Specify package to be installed") return {"CANCELLED"} if install_package(self.package): try: check_module("py_slvs") from ..registration import register_full register_full() self.report({"INFO"}, "Package successfully installed") except ModuleNotFoundError: msg = """Package should be available but cannot be found, check console for detailed info. Try restarting blender, otherwise get in contact.""" self.report( {"WARNING"}, msg, ) show_package_info("py_slvs") else: self.report({"WARNING"}, "Cannot install package: {}".format(self.package)) return {"CANCELLED"} return {"FINISHED"} def register(): bpy.utils.register_class(View3D_OT_slvs_install_package)
null
20,170
import bpy from bpy.types import Operator from .. import global_data from ..declarations import Operators from ..utilities.install import check_module from ..utilities.install import install_package, ensure_pip, show_package_info class View3D_OT_slvs_install_package(Operator): """Install module from local .whl file or from PyPi""" bl_idname = Operators.InstallPackage bl_label = "Install" package: bpy.props.StringProperty(subtype="FILE_PATH") def poll(cls, context): return not global_data.registered def execute(self, context): if not ensure_pip(): self.report( {"WARNING"}, "PIP is not available and cannot be installed, please install PIP manually", ) return {"CANCELLED"} if not self.package: self.report({"WARNING"}, "Specify package to be installed") return {"CANCELLED"} if install_package(self.package): try: check_module("py_slvs") from ..registration import register_full register_full() self.report({"INFO"}, "Package successfully installed") except ModuleNotFoundError: msg = """Package should be available but cannot be found, check console for detailed info. Try restarting blender, otherwise get in contact.""" self.report( {"WARNING"}, msg, ) show_package_info("py_slvs") else: self.report({"WARNING"}, "Cannot install package: {}".format(self.package)) return {"CANCELLED"} return {"FINISHED"} def unregister(): bpy.utils.unregister_class(View3D_OT_slvs_install_package)
null
20,171
import bpy from bpy.props import PointerProperty, FloatVectorProperty, FloatProperty from bpy.types import PropertyGroup def update(self, context): for window in context.window_manager.windows: for area in window.screen.areas: if area.type != "VIEW_3D": continue area.tag_redraw() area.spaces[0].show_gizmo = True
null
20,172
import bpy from bpy.props import PointerProperty, FloatVectorProperty, FloatProperty from bpy.types import PropertyGroup class ThemeSettingsEntity(PropertyGroup): default: FloatVectorProperty( name="Default", subtype="COLOR", default=(0, 0, 0, 0.8), size=4, min=0.0, max=1.0, update=update, ) highlight: FloatVectorProperty( name="Highlight", subtype="COLOR", default=(0.65, 0.65, 0.65, 0.5), size=4, min=0.0, max=1.0, update=update, ) selected: FloatVectorProperty( name="Selected", subtype="COLOR", default=(0.9, 0.582, 0.29, 0.7), size=4, min=0.0, max=1.0, update=update, ) selected_highlight: FloatVectorProperty( name="Selected Highlight", subtype="COLOR", default=(1.0, 0.647, 0.322, 0.95), size=4, min=0.0, max=1.0, update=update, ) inactive: FloatVectorProperty( name="Inactive", subtype="COLOR", default=(0, 0, 0, 0.4), size=4, min=0.0, max=1.0, update=update, ) inactive_selected: FloatVectorProperty( name="Inactive Selected", subtype="COLOR", default=(0.9, 0.582, 0.29, 0.2), size=4, min=0.0, max=1.0, update=update, ) fixed: FloatVectorProperty( name="Fixed", subtype="COLOR", default=(0.0, 0.55, 0.0, 0.7), size=4, min=0.0, max=1.0, update=update, ) class ThemeSettingsConstraint(PropertyGroup): default: FloatVectorProperty( name="Default", subtype="COLOR", default=(0.90, 0.54, 0.54, 0.7), size=4, min=0.0, max=1.0, update=update, ) highlight: FloatVectorProperty( name="Highlight", subtype="COLOR", default=(1.0, 0.6, 0.6, 0.95), size=4, min=0.0, max=1.0, update=update, ) failed: FloatVectorProperty( name="Failed", subtype="COLOR", default=(0.95, 0.0, 0.0, 0.8), size=4, min=0.0, max=1.0, update=update, ) failed_highlight: FloatVectorProperty( name="Failed Highlight", subtype="COLOR", default=(0.0, 0.55, 0.0, 0.7), size=4, min=0.0, max=1.0, update=update, ) reference: FloatVectorProperty( name="Reference Measurement", subtype="COLOR", default=(0.5, 0.5, 1.0, 0.7), size=4, min=0.0, max=1.0, update=update, ) reference_highlight: FloatVectorProperty( name="Reference Highlight", subtype="COLOR", default=(0.6, 0.6, 1.0, 0.95), size=4, min=0.0, max=1.0, update=update, ) text: FloatVectorProperty( name="Text", subtype="COLOR", default=(0.90, 0.90, 0.90, 1.0), size=4, min=0.0, max=1.0, update=update, ) text_highlight: FloatVectorProperty( name="Text Highlight", subtype="COLOR", default=(1.0, 1.0, 1.0, 1.0), size=4, min=0.0, max=1.0, update=update, ) class ThemeSettings(PropertyGroup): entity: PointerProperty(name="Entity", type=ThemeSettingsEntity) constraint: PointerProperty(name="Constraint", type=ThemeSettingsConstraint) def register(): bpy.utils.register_class(ThemeSettingsEntity) bpy.utils.register_class(ThemeSettingsConstraint) bpy.utils.register_class(ThemeSettings)
null
20,173
import bpy from bpy.props import PointerProperty, FloatVectorProperty, FloatProperty from bpy.types import PropertyGroup class ThemeSettingsEntity(PropertyGroup): class ThemeSettingsConstraint(PropertyGroup): class ThemeSettings(PropertyGroup): def unregister(): bpy.utils.unregister_class(ThemeSettings) bpy.utils.unregister_class(ThemeSettingsConstraint) bpy.utils.unregister_class(ThemeSettingsEntity)
null
20,174
import sys from pathlib import Path import logging import bpy from bpy.types import AddonPreferences, Panel, Menu from bl_ui.utils import PresetPanel from bpy.props import ( PointerProperty, BoolProperty, StringProperty, EnumProperty, IntProperty, FloatProperty, ) from . import theme from .. import global_data, units from ..declarations import Operators from ..utilities.register import get_path, get_name from ..utilities.view import update_cb def get_log_level(self): prop = self.bl_rna.properties["logging_level"] items = prop.enum_items default_value = items[prop.default].value item = items[self.get("logging_level", default_value)] return item.value
null
20,175
import sys from pathlib import Path import logging import bpy from bpy.types import AddonPreferences, Panel, Menu from bl_ui.utils import PresetPanel from bpy.props import ( PointerProperty, BoolProperty, StringProperty, EnumProperty, IntProperty, FloatProperty, ) from . import theme from .. import global_data, units from ..declarations import Operators from ..utilities.register import get_path, get_name from ..utilities.view import update_cb logger = logging.getLogger(__name__) def set_log_level(self, value): items = self.bl_rna.properties["logging_level"].enum_items item = items[value] level = item.identifier logger.info("setting log level: {}".format(item.name)) self["logging_level"] = level logger.setLevel(level)
null
20,176
import sys from pathlib import Path import logging import bpy from bpy.types import AddonPreferences, Panel, Menu from bl_ui.utils import PresetPanel from bpy.props import ( PointerProperty, BoolProperty, StringProperty, EnumProperty, IntProperty, FloatProperty, ) from . import theme from .. import global_data, units from ..declarations import Operators from ..utilities.register import get_path, get_name from ..utilities.view import update_cb logger = logging.getLogger(__name__) def get_wheel(): p = Path(__file__).parent.absolute() from sys import platform, version_info if platform == "linux" or platform == "linux2": # Linux platform_strig = "linux" elif platform == "darwin": # OS X platform_strig = "macosx" elif platform == "win32": # Windows platform_strig = "win" matches = list( p.glob( "**/*cp{}{}*{}*.whl".format( version_info.major, version_info.minor, platform_strig ) ) ) if matches: match = matches[0] logger.info("Local installation file available: " + str(match)) return match.as_posix() return ""
null
20,177
import sys from pathlib import Path import logging import bpy from bpy.types import AddonPreferences, Panel, Menu from bl_ui.utils import PresetPanel from bpy.props import ( PointerProperty, BoolProperty, StringProperty, EnumProperty, IntProperty, FloatProperty, ) from . import theme from .. import global_data, units from ..declarations import Operators from ..utilities.register import get_path, get_name from ..utilities.view import update_cb classes = ( SKETCHER_MT_theme_presets, SKETCHER_PT_theme_presets, Preferences, ) def register(): from bpy.utils import register_class for cls in classes: register_class(cls)
null
20,178
import sys from pathlib import Path import logging import bpy from bpy.types import AddonPreferences, Panel, Menu from bl_ui.utils import PresetPanel from bpy.props import ( PointerProperty, BoolProperty, StringProperty, EnumProperty, IntProperty, FloatProperty, ) from . import theme from .. import global_data, units from ..declarations import Operators from ..utilities.register import get_path, get_name from ..utilities.view import update_cb classes = ( SKETCHER_MT_theme_presets, SKETCHER_PT_theme_presets, Preferences, ) def unregister(): from bpy.utils import unregister_class for cls in reversed(classes): unregister_class(cls)
null
20,179
import pickle from typing import Union, Optional from pathlib import Path from bpy.types import Scene from .utilities.index import breakdown_index, assemble_index def scene_to_dict(scene): original = scene["sketcher"].to_dict() elements = {key: original[key] for key in ("entities", "constraints")} return elements The provided code snippet includes necessary dependencies for implementing the `save` function. Write a Python function `def save(file: Union[str, Path], scene: Optional[Scene] = None)` to solve the following problem: Saves CAD Sketcher data of scene into file Here is the function: def save(file: Union[str, Path], scene: Optional[Scene] = None): """Saves CAD Sketcher data of scene into file""" if not scene: import bpy scene = bpy.context.scene with open(file, "wb") as picklefile: pickler = pickle.Pickler(picklefile) # Convert to dict to avoid pickling PropertyGroup instances dict = scene_to_dict(scene) pickler.dump(dict) picklefile.close()
Saves CAD Sketcher data of scene into file
20,180
import pickle from typing import Union, Optional from pathlib import Path from bpy.types import Scene from .utilities.index import breakdown_index, assemble_index def scene_from_dict(scene, elements): original = scene["sketcher"].to_dict() original.update(elements) scene["sketcher"].update(original) The provided code snippet includes necessary dependencies for implementing the `load` function. Write a Python function `def load(file: Union[str, Path], scene: Optional[Scene] = None)` to solve the following problem: Overwrites scene with entities and constraints stored in file Here is the function: def load(file: Union[str, Path], scene: Optional[Scene] = None): """Overwrites scene with entities and constraints stored in file""" if not scene: import bpy scene = bpy.context.scene with open(file, "rb") as picklefile: unpickler = pickle.Unpickler(picklefile) load_dict = unpickler.load() scene_from_dict(scene, load_dict)
Overwrites scene with entities and constraints stored in file
20,181
import pickle from typing import Union, Optional from pathlib import Path from bpy.types import Scene from .utilities.index import breakdown_index, assemble_index def scene_from_dict(scene, elements): original = scene["sketcher"].to_dict() original.update(elements) scene["sketcher"].update(original) def _extend_element_dict(scene, elements): """Returns dictionary representation of scene with extended entities and constraints""" scene_dict = scene_to_dict(scene) fix_pointers(elements) for key in ("entities", "constraints"): dict_extend(scene_dict[key], elements[key]) return scene_dict def paste(context, dictionary): scene = context.scene final_dict = _extend_element_dict( scene, { "entities": dictionary["entities"], "constraints": dictionary["constraints"], }, ) scene_from_dict(scene, final_dict)
null
20,182
from typing import Union, Type from .group_entities import type_from_index from .categories import POINT, SEGMENT, LINE, CURVE, ELEMENT_2D from .types import SlvsSketch, SlvsCircle, SlvsGenericEntity EntityRef = Union[SlvsGenericEntity, int] def is_2d(entity: EntityRef) -> bool: def is_3d(entity: EntityRef) -> bool: return not is_2d(entity)
null
20,183
from typing import Union, Type from .group_entities import type_from_index from .categories import POINT, SEGMENT, LINE, CURVE, ELEMENT_2D from .types import SlvsSketch, SlvsCircle, SlvsGenericEntity EntityRef = Union[SlvsGenericEntity, int] def _get_type(value: EntityRef) -> Type[SlvsGenericEntity]: index = value if isinstance(value, int) else value.slvs_index return type_from_index(index) POINT = (*POINT3D, *POINT2D) def is_point(entity: EntityRef) -> bool: return _get_type(entity) in POINT
null
20,184
from typing import Union, Type from .group_entities import type_from_index from .categories import POINT, SEGMENT, LINE, CURVE, ELEMENT_2D from .types import SlvsSketch, SlvsCircle, SlvsGenericEntity EntityRef = Union[SlvsGenericEntity, int] def _get_type(value: EntityRef) -> Type[SlvsGenericEntity]: index = value if isinstance(value, int) else value.slvs_index return type_from_index(index) LINE = (SlvsLine3D, SlvsLine2D) def is_line(entity: EntityRef) -> bool: return _get_type(entity) in LINE
null
20,185
from typing import Union, Type from .group_entities import type_from_index from .categories import POINT, SEGMENT, LINE, CURVE, ELEMENT_2D from .types import SlvsSketch, SlvsCircle, SlvsGenericEntity EntityRef = Union[SlvsGenericEntity, int] def _get_type(value: EntityRef) -> Type[SlvsGenericEntity]: index = value if isinstance(value, int) else value.slvs_index return type_from_index(index) CURVE = (SlvsCircle, SlvsArc) def is_curve(entity: EntityRef) -> bool: return _get_type(entity) in CURVE
null
20,186
from typing import Union, Type from .group_entities import type_from_index from .categories import POINT, SEGMENT, LINE, CURVE, ELEMENT_2D from .types import SlvsSketch, SlvsCircle, SlvsGenericEntity EntityRef = Union[SlvsGenericEntity, int] def _get_type(value: EntityRef) -> Type[SlvsGenericEntity]: index = value if isinstance(value, int) else value.slvs_index return type_from_index(index) SEGMENT = (*LINE, *CURVE) def is_segment(entity: EntityRef) -> bool: return _get_type(entity) in SEGMENT
null