Draft: make move, rotate and scale commands link-aware (#18795)

* Draft: make move, rotate and scale commands link-aware

Fixes #12836.
Fixes #15681.

These changes are presented as a single ('big') PR because the mentioned commands have several similarities. Working on them seperately would have made less sense.

The commands have been made 'link-aware' meaning they can now handle Links and objects in linked containers.

This required several changes in the following main files. For each command all options are handled by a single function now (the `move`, `rotate` and `scale` functions). This was the only reasonable solution to correctly handle nested placements. As a result there is no longer a need to build very complex 'cmd' strings in the gui_*.py files (which is a good thing IMO).

Main files:

* move.py
* rotate.py
* scale.py
* gui_move.py
* gui_rotate.py
* gui_scale.py
* gui_trackers.py

The following files have also been updated:

* Draft.py: Imports updated.
* DraftGui.py: If `CopyMode` is changed the ghosts have to be updated. The move and rotate commands now also show previews of movable children. But since those are not copied they should be removed from the ghosts if `CopyMode` is changed to `True`.
* utils.py: Some helper functions have been added. An existing helper function (only used internally) has been renamed.
* gui_utils.py: The `select` function has been updated to accept a list of tuples to allow the reselection of nested objects.
* clone.py: A new property `ForceCompound`, necessary for non-uniform scaling, has been added.
* join.py: The `join_wires` function now returns the resultant wire objects.
* task_scale.py: Updated to allow negative scale factors. Support for `SubelementMode` preference added.
* dimension.py: `transform` methods added.
* layer.py: `get_layer` function added.
* svg.py: Updated to use `get_layer`.
* view_text.py: Instead of two added `coin.SoTransform()` nodes the main transform node is used instead. This was done so that ghosts of Draft Texts can be handled properly without requiring dedicated code in gui_trackers.py.

Notes:

* Support for "App::Annotation" is limited. Only their `Position` is handled (by the move and rotate commands).
* Support for "Image::ImagePlane" has been removed from the scale command. The object has its own calibrate feature (see https://wiki.freecad.org/Std_Import).
* Copies and clones are always created in the global space.

* Fix several unit test issues.

* Reset value that was changed while testing

* Rebase and update test_modification.py

* Reintroduce scaling of image planes
This commit is contained in:
Roy-043
2025-01-20 18:23:36 +01:00
committed by GitHub
parent 8d46ba6414
commit d587e6a91a
19 changed files with 1042 additions and 973 deletions

View File

@@ -34,6 +34,7 @@ import DraftVecUtils
def join_wires(wires, joinAttempts = 0):
"""join_wires(objects): merges a set of wires where possible, if any of those
wires have a coincident start and end point"""
wires = list(wires)
if joinAttempts > len(wires):
return
joinAttempts += 1
@@ -45,6 +46,7 @@ def join_wires(wires, joinAttempts = 0):
wires.pop(wire2Index)
break
join_wires(wires, joinAttempts)
return wires
joinWires = join_wires

View File

@@ -2,6 +2,7 @@
# * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * Copyright (c) 2020 FreeCAD Developers *
# * Copyright (c) 2024 The FreeCAD Project Association *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
@@ -31,62 +32,82 @@ import FreeCAD as App
from draftfunctions import join
from draftmake import make_copy
from draftmake import make_line
from draftutils import groups
from draftobjects import layer
from draftutils import gui_utils
from draftutils import params
from draftutils import utils
def move(objectslist, vector, copy=False):
"""move(objects,vector,[copy])
def move(selection, vector, copy=False, subelements=False):
"""move(selection, vector, [copy], [subelements])
Move the objects contained in objects (that can be an object or a
list of objects) in the direction and distance indicated by the given
vector.
Moves or copies selected objects.
Parameters
----------
objectslist : list
selection: single object / list of objects / selection set
When dealing with nested objects, use `Gui.Selection.getSelectionEx("", 0)`
to create the selection set.
vector : Base.Vector
Delta Vector to move the clone from the original position.
vector: App.Vector
Delta vector.
copy : bool
If copy is True, the actual objects are not moved, but copies
are created instead.
copy: bool, optional
Defaults to `False`.
If `True` the selected objects are not moved, but moved copies are
created instead.
Return
----------
The objects (or their copies) are returned.
subelements: bool, optional
Defaults to `False`.
If `True` subelements instead of whole objects are processed.
Only used if selection is a selection set.
Returns
-------
single object / list with 2 or more objects / empty list
The objects (or their copies)
"""
utils.type_check([(vector, App.Vector), (copy,bool)], "move")
if not isinstance(objectslist, list):
objectslist = [objectslist]
utils.type_check([(vector, App.Vector), (copy, bool), (subelements, bool)], "move")
if not isinstance(selection, list):
selection = [selection]
if not selection:
return None
objectslist.extend(groups.get_movable_children(objectslist))
newobjlist = []
if selection[0].isDerivedFrom("Gui::SelectionObject"):
if subelements:
return _move_subelements(selection, vector, copy)
else:
objs, parent_places, sel_info = utils._modifiers_process_selection(selection, copy)
else:
objs = utils._modifiers_filter_objects(utils._modifiers_get_group_contents(selection), copy)
parent_places = None
sel_info = None
if not objs:
return None
newobjs = []
newgroups = {}
objectslist = utils.filter_objects_for_modifiers(objectslist, copy)
if copy:
doc = App.ActiveDocument
for obj in objectslist:
if obj.isDerivedFrom("App::DocumentObjectGroup") \
and obj.Name not in newgroups:
newgroups[obj.Name] = doc.addObject(obj.TypeId,
utils.get_real_name(obj.Name))
for obj in objs:
if obj.isDerivedFrom("App::DocumentObjectGroup") and obj.Name not in newgroups:
newgroups[obj.Name] = obj.Document.addObject(obj.TypeId, utils.get_real_name(obj.Name))
for obj in objectslist:
for idx, obj in enumerate(objs):
newobj = None
# real_vector have been introduced to take into account
# the possibility that object is inside an App::Part
# TODO: Make Move work also with App::Link
if hasattr(obj, "getGlobalPlacement"):
v_minus_global = obj.getGlobalPlacement().inverse().Rotation.multVec(vector)
real_vector = obj.Placement.Rotation.multVec(v_minus_global)
if parent_places is not None:
parent_place = parent_places[idx]
elif hasattr(obj, "getGlobalPlacement"):
parent_place = obj.getGlobalPlacement() * obj.Placement.inverse()
else:
parent_place = App.Placement()
if copy or parent_place.isIdentity():
real_vector = vector
else:
real_vector = parent_place.inverse().Rotation.multVec(vector)
if obj.isDerivedFrom("App::DocumentObjectGroup"):
if copy:
@@ -94,121 +115,127 @@ def move(objectslist, vector, copy=False):
else:
newobj = obj
elif hasattr(obj, "Shape"):
elif hasattr(obj, "Placement"):
if copy:
newobj = make_copy.make_copy(obj)
if not parent_place.isIdentity():
newobj.Placement = parent_place * newobj.Placement
else:
newobj = obj
pla = newobj.Placement
pla.move(real_vector)
newobj.Placement.move(real_vector)
elif obj.isDerivedFrom("App::Annotation"):
if copy:
newobj = make_copy.make_copy(obj)
if not parent_place.isIdentity():
newobj.Position = parent_place.multVec(newobj.Position)
else:
newobj = obj
newobj.Position = obj.Position.add(real_vector)
newobj.Position = newobj.Position.add(real_vector)
elif utils.get_type(obj) in ["Text", "DraftText"]:
elif utils.get_type(obj) in ("Dimension", "LinearDimension", "AngularDimension"):
# "Dimension" was the type for linear dimensions <= v0.18.
if copy:
newobj = make_copy.make_copy(obj)
if not parent_place.isIdentity():
newobj.Proxy.transform(newobj, parent_place)
else:
newobj = obj
newobj.Placement.Base = obj.Placement.Base.add(real_vector)
elif utils.get_type(obj) in ["Dimension", "LinearDimension"]:
if copy:
newobj = make_copy.make_copy(obj)
else:
newobj = obj
newobj.Start = obj.Start.add(real_vector)
newobj.End = obj.End.add(real_vector)
newobj.Dimline = obj.Dimline.add(real_vector)
elif utils.get_type(obj) == "AngularDimension":
if copy:
newobj = make_copy.make_copy(obj)
else:
newobj = obj
newobj.Center = obj.Center.add(real_vector)
newobj.Dimline = obj.Dimline.add(real_vector)
elif hasattr(obj, "Placement"):
if copy:
newobj = make_copy.make_copy(obj)
else:
newobj = obj
pla = newobj.Placement
pla = App.Placement()
pla.move(real_vector)
newobj.Proxy.transform(newobj, pla)
if newobj is not None:
newobjlist.append(newobj)
newobjs.append(newobj)
if copy:
lyr = layer.get_layer(obj)
if lyr is not None:
lyr.Proxy.addObject(lyr, newobj)
for parent in obj.InList:
if parent.isDerivedFrom("App::DocumentObjectGroup") \
and (parent in objectslist):
if parent.isDerivedFrom("App::DocumentObjectGroup") and (parent in objs):
newgroups[parent.Name].addObject(newobj)
if utils.get_type(parent) == "Layer":
parent.Proxy.addObject(parent ,newobj)
if copy and params.get_param("selectBaseObjects"):
gui_utils.select(objectslist)
if not copy or params.get_param("selectBaseObjects"):
if sel_info is not None:
gui_utils.select(sel_info)
else:
gui_utils.select(objs)
else:
gui_utils.select(newobjlist)
gui_utils.select(newobjs)
if len(newobjlist) == 1:
return newobjlist[0]
return newobjlist
if len(newobjs) == 1:
return newobjs[0]
return newobjs
# Following functions are needed for SubObjects modifiers
# implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire)
def move_vertex(object, vertex_index, vector):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
vector = object.getGlobalPlacement().inverse().Rotation.multVec(vector)
points = object.Points
points[vertex_index] = points[vertex_index].add(vector)
object.Points = points
def move_edge(object, edge_index, vector):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
move_vertex(object, edge_index, vector)
if utils.is_closed_edge(edge_index, object):
move_vertex(object, 0, vector)
def _move_subelements(selection, vector, copy):
data_list, sel_info = utils._modifiers_process_subselection(selection, copy)
newobjs = []
if copy:
for obj, vert_idx, edge_idx, global_place in data_list:
if edge_idx >= 0:
newobjs.append(copy_moved_edge(obj, edge_idx, vector, global_place))
newobjs = join.join_wires(newobjs)
else:
move_vertex(object, edge_index+1, vector)
for obj, vert_idx, edge_idx, global_place in data_list:
if vert_idx >= 0:
move_vertex(obj, vert_idx, vector, global_place)
elif edge_idx >= 0:
move_edge(obj, edge_idx, vector, global_place)
def copy_moved_edges(arguments):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
copied_edges = []
for argument in arguments:
copied_edges.append(copy_moved_edge(argument[0], argument[1], argument[2]))
join.join_wires(copied_edges)
def copy_moved_edge(object, edge_index, vector):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
vertex1 = object.getGlobalPlacement().multVec(object.Points[edge_index]).add(vector)
if utils.is_closed_edge(edge_index, object):
vertex2 = object.getGlobalPlacement().multVec(object.Points[0]).add(vector)
if not copy or params.get_param("selectBaseObjects"):
gui_utils.select(sel_info)
else:
vertex2 = object.getGlobalPlacement().multVec(object.Points[edge_index+1]).add(vector)
return make_line.make_line(vertex1, vertex2)
gui_utils.select(newobjs)
if len(newobjs) == 1:
return newobjs[0]
return newobjs
def move_vertex(obj, vert_idx, vector, global_place=None):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
if global_place is None:
glp = obj.getGlobalPlacement()
else:
glp = global_place
vector = glp.inverse().Rotation.multVec(vector)
points = obj.Points
points[vert_idx] = points[vert_idx].add(vector)
obj.Points = points
def move_edge(obj, edge_idx, vector, global_place=None):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
move_vertex(obj, edge_idx, vector, global_place)
if utils.is_closed_edge(edge_idx, obj):
move_vertex(obj, 0, vector, global_place)
else:
move_vertex(obj, edge_idx+1, vector, global_place)
def copy_moved_edge(obj, edge_idx, vector, global_place=None):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
if global_place is None:
glp = obj.getGlobalPlacement()
else:
glp = global_place
vertex1 = glp.multVec(obj.Points[edge_idx]).add(vector)
if utils.is_closed_edge(edge_idx, obj):
vertex2 = glp.multVec(obj.Points[0]).add(vector)
else:
vertex2 = glp.multVec(obj.Points[edge_idx+1]).add(vector)
newobj = make_line.make_line(vertex1, vertex2)
gui_utils.format_object(newobj, obj)
return newobj
## @}

View File

@@ -2,6 +2,7 @@
# * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * Copyright (c) 2020 FreeCAD Developers *
# * Copyright (c) 2024 The FreeCAD Project Association *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
@@ -34,152 +35,178 @@ import DraftVecUtils
from draftfunctions import join
from draftmake import make_copy
from draftmake import make_line
from draftobjects import layer
from draftutils import groups
from draftutils import gui_utils
from draftutils import params
from draftutils import utils
def rotate(objectslist, angle, center=App.Vector(0, 0, 0),
axis=App.Vector(0, 0, 1), copy=False):
"""rotate(objects,angle,[center,axis,copy])
def rotate(selection, angle, center=App.Vector(0, 0, 0),
axis=App.Vector(0, 0, 1), copy=False, subelements=False):
"""rotate(selection, angle, [center], [axis], [copy], [subelements])
Rotates the objects contained in objects (that can be a list of objects
or an object) of the given angle (in degrees) around the center, using
axis as a rotation axis.
Rotates or copies selected objects.
Parameters
----------
objectslist : list
selection: single object / list of objects / selection set
When dealing with nested objects, use `Gui.Selection.getSelectionEx("", 0)`
to create the selection set.
angle : rotation angle (in degrees)
angle: float / integer
Rotation angle (in degrees).
center : Base.Vector
center: App.Vector, optional
Defaults to `App.Vector(0, 0, 0)`.
Rotation center.
axis : Base.Vector
If axis is omitted, the rotation will be around the vertical Z axis.
axis: App.Vector, optional
Defaults to `App.Vector(0, 0, 1)`.
Rotation axis.
copy : bool
If copy is True, the actual objects are not moved, but copies
are created instead.
copy: bool, optional
Defaults to `False`.
If `True` the selected objects are not rotated, but rotated copies are
created instead.
Return
----------
The objects (or their copies) are returned.
subelements: bool, optional
Defaults to `False`.
If `True` subelements instead of whole objects are processed.
Only used if selection is a selection set.
Returns
-------
single object / list with 2 or more objects / empty list
The objects (or their copies).
"""
import Part
utils.type_check([(copy,bool)], "rotate")
if not isinstance(objectslist,list):
objectslist = [objectslist]
utils.type_check([(angle, (float, int)), (center, App.Vector),
(axis, App.Vector), (copy, bool), (subelements, bool)], "rotate")
if not isinstance(selection, list):
selection = [selection]
if not selection:
return None
objectslist.extend(groups.get_movable_children(objectslist))
newobjlist = []
if selection[0].isDerivedFrom("Gui::SelectionObject"):
if subelements:
return _rotate_subelements(selection, angle, center, axis, copy)
else:
objs, parent_places, sel_info = utils._modifiers_process_selection(selection, copy)
else:
objs = utils._modifiers_filter_objects(utils._modifiers_get_group_contents(selection), copy)
parent_places = None
sel_info = None
if not objs:
return None
newobjs = []
newgroups = {}
objectslist = utils.filter_objects_for_modifiers(objectslist, copy)
if copy:
doc = App.ActiveDocument
for obj in objectslist:
if obj.isDerivedFrom("App::DocumentObjectGroup") \
and obj.Name not in newgroups:
newgroups[obj.Name] = doc.addObject(obj.TypeId,
utils.get_real_name(obj.Name))
for obj in objs:
if obj.isDerivedFrom("App::DocumentObjectGroup") and obj.Name not in newgroups:
newgroups[obj.Name] = obj.Document.addObject(obj.TypeId, utils.get_real_name(obj.Name))
for obj in objectslist:
for idx, obj in enumerate(objs):
newobj = None
# real_center and real_axis are introduced to take into account
# the possibility that object is inside an App::Part
if hasattr(obj, "getGlobalPlacement"):
ci = obj.getGlobalPlacement().inverse().multVec(center)
real_center = obj.Placement.multVec(ci)
ai = obj.getGlobalPlacement().inverse().Rotation.multVec(axis)
real_axis = obj.Placement.Rotation.multVec(ai)
if parent_places is not None:
parent_place = parent_places[idx]
elif hasattr(obj, "getGlobalPlacement"):
parent_place = obj.getGlobalPlacement() * obj.Placement.inverse()
else:
parent_place = App.Placement()
if copy or parent_place.isIdentity():
real_center = center
real_axis = axis
else:
real_center = parent_place.inverse().multVec(center)
real_axis = parent_place.inverse().Rotation.multVec(axis)
if obj.isDerivedFrom("App::Annotation"):
# TODO: this is very different from how move handle annotations
# maybe we can uniform the two methods
if copy:
newobj = make_copy.make_copy(obj)
else:
newobj = obj
if axis.normalize() == App.Vector(1, 0, 0):
newobj.ViewObject.RotationAxis = "X"
newobj.ViewObject.Rotation = angle
elif axis.normalize() == App.Vector(0, 1, 0):
newobj.ViewObject.RotationAxis = "Y"
newobj.ViewObject.Rotation = angle
elif axis.normalize() == App.Vector(0, -1, 0):
newobj.ViewObject.RotationAxis = "Y"
newobj.ViewObject.Rotation = -angle
elif axis.normalize() == App.Vector(0, 0, 1):
newobj.ViewObject.RotationAxis = "Z"
newobj.ViewObject.Rotation = angle
elif axis.normalize() == App.Vector(0, 0, -1):
newobj.ViewObject.RotationAxis = "Z"
newobj.ViewObject.Rotation = -angle
elif obj.isDerivedFrom("App::DocumentObjectGroup"):
if obj.isDerivedFrom("App::DocumentObjectGroup"):
if copy:
newobj = newgroups[obj.Name]
else:
newobj = obj
elif hasattr(obj, "Placement"):
# App.Console.PrintMessage("placement rotation\n")
if copy:
newobj = make_copy.make_copy(obj)
if not parent_place.isIdentity():
newobj.Placement = parent_place * newobj.Placement
else:
newobj = obj
newobj.Placement.rotate(real_center, real_axis, angle, comp=True)
elif hasattr(obj, "Shape"):
elif obj.isDerivedFrom("App::Annotation"):
if copy:
newobj = make_copy.make_copy(obj)
if not parent_place.isIdentity():
newobj.Position = parent_place.multVec(newobj.Position)
else:
newobj = obj
shape = newobj.Shape.copy()
shape.rotate(real_center, real_axis, angle)
newobj.Shape = shape
newobj.Position = rotate_vector_from_center(newobj.Position, angle, axis, center)
elif utils.get_type(obj) in ("Dimension", "LinearDimension", "AngularDimension"):
# "Dimension" was the type for linear dimensions <= v0.18.
if copy:
newobj = make_copy.make_copy(obj)
if not parent_place.isIdentity():
newobj.Proxy.transform(newobj, parent_place)
else:
newobj = obj
pla = App.Placement()
pla.rotate(real_center, real_axis, angle, comp=True)
newobj.Proxy.transform(newobj, pla)
if newobj is not None:
newobjlist.append(newobj)
newobjs.append(newobj)
if copy:
lyr = layer.get_layer(obj)
if lyr is not None:
lyr.Proxy.addObject(lyr, newobj)
for parent in obj.InList:
if parent.isDerivedFrom("App::DocumentObjectGroup") \
and (parent in objectslist):
if parent.isDerivedFrom("App::DocumentObjectGroup") and (parent in objs):
newgroups[parent.Name].addObject(newobj)
if utils.get_type(parent) == "Layer":
parent.Proxy.addObject(parent ,newobj)
if copy and params.get_param("selectBaseObjects"):
gui_utils.select(objectslist)
if not copy or params.get_param("selectBaseObjects"):
if sel_info is not None:
gui_utils.select(sel_info)
else:
gui_utils.select(objs)
else:
gui_utils.select(newobjlist)
gui_utils.select(newobjs)
if len(newobjlist) == 1:
return newobjlist[0]
return newobjlist
if len(newobjs) == 1:
return newobjs[0]
return newobjs
# Following functions are needed for SubObjects modifiers
# implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire)
def _rotate_subelements(selection, angle, center, axis, copy):
data_list, sel_info = utils._modifiers_process_subselection(selection, copy)
newobjs = []
if copy:
for obj, vert_idx, edge_idx, global_place in data_list:
if edge_idx >= 0:
newobjs.append(copy_rotated_edge(obj, edge_idx, angle, center, axis, global_place))
newobjs = join.join_wires(newobjs)
else:
for obj, vert_idx, edge_idx, global_place in data_list:
if vert_idx >= 0:
rotate_vertex(obj, vert_idx, angle, center, axis, global_place)
elif edge_idx >= 0:
rotate_edge(obj, edge_idx, angle, center, axis, global_place)
if not copy or params.get_param("selectBaseObjects"):
gui_utils.select(sel_info)
else:
gui_utils.select(newobjs)
def rotate_vertex(object, vertex_index, angle, center, axis):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
points = object.Points
points[vertex_index] = object.getGlobalPlacement().inverse().multVec(
rotate_vector_from_center(
object.getGlobalPlacement().multVec(points[vertex_index]),
angle, axis, center))
object.Points = points
if len(newobjs) == 1:
return newobjs[0]
return newobjs
def rotate_vector_from_center(vector, angle, axis, center):
@@ -192,46 +219,57 @@ def rotate_vector_from_center(vector, angle, axis, center):
return center.add(rv)
def rotate_edge(object, edge_index, angle, center, axis):
def rotate_vertex(obj, vert_idx, angle, center, axis, global_place=None):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
rotate_vertex(object, edge_index, angle, center, axis)
if utils.is_closed_edge(edge_index, object):
rotate_vertex(object, 0, angle, center, axis)
if global_place is None:
glp = obj.getGlobalPlacement()
else:
rotate_vertex(object, edge_index+1, angle, center, axis)
glp = global_place
points = obj.Points
points[vert_idx] = glp.inverse().multVec(
rotate_vector_from_center(
glp.multVec(points[vert_idx]),
angle, axis, center))
obj.Points = points
def copy_rotated_edges(arguments):
def rotate_edge(obj, edge_idx, angle, center, axis, global_place=None):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
copied_edges = []
for argument in arguments:
copied_edges.append(copy_rotated_edge(argument[0], argument[1],
argument[2], argument[3], argument[4]))
join.join_wires(copied_edges)
rotate_vertex(obj, edge_idx, angle, center, axis, global_place)
if utils.is_closed_edge(edge_idx, obj):
rotate_vertex(obj, 0, angle, center, axis, global_place)
else:
rotate_vertex(obj, edge_idx+1, angle, center, axis, global_place)
def copy_rotated_edge(object, edge_index, angle, center, axis):
def copy_rotated_edge(obj, edge_idx, angle, center, axis, global_place=None):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
if global_place is None:
glp = obj.getGlobalPlacement()
else:
glp = global_place
vertex1 = rotate_vector_from_center(
object.getGlobalPlacement().multVec(object.Points[edge_index]),
glp.multVec(obj.Points[edge_idx]),
angle, axis, center)
if utils.is_closed_edge(edge_index, object):
if utils.is_closed_edge(edge_idx, obj):
vertex2 = rotate_vector_from_center(
object.getGlobalPlacement().multVec(object.Points[0]),
glp.multVec(obj.Points[0]),
angle, axis, center)
else:
vertex2 = rotate_vector_from_center(
object.getGlobalPlacement().multVec(object.Points[edge_index+1]),
glp.multVec(obj.Points[edge_idx+1]),
angle, axis, center)
return make_line.make_line(vertex1, vertex2)
newobj = make_line.make_line(vertex1, vertex2)
gui_utils.format_object(newobj, obj)
return newobj
## @}

View File

@@ -2,6 +2,7 @@
# * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * Copyright (c) 2020 FreeCAD Developers *
# * Copyright (c) 2024 FreeCAD Project Association *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
@@ -27,132 +28,327 @@
## \addtogroup draftfunctions
# @{
import math
import FreeCAD as App
import DraftVecUtils
from draftfunctions import join
from draftmake import make_clone
from draftmake import make_copy
from draftmake import make_line
from draftmake import make_wire
from draftobjects import layer
from draftutils import gui_utils
from draftutils import params
from draftutils import utils
def scale(objectslist, scale=App.Vector(1,1,1),
center=App.Vector(0,0,0), copy=False):
"""scale(objects, scale, [center], copy)
def scale(selection, scale, center=App.Vector(0, 0, 0),
copy=False, clone=False, subelements=False):
"""scale(selection, scale, [center], [copy], [clone], [subelements])
Scales the objects contained in objects (that can be a list of objects or
an object) of the given around given center.
Scales or copies selected objects.
Parameters
----------
objectlist : list
selection: single object / list of objects / selection set
When dealing with nested objects, use `Gui.Selection.getSelectionEx("", 0)`
to create the selection set.
scale : Base.Vector
Scale factors defined by a given vector (in X, Y, Z directions).
scale: App.Vector
The X, Y and Z component of the vector define the scale factors.
objectlist : Base.Vector
center: App.Vector, optional
Defaults to `App.Vector(0, 0, 0)`.
Center of the scale operation.
copy : bool
If copy is True, the actual objects are not scaled, but copies
are created instead.
copy: bool, optional
Defaults to `False`.
If `True` the selected objects are not scaled, but scaled copies are
created instead. If clone is `True`, copy is internally set to `False`.
Return
----------
The objects (or their copies) are returned.
clone: bool, optional
Defaults to `False`.
If `True` the selected objects are not scaled, but scaled clones are
created instead.
subelements: bool, optional
Defaults to `False`.
If `True` subelements instead of whole objects are processed.
Only used if selection is a selection set.
Returns
-------
single object / list with 2 or more objects / empty list
The objects (or their copies).
"""
if not isinstance(objectslist, list):
objectslist = [objectslist]
newobjlist = []
for obj in objectslist:
if copy:
newobj = make_copy.make_copy(obj)
utils.type_check([(scale, App.Vector), (center, App.Vector),
(copy, bool), (clone, bool), (subelements, bool)], "scale")
sx, sy, sz = scale
if sx * sy * sz == 0:
raise ValueError("Zero component in scale vector")
if not isinstance(selection, list):
selection = [selection]
if not selection:
return None
if clone:
copy = False
if selection[0].isDerivedFrom("Gui::SelectionObject"):
if subelements:
return _scale_subelements(selection, scale, center, copy)
else:
newobj = obj
if hasattr(obj,'Shape'):
scaled_shape = obj.Shape.copy()
m = App.Matrix()
m.move(center.negative())
m.scale(scale.x,scale.y,scale.z)
m.move(center)
scaled_shape = scaled_shape.transformGeometry(m)
if utils.get_type(obj) == "Rectangle":
p = []
for v in scaled_shape.Vertexes:
p.append(v.Point)
pl = obj.Placement.copy()
pl.Base = p[0]
diag = p[2].sub(p[0])
bb = p[1].sub(p[0])
bh = p[3].sub(p[0])
nb = DraftVecUtils.project(diag,bb)
nh = DraftVecUtils.project(diag,bh)
if obj.Length < 0: l = -nb.Length
else: l = nb.Length
if obj.Height < 0: h = -nh.Length
else: h = nh.Length
newobj.Length = l
newobj.Height = h
tr = p[0].sub(obj.Shape.Vertexes[0].Point) # unused?
newobj.Placement = pl
elif utils.get_type(obj) == "Wire" or utils.get_type(obj) == "BSpline":
for index, point in enumerate(newobj.Points):
scale_vertex(newobj, index, scale, center)
elif hasattr(obj,'Shape'):
newobj.Shape = scaled_shape
elif hasattr(obj,"Position"):
d = obj.Position.sub(center)
newobj.Position = center.add(App.Vector(d.x * scale.x,
d.y * scale.y,
d.z * scale.z))
elif hasattr(obj,"Placement"):
d = obj.Placement.Base.sub(center)
newobj.Placement.Base = center.add(App.Vector(d.x * scale.x,
d.y * scale.y,
d.z * scale.z))
if hasattr(obj,"Height"):
obj.setExpression('Height', None)
obj.Height = obj.Height * scale.y
if hasattr(obj,"Width"):
obj.setExpression('Width', None)
obj.Width = obj.Width * scale.x
if hasattr(obj,"XSize"):
obj.setExpression('XSize', None)
obj.XSize = obj.XSize * scale.x
if hasattr(obj,"YSize"):
obj.setExpression('YSize', None)
obj.YSize = obj.YSize * scale.y
if obj.ViewObject and hasattr(obj.ViewObject,"FontSize"):
obj.ViewObject.FontSize = obj.ViewObject.FontSize * scale.y
if copy:
gui_utils.format_object(newobj,obj)
newobjlist.append(newobj)
if copy and params.get_param("selectBaseObjects"):
gui_utils.select(objectslist)
objs, parent_places, sel_info = utils._modifiers_process_selection(selection, (copy or clone), scale=True)
else:
gui_utils.select(newobjlist)
if len(newobjlist) == 1: return newobjlist[0]
return newobjlist
objs = utils._modifiers_filter_objects(utils._modifiers_get_group_contents(selection), (copy or clone), scale=True)
parent_places = None
sel_info = None
if not objs:
return None
newobjs = []
newgroups = {}
if copy or clone:
for obj in objs:
if obj.isDerivedFrom("App::DocumentObjectGroup") and obj.Name not in newgroups:
newgroups[obj.Name] = obj.Document.addObject(obj.TypeId, utils.get_real_name(obj.Name))
for idx, obj in enumerate(objs):
newobj = None
create_non_parametric = False
if parent_places is not None:
parent_place = parent_places[idx]
elif hasattr(obj, "getGlobalPlacement"):
parent_place = obj.getGlobalPlacement() * obj.Placement.inverse()
else:
parent_place = App.Placement()
if obj.isDerivedFrom("App::DocumentObjectGroup"):
if copy or clone:
newobj = newgroups[obj.Name]
else:
newobj = obj
elif obj.isDerivedFrom("App::Annotation"):
if parent_place.isIdentity():
pos = obj.Position
else:
pos = parent_place.multVec(obj.Position)
pos = scale_vector_from_center(pos, scale, center)
if copy or clone:
newobj = make_copy.make_copy(obj)
newobj.Position = pos
else:
newobj = obj
if parent_place.isIdentity():
newobj.Position = pos
else:
newobj.Position = parent_place.inverse().multVec(pos)
elif obj.isDerivedFrom("Image::ImagePlane"):
if parent_place.isIdentity():
pla = obj.Placement
else:
pla = parent_place * obj.Placement
pla = App.Placement(_get_scaled_matrix(pla, scale, center))
scale = pla.Rotation.inverted().multVec(scale)
if copy:
newobj = make_copy.make_copy(obj)
newobj.Placement = pla
else:
newobj = obj
if parent_place.isIdentity():
newobj.Placement = pla
else:
newobj.Placement = parent_place.inverse() * pla
newobj.XSize = newobj.XSize * abs(scale.x)
newobj.YSize = newobj.YSize * abs(scale.y)
elif clone:
if not hasattr(obj, "Placement"):
continue
if not hasattr(obj, "Shape"):
continue
if sx == sy == sz:
newobj = make_clone.make_clone(obj, forcedraft=True)
newobj.Placement.Base = scale_vector_from_center(newobj.Placement.Base, scale, center)
newobj.Scale = scale
else:
if parent_place.isIdentity():
source = obj
else:
source = make_clone.make_clone(obj, forcedraft=True)
source.Placement = parent_place * obj.Placement
source.Visibility = False
delta = scale_vector_from_center(App.Vector(), scale, center)
newobj = make_clone.make_clone(source, delta=delta, forcedraft=True)
newobj.ForceCompound = True
newobj.Scale = scale
elif utils.get_type(obj) in ("Circle", "Ellipse"):
if abs(sx) == abs(sy) == abs(sz):
if parent_place.isIdentity():
pla = obj.Placement
else:
pla = parent_place * obj.Placement
pla = App.Placement(_get_scaled_matrix(pla, scale, center))
if copy:
newobj = make_copy.make_copy(obj)
newobj.Placement = pla
else:
newobj = obj
if parent_place.isIdentity():
newobj.Placement = pla
else:
newobj.Placement = parent_place.inverse() * pla
if utils.get_type(newobj) == "Circle":
newobj.Radius = abs(sx) * newobj.Radius
else:
newobj.MinorRadius = abs(sx) * newobj.MinorRadius
newobj.MajorRadius = abs(sx) * newobj.MajorRadius
if newobj.FirstAngle != newobj.LastAngle and sx * sy * sz < 0:
newobj.FirstAngle = (newobj.FirstAngle.Value + 180) % 360
newobj.LastAngle = (newobj.LastAngle.Value + 180) % 360
else:
create_non_parametric = True
elif utils.get_type(obj) == "Rectangle":
if parent_place.isIdentity():
pla = obj.Placement
else:
pla = parent_place * obj.Placement
pts = [
App.Vector (0.0, 0.0, 0.0),
App.Vector (obj.Length.Value, 0.0, 0.0),
App.Vector (obj.Length.Value, obj.Height.Value, 0.0),
App.Vector (0.0, obj.Height.Value, 0.0)
]
pts = [pla.multVec(p) for p in pts]
pts = [scale_vector_from_center(p, scale, center) for p in pts]
pla = App.Placement(_get_scaled_matrix(pla, scale, center))
x_vec = pts[1] - pts[0]
y_vec = pts[3] - pts[0]
ang = x_vec.getAngle(y_vec)
if math.isclose(ang % math.pi/2, math.pi/4, abs_tol=1e-6):
if copy:
newobj = make_copy.make_copy(obj)
newobj.Placement = pla
else:
newobj = obj
if parent_place.isIdentity():
newobj.Placement = pla
else:
newobj.Placement = parent_place.inverse() * pla
newobj.Length = x_vec.Length
newobj.Height = y_vec.Length
else:
newobj = make_wire.make_wire(pts, closed=True, placement=pla, face=obj.MakeFace)
gui_utils.format_object(newobj, obj)
if not copy:
obj.Document.removeObject(obj.Name)
elif utils.get_type(obj) in ("Wire", "BSpline"):
if parent_place.isIdentity():
pla = obj.Placement
else:
pla = parent_place * obj.Placement
pts = [pla.multVec(p) for p in obj.Points]
pts = [scale_vector_from_center(p, scale, center) for p in pts]
pla = App.Placement(_get_scaled_matrix(pla, scale, center))
if copy:
newobj = make_copy.make_copy(obj)
newobj.Placement = pla
else:
newobj = obj
if parent_place.isIdentity():
newobj.Placement = pla
else:
newobj.Placement = parent_place.inverse() * pla
pla_inv = pla.inverse()
newobj.Points = [pla_inv.multVec(p) for p in pts]
elif hasattr(obj, "Placement") and hasattr(obj, "Shape"):
create_non_parametric = True
if create_non_parametric:
import Part
if parent_place.isIdentity():
pla = obj.Placement
else:
pla = parent_place * obj.Placement
pla = App.Placement(_get_scaled_matrix(pla, scale, center))
mtx = _get_scaled_matrix(parent_place, scale, center)
shp = obj.Shape.copy().transformShape(pla.Matrix.inverse() * mtx, False, True)
newobj = obj.Document.addObject("Part::FeaturePython", utils.get_real_name(obj.Name))
newobj.Shape = Part.Compound([shp])
newobj.Placement = pla
if App.GuiUp:
if utils.get_type(obj) in ("Circle", "Ellipse"):
from draftviewproviders.view_base import ViewProviderDraft
ViewProviderDraft(newobj.ViewObject)
else:
newobj.ViewObject.Proxy = 0
gui_utils.format_object(newobj, obj)
if not copy:
obj.Document.removeObject(obj.Name)
if newobj is not None:
newobjs.append(newobj)
if copy:
lyr = layer.get_layer(obj)
if lyr is not None:
lyr.Proxy.addObject(lyr, newobj)
for parent in obj.InList:
if parent.isDerivedFrom("App::DocumentObjectGroup") and (parent in objs):
newgroups[parent.Name].addObject(newobj)
if not (copy or clone) or params.get_param("selectBaseObjects"):
if sel_info is not None:
gui_utils.select(sel_info)
else:
gui_utils.select(objs)
else:
gui_utils.select(newobjs)
if len(newobjs) == 1:
return newobjs[0]
return newobjs
# Following functions are needed for SubObjects modifiers
# implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire)
def _scale_subelements(selection, scale, center, copy):
data_list, sel_info = utils._modifiers_process_subselection(selection, copy)
newobjs = []
if copy:
for obj, vert_idx, edge_idx, global_place in data_list:
if edge_idx >= 0:
newobjs.append(copy_scaled_edge(obj, edge_idx, scale, center, global_place))
newobjs = join.join_wires(newobjs)
else:
for obj, vert_idx, edge_idx, global_place in data_list:
if vert_idx >= 0:
scale_vertex(obj, vert_idx, scale, center, global_place)
elif edge_idx >= 0:
scale_edge(obj, edge_idx, scale, center, global_place)
if not copy or params.get_param("selectBaseObjects"):
gui_utils.select(sel_info)
else:
gui_utils.select(newobjs)
if len(newobjs) == 1:
return newobjs[0]
return newobjs
def scale_vertex(obj, vertex_index, scale, center):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
points = obj.Points
points[vertex_index] = obj.getGlobalPlacement().inverse().multVec(
scale_vector_from_center(
obj.getGlobalPlacement().multVec(points[vertex_index]),
scale, center))
obj.Points = points
def _get_scaled_matrix(pla, scale, center):
mtx = App.Matrix(pla.Matrix)
mtx.move(-center)
mtx.scale(scale)
mtx.move(center)
return mtx
def scale_vector_from_center(vector, scale, center):
@@ -160,49 +356,53 @@ def scale_vector_from_center(vector, scale, center):
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
return vector.sub(center).scale(scale.x, scale.y, scale.z).add(center)
return vector.sub(center).scale(*scale).add(center)
def scale_edge(obj, edge_index, scale, center):
def scale_vertex(obj, vert_idx, scale, center, global_place=None):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
scale_vertex(obj, edge_index, scale, center)
if utils.is_closed_edge(edge_index, obj):
scale_vertex(obj, 0, scale, center)
if global_place is None:
glp = obj.getGlobalPlacement()
else:
scale_vertex(obj, edge_index+1, scale, center)
glp = global_place
points = obj.Points
points[vert_idx] = glp.inverse().multVec(
scale_vector_from_center(glp.multVec(points[vert_idx]), scale, center)
)
obj.Points = points
def copy_scaled_edge(obj, edge_index, scale, center):
def scale_edge(obj, edge_idx, scale, center, global_place=None):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
vertex1 = scale_vector_from_center(
obj.getGlobalPlacement().multVec(obj.Points[edge_index]),
scale, center)
if utils.is_closed_edge(edge_index, obj):
vertex2 = scale_vector_from_center(
obj.getGlobalPlacement().multVec(obj.Points[0]),
scale, center)
scale_vertex(obj, edge_idx, scale, center, global_place)
if utils.is_closed_edge(edge_idx, obj):
scale_vertex(obj, 0, scale, center, global_place)
else:
vertex2 = scale_vector_from_center(
obj.getGlobalPlacement().multVec(obj.Points[edge_index+1]),
scale, center)
return make_line.make_line(vertex1, vertex2)
scale_vertex(obj, edge_idx+1, scale, center, global_place)
def copy_scaled_edges(arguments):
def copy_scaled_edge(obj, edge_idx, scale, center, global_place=None):
"""
Needed for SubObjects modifiers.
Implemented by Dion Moult during 0.19 dev cycle (works only with Draft Wire).
"""
copied_edges = []
for argument in arguments:
copied_edges.append(copy_scaled_edge(argument[0], argument[1],
argument[2], argument[3]))
join.join_wires(copied_edges)
if global_place is None:
glp = obj.getGlobalPlacement()
else:
glp = global_place
vertex1 = scale_vector_from_center(glp.multVec(obj.Points[edge_idx]), scale, center)
if utils.is_closed_edge(edge_idx, obj):
vertex2 = scale_vector_from_center(glp.multVec(obj.Points[0]), scale, center)
else:
vertex2 = scale_vector_from_center(glp.multVec(obj.Points[edge_idx+1]), scale, center)
newobj = make_line.make_line(vertex1, vertex2)
gui_utils.format_object(newobj, obj)
return newobj
## @}

View File

@@ -35,6 +35,7 @@ import DraftVecUtils
import WorkingPlane
from draftfunctions import svgtext
from draftfunctions.svgshapes import get_proj, get_circle, get_path
from draftobjects import layer
from draftutils import params
from draftutils import utils
from draftutils.messages import _wrn, _err
@@ -955,31 +956,14 @@ def _get_view_object(obj):
return None
# Similar function as in view_layer.py
def _get_layer(obj):
"""Get the layer the object belongs to."""
finds = obj.Document.findObjects(Name="LayerContainer")
if not finds:
return None
# First look in the LayerContainer:
for layer in finds[0].Group:
if utils.get_type(layer) == "Layer" and obj in layer.Group:
return layer
# If not found, look through all App::FeaturePython objects (not just layers):
for find in obj.Document.findObjects(Type="App::FeaturePython"):
if utils.get_type(find) == "Layer" and obj in find.Group:
return find
return None
def get_print_color(obj):
"""Return the print color of the parent layer, if available."""
# Layers are not in the Inlist of obj because a layer's Group is App::PropertyLinkListHidden:
layer = _get_layer(obj)
if layer is None:
lyr = layer.get_layer(obj)
if lyr is None:
return None
if layer.ViewObject.UsePrintColor:
return layer.ViewObject.LinePrintColor
if lyr.ViewObject.UsePrintColor:
return lyr.ViewObject.LinePrintColor
return None