mirror of
https://github.com/IfcOpenShell/IfcOpenShell.git
synced 2026-08-09 01:11:40 +00:00
Compare commits
75 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f16ba3d26e | |||
| efac8a0ec0 | |||
| e52e5e2e58 | |||
| 2d59ea1988 | |||
| 55a2430d71 | |||
| 04a2535a98 | |||
| 727b5f3475 | |||
| a45f2fae61 | |||
| 1ae50b8cce | |||
| 9fda996ebe | |||
| 7a7a250942 | |||
| bc1fb2a88d | |||
| c55a79b8b5 | |||
| b669baf793 | |||
| 32ac20e8e3 | |||
| 0d5ea02169 | |||
| 0a027d47a3 | |||
| 6014bbd877 | |||
| 6d6d92b849 | |||
| bb49822f2e | |||
| 21ea58b0e6 | |||
| b66d8b2c4d | |||
| f9be61c10b | |||
| b61f809731 | |||
| 948ffce7e9 | |||
| c68e4a0eee | |||
| 6603c8459a | |||
| 824c1fc280 | |||
| 705af7ba3a | |||
| 074fc26e8f | |||
| a90064929b | |||
| 397f13e71c | |||
| 7ebdd046b6 | |||
| 57cfd9d1fd | |||
| e333c1c100 | |||
| 97a85fe5a7 | |||
| 8ee52c466f | |||
| fe4fdd091d | |||
| 56121ca061 | |||
| 7b613a0bcc | |||
| b35f99e63f | |||
| f744753726 | |||
| 2e21fc5a98 | |||
| ca9bbbc4a7 | |||
| 5994fbde27 | |||
| 47dc1a6c68 | |||
| 489084c7be | |||
| 6c590bf008 | |||
| 96e2efebc8 | |||
| d188e3beaf | |||
| 93c0290131 | |||
| f3a7a35acf | |||
| 183e4c47f7 | |||
| 2ac92f01e4 | |||
| 2e9e75c7bd | |||
| 8857396a1f | |||
| f0970b90b0 | |||
| 71a598e63a | |||
| 3d8115ebc5 | |||
| b5a0f1fc74 | |||
| 25441bd816 | |||
| 65811ac7c9 | |||
| d9d1824886 | |||
| 16e5f18553 | |||
| b7a9b7bc5a | |||
| e14397058d | |||
| f0117c60b3 | |||
| 0e5223a30d | |||
| bc41ff78f4 | |||
| 9123d8c183 | |||
| ffd939508c | |||
| 9213b31235 | |||
| 2155e3206f | |||
| 9e0c6cf524 | |||
| d5dc069b2f |
@@ -55,11 +55,17 @@ jobs:
|
||||
black --diff --check . | black-codeclimate | python .github/workflows/black_to_github_annotations.py
|
||||
continue-on-error: true
|
||||
|
||||
- name: ty check
|
||||
id: ty
|
||||
run: |
|
||||
poe ty-venv
|
||||
poe ty
|
||||
- name: ty check (venv setup)
|
||||
run: poe ty-venv
|
||||
|
||||
- name: ty check (bonsai)
|
||||
id: ty-bonsai
|
||||
run: poe ty-bonsai
|
||||
continue-on-error: true
|
||||
|
||||
- name: ty check (ios)
|
||||
id: ty-ios
|
||||
run: poe ty-ios
|
||||
continue-on-error: true
|
||||
|
||||
- name: Ruff check
|
||||
@@ -109,7 +115,10 @@ jobs:
|
||||
if [ "${{ steps.ruff.outcome }}" != "success" ]; then
|
||||
echo "::error::Ruff check failed, see Summary or 'ruff' step for the details." && ERROR=1
|
||||
fi
|
||||
if [ "${{ steps.ty.outcome }}" != "success" ]; then
|
||||
echo "::error::ty check failed, see 'ty check' step for the details." && ERROR=1
|
||||
if [ "${{ steps.ty-bonsai.outcome }}" != "success" ]; then
|
||||
echo "::error::ty check (bonsai) failed, see 'ty check (bonsai)' step for the details." && ERROR=1
|
||||
fi
|
||||
if [ "${{ steps.ty-ios.outcome }}" != "success" ]; then
|
||||
echo "::error::ty check (ios) failed, see 'ty check (ios)' step for the details." && ERROR=1
|
||||
fi
|
||||
exit $ERROR
|
||||
|
||||
@@ -18,7 +18,7 @@ and many other libraries, CLI apps, and more. Support is also provided for auxil
|
||||
|
||||
For more information, see:
|
||||
|
||||
* [IfcOpenShell Website](http://ifcopenshell.org)
|
||||
* [IfcOpenShell Website](https://ifcopenshell.org)
|
||||
* [IfcOpenShell Documentation](https://docs.ifcopenshell.org)
|
||||
* [IfcOpenShell C++ Installation](https://docs.ifcopenshell.org/ifcopenshell/installation.html)
|
||||
* [IfcOpenShell Python Installation](https://docs.ifcopenshell.org/ifcopenshell-python/installation.html)
|
||||
|
||||
@@ -68,6 +68,7 @@ def unpack_dependencies(install_dir: Path) -> None:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
action = None
|
||||
if len(sys.argv) != 2 or (action := sys.argv[1].lower()) not in ("pack", "unpack"):
|
||||
print(__doc__)
|
||||
sys.exit(1)
|
||||
|
||||
@@ -82,8 +82,6 @@ ignore = [
|
||||
all = "error"
|
||||
|
||||
# Structural rules (no deep type inference needed, easier to adapt).
|
||||
# Has false positives due to ty walrus operator bug.
|
||||
possibly-unresolved-reference = "ignore"
|
||||
# Maybe later, requires to specify element types for all generics.
|
||||
missing-type-argument = "ignore"
|
||||
# Conflicts with `bpy` props defined using annotations.
|
||||
@@ -111,7 +109,6 @@ no-matching-overload = "ignore"
|
||||
not-subscriptable = "ignore"
|
||||
unsupported-dynamic-base = "ignore"
|
||||
unsupported-operator = "ignore"
|
||||
type-assertion-failure = "ignore"
|
||||
|
||||
[tool.ty.environment]
|
||||
extra-paths = [
|
||||
@@ -195,7 +192,6 @@ format.sequence = ["black", "ruff"]
|
||||
cmake-format = "gersemi . --in-place"
|
||||
|
||||
[tool.poe.tasks.ty-ios]
|
||||
# --ignore unresolved-reference: walrus operator false positives in ty.
|
||||
cmd = """
|
||||
ty check
|
||||
nix/
|
||||
@@ -213,7 +209,6 @@ cmd = """
|
||||
src/ifcpatch
|
||||
src/ifctester
|
||||
--python=src/ifcopenshell-python/.venv
|
||||
--ignore unresolved-reference
|
||||
"""
|
||||
|
||||
[tool.poe.tasks.bonsai-deps]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
black==26.3.1
|
||||
ruff==0.15.12
|
||||
ruff==0.15.22
|
||||
poethepoet
|
||||
ty==0.0.59
|
||||
ty==0.0.61
|
||||
gersemi==0.26.1
|
||||
|
||||
@@ -188,6 +188,8 @@ class BcfClient:
|
||||
response.raise_for_status()
|
||||
return response.status_code, response.text
|
||||
except requests.exceptions.HTTPError as errh:
|
||||
response = errh.response
|
||||
assert response is not None
|
||||
print(f"message: {response.reason}' '{response.status_code}, {errh}")
|
||||
return response.status_code, response.reason
|
||||
|
||||
@@ -206,6 +208,8 @@ class BcfClient:
|
||||
response.raise_for_status()
|
||||
return response.status_code, response.text
|
||||
except requests.exceptions.HTTPError as errh:
|
||||
response = errh.response
|
||||
assert response is not None
|
||||
print(f"message: {response.reason}' '{response.status_code}, {errh}")
|
||||
return response.status_code, response.reason
|
||||
|
||||
@@ -222,6 +226,8 @@ class BcfClient:
|
||||
response.raise_for_status()
|
||||
return response.status_code, response.text
|
||||
except requests.exceptions.HTTPError as errh:
|
||||
response = errh.response
|
||||
assert response is not None
|
||||
print(f"message: {response.reason}' '{response.status_code}, {errh}")
|
||||
return response.status_code, response.reason
|
||||
|
||||
|
||||
@@ -24,10 +24,28 @@ a text, a tspan { fill: blue !important; text-decoration: underline;}
|
||||
a:hover { cursor: pointer; }
|
||||
.cut { fill: black; stroke: black; stroke-linecap: 'round'; stroke-width: 0.35; fill-rule: evenodd; }
|
||||
.projection { fill: white; stroke: black; stroke-linecap: 'round'; stroke-width: 0.25; }
|
||||
.surface { stroke: none; fill: #fff; fill-rule: evenodd; }
|
||||
.annotation { fill: none; stroke: black; stroke-linecap: 'round'; stroke-width: 0.25; }
|
||||
.IfcAnnotation { fill: none; stroke: black; stroke-linecap: 'round'; stroke-width: 0.25; }
|
||||
.IfcGeographicElement { fill: none; stroke: black; stroke-linecap: 'round'; stroke-width: 1; }
|
||||
/* SVG edge classification (issue #3668): see edge-classification.md. These select directly on
|
||||
the <path> element (each classified projection edge carries its own class), so they win over
|
||||
the inherited .projection rule above regardless of specificity. */
|
||||
path.outline { stroke: black; stroke-width: 0.35; stroke-opacity: 1; }
|
||||
path.boundary { stroke: black; stroke-width: 0.3; stroke-opacity: 0.9; }
|
||||
path.crease { stroke: black; stroke-width: 0.25; stroke-opacity: 0.85; }
|
||||
path.sharp { stroke: black; stroke-width: 0.18; stroke-opacity: 0.7; }
|
||||
path.flush { stroke: black; stroke-width: 0.1; stroke-opacity: 0.4; }
|
||||
|
||||
/* Debug CSS for troubleshooting edge classification */
|
||||
/*
|
||||
path.outline { stroke: black; stroke-width: 0.35; stroke-opacity: 1; }
|
||||
path.boundary { stroke: orange; stroke-width: 0.3; stroke-opacity: 0.9; }
|
||||
path.crease { stroke: green; stroke-width: 0.25; stroke-opacity: 0.85; }
|
||||
path.sharp { stroke: red; stroke-width: 0.18; stroke-opacity: 0.7; }
|
||||
path.flush { stroke: blue; stroke-width: 0.1; stroke-opacity: 0.4; }
|
||||
*/
|
||||
|
||||
.surface {fill: white; stroke-width: 0.1;}
|
||||
.annotation { fill: none; stroke: black; stroke-linecap: 'round'; stroke-width: 0.3; }
|
||||
.IfcAnnotation { fill: none; stroke: black; stroke-linecap: 'round'; stroke-width: 0.3; }
|
||||
/* .IfcGeographicElement { fill: none; stroke: rgb(150, 150, 150); stroke-linecap: 'round'; stroke-dasharray: 1, 2;} */
|
||||
.PredefinedType-LINEWORK { stroke: black; stroke-width: 0.25; }
|
||||
.PredefinedType-LINEWORK.dashed { stroke-dasharray: 3, 2; }
|
||||
.PredefinedType-LINEWORK.fine { stroke-width: 0.18; stroke: #777777; }
|
||||
|
||||
@@ -5,7 +5,7 @@ FILE_NAME('EPset_Drawing.ifc','2020-01-01T00:00:00',$,$,'EPset_Drawing','EPset_D
|
||||
FILE_SCHEMA(('IFC4'));
|
||||
ENDSEC;
|
||||
DATA;
|
||||
#1=IFCPROPERTYSETTEMPLATE('2JhNIvqZrFnAgxfhK0XVQX',$,'EPset_Drawing','',.PSET_OCCURRENCEDRIVEN.,'IfcAnnotation/DRAWING',(#23,#22,#27,#24,#29,#30,#19,#12,#26,#9,#8,#7,#6,#4,#18,#11,#5,#20,#25,#14,#10,#17,#28,#16,#3,#21,#13,#15,#2));
|
||||
#1=IFCPROPERTYSETTEMPLATE('2JhNIvqZrFnAgxfhK0XVQX',$,'EPset_Drawing','',.PSET_OCCURRENCEDRIVEN.,'IfcAnnotation/DRAWING',(#23,#22,#27,#24,#29,#30,#19,#12,#26,#9,#8,#7,#6,#4,#18,#11,#5,#20,#25,#14,#10,#17,#28,#16,#3,#21,#13,#15,#2,#31,#32,#33,#34,#35,#36,#37));
|
||||
#2=IFCSIMPLEPROPERTYTEMPLATE('23JavTMk98ZxXhrUEnjAcf',$,'TargetView','',.P_SINGLEVALUE.,'IfcLabel',$,$,$,$,$,.READWRITE.);
|
||||
#3=IFCSIMPLEPROPERTYTEMPLATE('1yVWUt5H9DAOuu0OaMMLpe',$,'Scale','The scale of this drawing represented as a numerator and denominator, such as 1/100',.P_SINGLEVALUE.,'IfcLabel',$,$,$,$,$,.READWRITE.);
|
||||
#4=IFCSIMPLEPROPERTYTEMPLATE('3gsuPBtU93b8f0gg1pjkq6',$,'HumanScale','The scale of this drawing in human readable format, such as 1:100',.P_SINGLEVALUE.,'IfcLabel',$,$,$,$,$,.READWRITE.);
|
||||
@@ -35,5 +35,12 @@ DATA;
|
||||
#28=IFCSIMPLEPROPERTYTEMPLATE('1YSnFzurrEyRNtoLdmmddP',$,'BringToFront','The objects with these SVG classes will render in front of all other objects.Ex: IfcBeam, IfcColumn',.P_SINGLEVALUE.,'IfcText',$,$,$,$,$,.READWRITE.);
|
||||
#29=IFCSIMPLEPROPERTYTEMPLATE('0lP6Y8q9v2QhDnR4sT7uVx',$,'PerspectiveShiftX','Horizontal perspective camera shift stored as drawing metadata using Blender camera shift units.',.P_SINGLEVALUE.,'IfcReal',$,$,$,$,$,.READWRITE.);
|
||||
#30=IFCSIMPLEPROPERTYTEMPLATE('2mR8b1NcW5EoFyG7hJ9kLp',$,'PerspectiveShiftY','Vertical perspective camera shift stored as drawing metadata using Blender camera shift units.',.P_SINGLEVALUE.,'IfcReal',$,$,$,$,$,.READWRITE.);
|
||||
#31=IFCSIMPLEPROPERTYTEMPLATE('1cFVJnqT13m8ItkMHaI1tp',$,'UseEdgeClassification','Enable the boundary/outline/sharp/crease/flush SVG edge classification scheme (issue #3668). When false, drawings use the original unclassified linework.',.P_SINGLEVALUE.,'IfcBoolean',$,$,$,$,$,.READWRITE.);
|
||||
#32=IFCSIMPLEPROPERTYTEMPLATE('2kB$mxBgnBUvhjh0Ti0c4P',$,'RenderCreases','Whether to render ''crease'' (concave) edges. Only relevant when UseEdgeClassification is enabled.',.P_SINGLEVALUE.,'IfcBoolean',$,$,$,$,$,.READWRITE.);
|
||||
#33=IFCSIMPLEPROPERTYTEMPLATE('3MSIJNW$T8r9Hl12kk0BY$',$,'ValleyAngleMinDegrees','Minimum concave dihedral deviation from flat, in degrees, for a projection edge to be classified as ''crease'' rather than ''flush''.',.P_SINGLEVALUE.,'IfcReal',$,$,$,$,$,.READWRITE.);
|
||||
#34=IFCSIMPLEPROPERTYTEMPLATE('2epSGfC4bFM9gb1X7zBIp4',$,'RenderSharp','Whether to render ''sharp'' (convex) edges. Only relevant when UseEdgeClassification is enabled.',.P_SINGLEVALUE.,'IfcBoolean',$,$,$,$,$,.READWRITE.);
|
||||
#35=IFCSIMPLEPROPERTYTEMPLATE('3TZwsEjkr5WRDKcgrYzSIA',$,'RidgeAngleMinDegrees','Minimum convex dihedral deviation from flat, in degrees, for a projection edge to be classified as ''sharp'' rather than ''flush''.',.P_SINGLEVALUE.,'IfcReal',$,$,$,$,$,.READWRITE.);
|
||||
#36=IFCSIMPLEPROPERTYTEMPLATE('2Jua$lO754vgZOkBoHM2gA',$,'RenderFlush','Whether to render ''flush'' edges (dihedral deviation below both ridge/valley thresholds). Only relevant when UseEdgeClassification is enabled.',.P_SINGLEVALUE.,'IfcBoolean',$,$,$,$,$,.READWRITE.);
|
||||
#37=IFCSIMPLEPROPERTYTEMPLATE('1zM9sia2L8RQDnWZxgUwlZ',$,'JoinClasses','Comma separated list of IFC classes whose cut linework will be joined together when they meet (e.g. mitred at a corner).\X2\000A\X0\Defaults to ''IfcWall,IfcSlab'' if not set. Override to also join other classes, such as ''IfcWall,IfcSlab,IfcCovering''.',.P_SINGLEVALUE.,'IfcText',$,$,$,$,$,.READWRITE.);
|
||||
ENDSEC;
|
||||
END-ISO-10303-21;
|
||||
|
||||
@@ -244,7 +244,7 @@ function addGanttElement(blenderId, tasks, workSched, filename) {
|
||||
vShowTaskInfoLink: 1, // Show link in tool tip (0/1)
|
||||
vShowEndWeekDate: 0, // Show/Hide the date for the last day of the week in header for daily
|
||||
vUseSingleCell: 10000, // Set the threshold cell per table row (Helps performance for large data.
|
||||
vFormatArr: ["Day", "Week", "Month", "Quarter"], // Even with setUseSingleCell using Hour format on such a large chart can cause issues in some browsers,
|
||||
vFormatArr: ["Hour", "Day", "Week", "Month", "Quarter"], // vUseSingleCell keeps Hour usable on large charts.
|
||||
vShowRes: true, // Disable the resource column.
|
||||
vShowComp: false, // Disable the completion column.
|
||||
vShowDur: false, // Disable the duration column, because jsgantt doesn't calculate durations the way we want.
|
||||
|
||||
@@ -1103,12 +1103,14 @@ class IfcImporter:
|
||||
vertices = [[v[i], v[i + 1], v[i + 2], 1] for i in range(0, len(v), 3)]
|
||||
edges = [[e[i], e[i + 1]] for i in range(0, len(e), 2)]
|
||||
v2 = None
|
||||
polyline = None
|
||||
for edge in edges:
|
||||
v1 = vertices[edge[0]]
|
||||
if v1 != v2:
|
||||
polyline = curve.splines.new("POLY")
|
||||
polyline.points[-1].co = mathutils.Vector(v1)
|
||||
v2 = vertices[edge[1]]
|
||||
assert polyline is not None
|
||||
polyline.points.add(1)
|
||||
polyline.points[-1].co = mathutils.Vector(v2)
|
||||
edges_item_ids = ifcopenshell.util.shape.get_edges_representation_item_ids(geometry).tolist()
|
||||
|
||||
@@ -843,7 +843,6 @@ class AddBoundary(bpy.types.Operator, tool.Ifc.Operator):
|
||||
settings = ifcopenshell.geom.settings()
|
||||
shape = ifcopenshell.geom.create_shape(settings, opening)
|
||||
mat = Matrix(ifcopenshell.util.shape.get_shape_matrix(shape))
|
||||
mat.translation = (0, 0, 0)
|
||||
opening_bm = bmesh.new()
|
||||
verts = ifcopenshell.util.shape.get_vertices(shape.geometry)
|
||||
for vert in verts:
|
||||
@@ -1060,6 +1059,7 @@ class AddBoundary(bpy.types.Operator, tool.Ifc.Operator):
|
||||
return tool.Ifc.get().createIfcConnectionSurfaceGeometry(surface)
|
||||
|
||||
def export_surface(self, polygon, target_face_matrix):
|
||||
ifc_file = tool.Ifc.get()
|
||||
x_axis = target_face_matrix.col[0][:3]
|
||||
z_axis = target_face_matrix.col[2][:3]
|
||||
p1 = target_face_matrix.translation
|
||||
@@ -1072,18 +1072,20 @@ class AddBoundary(bpy.types.Operator, tool.Ifc.Operator):
|
||||
placement = builder.create_axis2_placement_3d([o / self.unit_scale for o in p1], z_axis, x_axis)
|
||||
surface.BasisSurface = tool.Ifc.get().create_entity("IfcPlane", placement)
|
||||
|
||||
if tool.Ifc.get().schema != "IFC2X3":
|
||||
schema = ifc_file.schema
|
||||
if schema != "IFC2X3":
|
||||
points = [tool.Model.convert_si_to_unit(list(co)) for co in polygon.exterior.coords]
|
||||
point_list = tool.Ifc.get().createIfcCartesianPointList2D(points)
|
||||
outer_boundary = tool.Ifc.get().createIfcIndexedPolyCurve(point_list, None, False)
|
||||
|
||||
inner_boundaries = []
|
||||
inner_boundaries: list[ifcopenshell.entity_instance] = []
|
||||
for interior in polygon.interiors:
|
||||
points = [tool.Model.convert_si_to_unit(list(co)) for co in interior.coords]
|
||||
point_list = tool.Ifc.get().createIfcCartesianPointList2D(points)
|
||||
inner_boundaries.append(tool.Ifc.get().createIfcIndexedPolyCurve(point_list, None, False))
|
||||
else:
|
||||
pass # TODO
|
||||
# TODO:
|
||||
raise NotImplementedError(schema)
|
||||
|
||||
surface.OuterBoundary = outer_boundary
|
||||
surface.InnerBoundaries = inner_boundaries
|
||||
|
||||
@@ -400,6 +400,7 @@ class CadOffset(bpy.types.Operator):
|
||||
[verts.update(e.verts) for e in edges]
|
||||
|
||||
# Use the viewport angle to determine the offset direction
|
||||
wp = None
|
||||
for area in bpy.context.screen.areas:
|
||||
if area.type == "VIEW_3D":
|
||||
# Don't ask me, I don't know.
|
||||
@@ -409,6 +410,7 @@ class CadOffset(bpy.types.Operator):
|
||||
z = area.spaces.active.region_3d.view_rotation @ Vector((0, 0, 1))
|
||||
wp = Matrix([x, y, z, Vector((0, 0, 0))]).to_4x4().transposed()
|
||||
break
|
||||
assert wp is not None
|
||||
|
||||
rotation = Matrix.Rotation(pi / 2, 2, "Z")
|
||||
rotation_i = Matrix.Rotation(-pi / 2, 2, "Z")
|
||||
|
||||
@@ -478,6 +478,7 @@ class ChangeClassificationLevel(bpy.types.Operator):
|
||||
def execute(self, context):
|
||||
props = tool.Classification.get_classification_props()
|
||||
props.available_library_references.clear()
|
||||
reference = None
|
||||
for reference in IfcStore.classification_file.by_id(self.parent_id).HasReferences:
|
||||
new = props.available_library_references.add()
|
||||
new.identification = reference.Identification or ""
|
||||
@@ -485,6 +486,7 @@ class ChangeClassificationLevel(bpy.types.Operator):
|
||||
new.ifc_definition_id = reference.id()
|
||||
new.has_references = bool(reference.HasReferences)
|
||||
new.referenced_source
|
||||
assert reference
|
||||
if reference.ReferencedSource.is_a("IfcClassificationReference"):
|
||||
props.active_library_referenced_source = reference.ReferencedSource.ReferencedSource.id()
|
||||
else:
|
||||
|
||||
@@ -156,6 +156,8 @@ class CostSchedulesData:
|
||||
values = root_element.CostValues
|
||||
elif root_element.is_a("IfcConstructionResource"):
|
||||
values = root_element.BaseCosts
|
||||
else:
|
||||
assert False, root_element
|
||||
for cost_value in values or []:
|
||||
cls._load_cost_value(root_element, data, cost_value)
|
||||
# data["CostValues"].append(cost_value.id())
|
||||
|
||||
@@ -47,6 +47,7 @@ classes = (
|
||||
operator.CleanWireframes,
|
||||
operator.ContractSheet,
|
||||
operator.ConvertSVGToDXF,
|
||||
operator.CopyAnnotationToDrawing,
|
||||
operator.CopyTextToSelection,
|
||||
operator.CreateDrawing,
|
||||
operator.CreateSheets,
|
||||
@@ -107,6 +108,7 @@ classes = (
|
||||
operator.SelectAssignedProduct,
|
||||
operator.SelectSimilarTextLiteralValue,
|
||||
operator.ToggleTargetView,
|
||||
operator.ToggleDrawingCategorySelection,
|
||||
operator.OpenDocumentationWebUi,
|
||||
operator.FilterSelectedObjectsIfIntersectedByCamera,
|
||||
prop.Variable,
|
||||
|
||||
@@ -425,10 +425,12 @@ class BaseDecorator:
|
||||
|
||||
blf.size(font_id, font_size_px)
|
||||
|
||||
w, h = None, None
|
||||
if box_alignment or center or vcenter:
|
||||
w, h = blf.dimensions(font_id, text)
|
||||
|
||||
if box_alignment:
|
||||
assert w is not None and h is not None
|
||||
box_alignment_offset = Vector((0, 0))
|
||||
if "bottom" in box_alignment:
|
||||
pass
|
||||
@@ -450,10 +452,12 @@ class BaseDecorator:
|
||||
else:
|
||||
# horizontal centering
|
||||
if center:
|
||||
assert w is not None
|
||||
pos -= Vector((cos, sin)) * w * 0.5
|
||||
|
||||
# vertical centering
|
||||
if vcenter:
|
||||
assert h is not None
|
||||
pos -= Vector((-sin, cos)) * h * 0.5
|
||||
|
||||
# side-shifting
|
||||
@@ -1001,6 +1005,8 @@ class FallDecorator(BaseDecorator):
|
||||
O = A.copy()
|
||||
O.z = B.z
|
||||
run = (B - O).length
|
||||
|
||||
angle_tg = None
|
||||
if run != 0:
|
||||
angle_tg = rise / run
|
||||
angle = round(degrees(atan(angle_tg)))
|
||||
@@ -1018,6 +1024,7 @@ class FallDecorator(BaseDecorator):
|
||||
elif object_type == "SLOPE_PERCENT":
|
||||
if angle == 90:
|
||||
return "-"
|
||||
assert angle_tg is not None
|
||||
return f"{round(angle_tg * 100)} %"
|
||||
return "NO DATA"
|
||||
|
||||
@@ -1249,6 +1256,7 @@ class SectionLevelDecorator(BaseDecorator):
|
||||
}
|
||||
|
||||
# process edges
|
||||
text_position, text_dir = None, None
|
||||
for edge in edges_original:
|
||||
v0, v1 = winspace_verts[edge[0]], winspace_verts[edge[1]]
|
||||
start_i = len(output_verts)
|
||||
@@ -1554,32 +1562,39 @@ class SectionDecorator(BaseDecorator):
|
||||
v0, v1 = winspace_verts[edge[0]], winspace_verts[edge[1]]
|
||||
start_i = len(output_verts)
|
||||
|
||||
circle_head = None
|
||||
if display_start_circle or display_end_circle:
|
||||
circle_head = get_circle_head(circle_size)
|
||||
|
||||
if display_start_symbol or display_end_symbol or connect_markers:
|
||||
triangle_head, divider_offset, edge_dir_circle = None, None, None
|
||||
display_symbol = display_start_symbol or display_end_symbol
|
||||
if display_symbol or connect_markers:
|
||||
edge_dir = (v1 - v0).normalized()
|
||||
side = (edge_dir.yx * Vector((1, -1))).to_3d()
|
||||
edge_dir_circle = edge_dir * circle_size
|
||||
|
||||
if display_start_symbol or display_end_symbol:
|
||||
triangle_head = get_triangle_head(edge_dir, -side, triangle_length, triangle_width)
|
||||
divider_offset = []
|
||||
divider_offset.append(edge_dir_circle if connect_markers else edge_dir_circle * 3)
|
||||
divider_offset.append(edge_dir_circle)
|
||||
if display_symbol:
|
||||
triangle_head = get_triangle_head(edge_dir, -side, triangle_length, triangle_width)
|
||||
divider_offset = []
|
||||
divider_offset.append(edge_dir_circle if connect_markers else edge_dir_circle * 3)
|
||||
divider_offset.append(edge_dir_circle)
|
||||
|
||||
if display_start_circle:
|
||||
assert circle_head is not None
|
||||
start_i = add_verts_sequence([v + v0 for v in circle_head], start_i, **out_kwargs, closed=True)
|
||||
# circle middle divider
|
||||
if not display_start_symbol:
|
||||
assert divider_offset is not None
|
||||
start_i = add_verts_sequence(
|
||||
[v0 + divider_offset[0], v0 - divider_offset[1]], start_i, **out_kwargs
|
||||
)
|
||||
|
||||
if display_start_symbol:
|
||||
assert triangle_head is not None
|
||||
start_i = add_verts_sequence([v + v0 for v in triangle_head], start_i, **out_kwargs, closed=True)
|
||||
|
||||
if display_end_circle:
|
||||
assert circle_head is not None
|
||||
start_i = add_verts_sequence([v + v1 for v in circle_head], start_i, **out_kwargs, closed=True)
|
||||
# circle middle divider
|
||||
if not display_end_symbol:
|
||||
@@ -1588,9 +1603,11 @@ class SectionDecorator(BaseDecorator):
|
||||
)
|
||||
|
||||
if display_end_symbol:
|
||||
assert triangle_head is not None
|
||||
start_i = add_verts_sequence([v + v1 for v in triangle_head], start_i, **out_kwargs, closed=True)
|
||||
|
||||
if connect_markers:
|
||||
assert edge_dir_circle is not None
|
||||
gap = []
|
||||
gap.append(edge_dir_circle if display_start_symbol else Vector((0, 0, 0)))
|
||||
gap.append(edge_dir_circle if display_end_symbol else Vector((0, 0, 0)))
|
||||
@@ -1677,6 +1694,12 @@ class CutDecorator:
|
||||
selected_elements_color = self.addon_prefs.decorator_color_selected
|
||||
self.fallback_colour = (0.3, 0.3, 0.3, 1)
|
||||
|
||||
# Evaluate camera movement once per redraw rather than twice per object: is_camera_moved()
|
||||
# runs eval()/numpy on the camera matrix and, as a side effect, refreshes the stored
|
||||
# checksum on the first True result - so calling it per object also made the second call
|
||||
# (fill) see an already-updated checksum and skip recalculating when it shouldn't.
|
||||
self.camera_moved = self.is_camera_moved()
|
||||
|
||||
all_vertices = []
|
||||
all_edges = []
|
||||
selected_vertices = []
|
||||
@@ -1802,23 +1825,35 @@ class CutDecorator:
|
||||
|
||||
# Currently selected objects must be recalculated as they may be being moved / edited.
|
||||
# If the camera is selected, we also recalculate as the user may be moving the camera.
|
||||
is_selected = obj.select_get()
|
||||
recalc_cut = not has_cut_cache or is_selected or self.camera_moved
|
||||
recalc_fill = not has_fill_cache or is_selected or self.camera_moved
|
||||
if not (recalc_cut or recalc_fill):
|
||||
return
|
||||
|
||||
if not has_cut_cache or obj.select_get() or self.is_camera_moved():
|
||||
self.recalculate_cut(context, obj, element)
|
||||
if not has_fill_cache or obj.select_get() or self.is_camera_moved():
|
||||
self.recalculate_fill(context, obj, element)
|
||||
# The intersection test builds a bmesh and scans every vertex; both recalculations need
|
||||
# the same answer, so compute it once here rather than once in each.
|
||||
is_intersecting = tool.Drawing.is_intersecting_camera(obj, context.scene.camera)
|
||||
if recalc_cut:
|
||||
self.recalculate_cut(context, obj, element, is_intersecting)
|
||||
if recalc_fill:
|
||||
self.recalculate_fill(context, obj, element, is_intersecting)
|
||||
|
||||
def recalculate_cut(self, context, obj: bpy.types.Object, element: ifcopenshell.entity_instance) -> None:
|
||||
if tool.Drawing.is_intersecting_camera(obj, context.scene.camera):
|
||||
def recalculate_cut(
|
||||
self, context, obj: bpy.types.Object, element: ifcopenshell.entity_instance, is_intersecting: bool
|
||||
) -> None:
|
||||
if is_intersecting:
|
||||
verts, edges = tool.Drawing.bisect_mesh(obj, context.scene.camera)
|
||||
DecoratorData.cut_cache[element.id()] = (verts, edges)
|
||||
else:
|
||||
DecoratorData.cut_cache[element.id()] = (False, False)
|
||||
|
||||
def recalculate_fill(self, context, obj: bpy.types.Object, element: ifcopenshell.entity_instance) -> None:
|
||||
def recalculate_fill(
|
||||
self, context, obj: bpy.types.Object, element: ifcopenshell.entity_instance, is_intersecting: bool
|
||||
) -> None:
|
||||
element_id = element.id()
|
||||
|
||||
if not tool.Drawing.is_intersecting_camera(obj, context.scene.camera):
|
||||
if not is_intersecting:
|
||||
DecoratorData.fill_cache[element_id] = {}
|
||||
return
|
||||
|
||||
@@ -1871,6 +1906,8 @@ class CutDecorator:
|
||||
layer_set = material
|
||||
offset = 0
|
||||
sense_factor = 1
|
||||
else:
|
||||
assert False, material
|
||||
|
||||
if len(layer_set.MaterialLayers) == 1:
|
||||
material = layer_set.MaterialLayers[0].Material
|
||||
@@ -1897,6 +1934,8 @@ class CutDecorator:
|
||||
co = Vector((0.0, 0.0, offset))
|
||||
no = tool.Drawing.get_extrusion_vector(element).normalized()
|
||||
no = Vector([1.0, 0.0, 0.0])
|
||||
else:
|
||||
assert False, usage
|
||||
no *= sense_factor
|
||||
last_i = len(layer_set.MaterialLayers) - 1
|
||||
|
||||
|
||||
@@ -225,9 +225,11 @@ def format_distance(
|
||||
unit_system, unit_length, unit_fraction = unit_mapping[custom_unit]
|
||||
|
||||
value *= unit_scale
|
||||
tx_dist = None
|
||||
|
||||
# Imperial Formatting
|
||||
if unit_system == "IMPERIAL":
|
||||
toInches = None
|
||||
if in_unit_length:
|
||||
if unit_length == "INCHES":
|
||||
toInches = 1
|
||||
@@ -241,6 +243,7 @@ def format_distance(
|
||||
toInches = 1550
|
||||
inPerFoot = 144
|
||||
|
||||
assert toInches is not None
|
||||
decInches = value * toInches
|
||||
decFeet = decInches / 12
|
||||
|
||||
@@ -383,6 +386,7 @@ def format_distance(
|
||||
if precision and isinstance(precision, float):
|
||||
value = precision * round(float(value) / precision)
|
||||
|
||||
fmt = None
|
||||
if decimal_places is not None:
|
||||
fmt = "%1." + str(decimal_places) + "f"
|
||||
|
||||
@@ -465,6 +469,7 @@ def format_distance(
|
||||
assert f"Unexpected unit_system - '{unit_system}'."
|
||||
# tx_dist = fmt % value
|
||||
|
||||
assert tx_dist is not None
|
||||
return tx_dist
|
||||
|
||||
|
||||
|
||||
@@ -228,6 +228,90 @@ class DuplicateDrawing(bpy.types.Operator, tool.Ifc.Operator):
|
||||
)
|
||||
|
||||
|
||||
def get_copy_annotation_target_drawings(self, context):
|
||||
global COPY_ANNOTATION_TARGET_DRAWINGS_ENUM
|
||||
drawings = [e for e in tool.Ifc.get().by_type("IfcAnnotation") if e.ObjectType == "DRAWING"]
|
||||
drawings.sort(key=lambda d: d.Name or "")
|
||||
COPY_ANNOTATION_TARGET_DRAWINGS_ENUM = [(str(d.id()), d.Name or "Unnamed", "") for d in drawings]
|
||||
return COPY_ANNOTATION_TARGET_DRAWINGS_ENUM
|
||||
|
||||
|
||||
COPY_ANNOTATION_TARGET_DRAWINGS_ENUM = []
|
||||
|
||||
|
||||
class CopyAnnotationToDrawing(bpy.types.Operator, tool.Ifc.Operator):
|
||||
bl_idname = "bim.copy_annotation_to_drawing"
|
||||
bl_label = "Copy Annotation To Drawing"
|
||||
bl_description = (
|
||||
"Copy the selected annotations to another drawing.\n\n"
|
||||
"The copies become independent annotations assigned to the chosen drawing, "
|
||||
"placed in its view plane. The originals stay in their current drawing"
|
||||
)
|
||||
bl_options = {"REGISTER", "UNDO"}
|
||||
target_drawing: bpy.props.EnumProperty(name="Target Drawing", items=get_copy_annotation_target_drawings)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
target_drawing: str
|
||||
|
||||
@classmethod
|
||||
def poll(cls, context):
|
||||
if not tool.Ifc.get():
|
||||
cls.poll_message_set("No IFC project loaded.")
|
||||
return False
|
||||
if not cls.get_selected_annotations(context):
|
||||
cls.poll_message_set("No annotation selected.")
|
||||
return False
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def get_selected_annotations(cls, context) -> list[ifcopenshell.entity_instance]:
|
||||
return [
|
||||
element
|
||||
for obj in context.selected_objects
|
||||
if (element := tool.Ifc.get_entity(obj))
|
||||
and element.is_a("IfcAnnotation")
|
||||
and element.ObjectType != "DRAWING"
|
||||
]
|
||||
|
||||
def invoke(self, context, event):
|
||||
assert context.window_manager
|
||||
return context.window_manager.invoke_props_dialog(self)
|
||||
|
||||
def draw(self, context):
|
||||
assert self.layout
|
||||
row = self.layout.row()
|
||||
row.prop(self, "target_drawing")
|
||||
|
||||
def _execute(self, context):
|
||||
if not self.target_drawing:
|
||||
self.report({"ERROR"}, "No target drawing selected.")
|
||||
return {"CANCELLED"}
|
||||
target_drawing = tool.Ifc.get().by_id(int(self.target_drawing))
|
||||
annotations = self.get_selected_annotations(context)
|
||||
previous_selection = [obj for a in annotations if (obj := tool.Ifc.get_object(a))]
|
||||
previous_active = context.view_layer.objects.active
|
||||
copied = core.copy_annotations_to_drawing(
|
||||
tool.Ifc,
|
||||
tool.Collector,
|
||||
tool.Drawing,
|
||||
tool.Geometry,
|
||||
annotations=annotations,
|
||||
target_drawing=target_drawing,
|
||||
)
|
||||
for obj in context.selected_objects:
|
||||
obj.select_set(False)
|
||||
for obj in previous_selection:
|
||||
if obj.name in context.view_layer.objects:
|
||||
obj.select_set(True)
|
||||
if previous_active and previous_active.name in context.view_layer.objects:
|
||||
context.view_layer.objects.active = previous_active
|
||||
skipped = len(annotations) - len(copied)
|
||||
message = f"Copied {len(copied)} annotations to {target_drawing.Name or 'Unnamed'}."
|
||||
if skipped:
|
||||
message += f" Skipped {skipped} already in that drawing."
|
||||
self.report({"INFO"}, message)
|
||||
|
||||
|
||||
class CreateDrawing(bpy.types.Operator):
|
||||
"""Creates/refreshes a .svg drawing
|
||||
|
||||
@@ -698,6 +782,8 @@ class CreateDrawing(bpy.types.Operator):
|
||||
layer_set = material
|
||||
offset = 0
|
||||
sense_factor = 1
|
||||
else:
|
||||
assert False, material
|
||||
|
||||
camera_matrix_i = context.scene.camera.matrix_world.inverted()
|
||||
|
||||
@@ -722,7 +808,6 @@ class CreateDrawing(bpy.types.Operator):
|
||||
bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=0.000001)
|
||||
bmesh.ops.triangle_fill(bm, use_dissolve=True, edges=bm.edges)
|
||||
|
||||
prev_co = None
|
||||
if not usage:
|
||||
sense_factor = 1 # Assume the extrusion vector points in the direction sense
|
||||
no = tool.Drawing.get_extrusion_vector(element).normalized()
|
||||
@@ -739,6 +824,8 @@ class CreateDrawing(bpy.types.Operator):
|
||||
co = Vector((0.0, 0.0, offset))
|
||||
no = tool.Drawing.get_extrusion_vector(element).normalized()
|
||||
no = Vector([1.0, 0.0, 0.0])
|
||||
else:
|
||||
assert False, usage
|
||||
no *= sense_factor
|
||||
last_i = len(layer_set.MaterialLayers) - 1
|
||||
for i, layer in enumerate(layer_set.MaterialLayers):
|
||||
@@ -906,6 +993,10 @@ class CreateDrawing(bpy.types.Operator):
|
||||
if os.path.isfile(svg_path) and self.props.should_use_linework_cache:
|
||||
return svg_path
|
||||
|
||||
ifc = tool.Ifc.get()
|
||||
semantics = None
|
||||
pairs = None
|
||||
|
||||
# in case of printing multiple drawings we need to sync just once
|
||||
if self.sync and self.drawing_index == 0:
|
||||
with profile("sync"):
|
||||
@@ -1309,6 +1400,18 @@ class CreateDrawing(bpy.types.Operator):
|
||||
self.svg_settings = ifcopenshell.geom.settings()
|
||||
self.svg_settings.set("dimensionality", ifcopenshell.ifcopenshell_wrapper.CURVES_SURFACES_AND_SOLIDS)
|
||||
self.svg_settings.set("iterator-output", ifcopenshell.ifcopenshell_wrapper.NATIVE)
|
||||
# SVG edge classification (issue #3668). See edge-classification.md. Settings are
|
||||
# per-drawing, stored in EPset_Drawing and read into self.cprops by import_camera_props.
|
||||
try:
|
||||
self.svg_settings.set("svg-use-edge-classification", self.cprops.use_edge_classification)
|
||||
self.svg_settings.set("svg-render-crease-edges", self.cprops.render_creases)
|
||||
self.svg_settings.set("svg-valley-angle-min-degrees", self.cprops.valley_angle_min_degrees)
|
||||
self.svg_settings.set("svg-render-sharp-edges", self.cprops.render_sharp)
|
||||
self.svg_settings.set("svg-ridge-angle-min-degrees", self.cprops.ridge_angle_min_degrees)
|
||||
self.svg_settings.set("svg-emit-flush-edges", self.cprops.render_flush)
|
||||
except Exception:
|
||||
# Backwards compatibility with older ifcopenshell builds that don't expose these keys.
|
||||
pass
|
||||
self.svg_buffer = ifcopenshell.geom.serializers.buffer()
|
||||
self.serialiser_settings = ifcopenshell.geom.serializer_settings()
|
||||
self.serialiser = ifcopenshell.geom.serializers.svg(
|
||||
@@ -1443,19 +1546,24 @@ class CreateDrawing(bpy.types.Operator):
|
||||
join_criteria = join_criteria.split(",")
|
||||
else:
|
||||
# Drawing convention states that same objects classes with the same material are merged when cut.
|
||||
# We compare the resolved list of constituent material names ("materials.Name") rather than
|
||||
# "material.Name", because for layered walls/slabs the latter resolves to the optional
|
||||
# IfcMaterialLayerSet.LayerSetName, which is frequently left unset (or set inconsistently) even when
|
||||
# two elements share the exact same layer composition. That caused mitred/butt-joined walls with
|
||||
# identical materials to keep a spurious visible seam in the 2D linework. See #6274.
|
||||
join_criteria = [
|
||||
"class",
|
||||
"materials.Name",
|
||||
"material.Name",
|
||||
"/Pset_.*Common/.Status",
|
||||
"EPset_Status.Status",
|
||||
"EPset_Status.UserDefinedStatus",
|
||||
"Material.Name",
|
||||
]
|
||||
|
||||
join_classes = ifcopenshell.util.element.get_pset(self.camera_element, "EPset_Drawing", "JoinClasses")
|
||||
if join_classes:
|
||||
join_classes = tuple(c.strip() for c in join_classes.split(",") if c.strip())
|
||||
else:
|
||||
# Architectural convention only merges these objects by default. E.g. pipe
|
||||
# segments and fittings shouldn't merge. Users may override this per-drawing
|
||||
# via the EPset_Drawing.JoinClasses property (e.g. to also join IfcCovering).
|
||||
join_classes = ("IfcWall", "IfcSlab")
|
||||
|
||||
group = root.find("{http://www.w3.org/2000/svg}g")
|
||||
joined_paths = {}
|
||||
self.is_manifold_cache = {}
|
||||
@@ -1557,8 +1665,7 @@ class CreateDrawing(bpy.types.Operator):
|
||||
)
|
||||
path.attrib["d"] = d
|
||||
|
||||
# Architectural convention only merges these objects. E.g. pipe segments and fittings shouldn't merge.
|
||||
if not element.is_a("IfcWall") and not element.is_a("IfcSlab"):
|
||||
if not any(element.is_a(c) for c in join_classes):
|
||||
continue
|
||||
|
||||
keys = []
|
||||
@@ -2203,7 +2310,11 @@ class SelectAllDrawings(bpy.types.Operator):
|
||||
|
||||
def execute(self, context):
|
||||
props = tool.Drawing.get_document_props()
|
||||
# When filtering to sheeted drawings only, act on the visible drawings only.
|
||||
sheeted_ids = tool.Drawing.get_sheeted_drawing_ids() if props.show_drawings_on_sheets_only else None
|
||||
for drawing in props.drawings:
|
||||
if sheeted_ids is not None and drawing.is_drawing and drawing.ifc_definition_id not in sheeted_ids:
|
||||
continue
|
||||
if drawing.is_selected != self.select_all:
|
||||
drawing.is_selected = self.select_all
|
||||
return {"FINISHED"}
|
||||
@@ -3763,6 +3874,26 @@ class ToggleTargetView(bpy.types.Operator):
|
||||
return {"FINISHED"}
|
||||
|
||||
|
||||
class ToggleDrawingCategorySelection(bpy.types.Operator):
|
||||
bl_idname = "bim.toggle_drawing_category_selection"
|
||||
bl_label = "Toggle Category Selection"
|
||||
bl_description = "Select or deselect all drawings in this view category"
|
||||
bl_options = {"REGISTER", "UNDO"}
|
||||
|
||||
target_view: bpy.props.StringProperty()
|
||||
|
||||
if TYPE_CHECKING:
|
||||
target_view: str
|
||||
|
||||
def execute(self, context):
|
||||
drawings = tool.Drawing.get_visible_drawings_in_category(self.target_view)
|
||||
# If everything visible in the category is already selected, deselect all; otherwise select all.
|
||||
new_state = not all(d.is_selected for d in drawings)
|
||||
for drawing in drawings:
|
||||
drawing.is_selected = new_state
|
||||
return {"FINISHED"}
|
||||
|
||||
|
||||
class ExpandSheet(bpy.types.Operator):
|
||||
bl_idname = "bim.expand_sheet"
|
||||
bl_label = "Expand Sheet"
|
||||
|
||||
@@ -409,6 +409,12 @@ class DocProperties(PropertyGroup):
|
||||
options=set(),
|
||||
)
|
||||
is_editing_drawings: BoolProperty(name="Is Editing Drawings", default=False)
|
||||
show_drawings_on_sheets_only: BoolProperty(
|
||||
name="Show Only Drawings on Sheets",
|
||||
description="Only show drawings that are placed on a sheet",
|
||||
default=False,
|
||||
options=set(),
|
||||
)
|
||||
is_editing_schedules: BoolProperty(name="Is Editing Schedules", default=False)
|
||||
is_editing_references: BoolProperty(name="Is Editing References", default=False)
|
||||
target_view: EnumProperty(
|
||||
@@ -439,6 +445,7 @@ class DocProperties(PropertyGroup):
|
||||
should_use_annotation_cache: bool
|
||||
should_draw_linked_projects: bool
|
||||
is_editing_drawings: bool
|
||||
show_drawings_on_sheets_only: bool
|
||||
is_editing_schedules: bool
|
||||
is_editing_references: bool
|
||||
target_view: Literal["PLAN_VIEW", "ELEVATION_VIEW", "SECTION_VIEW", "REFLECTED_PLAN_VIEW", "MODEL_VIEW"]
|
||||
@@ -536,6 +543,50 @@ class BIMCameraProperties(PropertyGroup):
|
||||
default=True,
|
||||
update=get_update_layer_callback("has_annotation", "HasAnnotation"),
|
||||
)
|
||||
use_edge_classification: BoolProperty(
|
||||
name="Use Edge Classification",
|
||||
description="Classify projection edges into boundary/outline/sharp/crease/flush "
|
||||
"instead of drawing all linework identically. See edge-classification.md",
|
||||
default=False,
|
||||
update=get_update_layer_callback("use_edge_classification", "UseEdgeClassification"),
|
||||
)
|
||||
render_creases: BoolProperty(
|
||||
name="Render Creases",
|
||||
description="Render 'crease' (concave) projection edges",
|
||||
default=True,
|
||||
update=get_update_layer_callback("render_creases", "RenderCreases"),
|
||||
)
|
||||
valley_angle_min_degrees: FloatProperty(
|
||||
name="Valley Angle Minimum",
|
||||
description="Minimum concave dihedral deviation from flat, in degrees, for a projection "
|
||||
"edge to be classified as 'crease' rather than 'flush'",
|
||||
default=12.0,
|
||||
min=0.0,
|
||||
max=180.0,
|
||||
update=get_update_layer_callback("valley_angle_min_degrees", "ValleyAngleMinDegrees"),
|
||||
)
|
||||
render_sharp: BoolProperty(
|
||||
name="Render Sharp",
|
||||
description="Render 'sharp' (convex) projection edges",
|
||||
default=True,
|
||||
update=get_update_layer_callback("render_sharp", "RenderSharp"),
|
||||
)
|
||||
ridge_angle_min_degrees: FloatProperty(
|
||||
name="Ridge Angle Minimum",
|
||||
description="Minimum convex dihedral deviation from flat, in degrees, for a projection "
|
||||
"edge to be classified as 'sharp' rather than 'flush'",
|
||||
default=45.0,
|
||||
min=0.0,
|
||||
max=180.0,
|
||||
update=get_update_layer_callback("ridge_angle_min_degrees", "RidgeAngleMinDegrees"),
|
||||
)
|
||||
render_flush: BoolProperty(
|
||||
name="Render Flush",
|
||||
description="Render 'flush' projection edges (dihedral deviation below both ridge/valley "
|
||||
"thresholds). Omitted by default",
|
||||
default=False,
|
||||
update=get_update_layer_callback("render_flush", "RenderFlush"),
|
||||
)
|
||||
target_view: EnumProperty(
|
||||
name="Target View",
|
||||
default="PLAN_VIEW",
|
||||
|
||||
@@ -110,12 +110,14 @@ class Scheduler:
|
||||
y = self.margin
|
||||
rows = list(sheet.iter_rows())
|
||||
total_rows = len(rows)
|
||||
x = None
|
||||
for i, row in enumerate(rows):
|
||||
# The last row may contain only null values
|
||||
if i == (total_rows - 1) and not [c for c in row if c.value is not None]:
|
||||
continue
|
||||
|
||||
x = self.margin
|
||||
unmerged_height = None
|
||||
for cell in row:
|
||||
if isinstance(cell, openpyxl.cell.cell.MergedCell):
|
||||
column_letter = openpyxl.utils.get_column_letter(cell.column)
|
||||
@@ -230,8 +232,11 @@ class Scheduler:
|
||||
)
|
||||
|
||||
x += unmerged_width
|
||||
|
||||
assert unmerged_height is not None
|
||||
y += unmerged_height
|
||||
|
||||
assert x is not None
|
||||
total_width = x + self.margin
|
||||
total_height = y + self.margin
|
||||
self.svg["width"] = "{}mm".format(total_width)
|
||||
@@ -375,6 +380,7 @@ class Scheduler:
|
||||
tri = 0
|
||||
stop_iterating_over_rows = False
|
||||
# TODO: row spans support?
|
||||
x = None
|
||||
for tr in table.getElementsByType(TableRow):
|
||||
if stop_iterating_over_rows:
|
||||
break
|
||||
@@ -491,6 +497,7 @@ class Scheduler:
|
||||
tri += 1
|
||||
y += height
|
||||
|
||||
assert x is not None
|
||||
total_width = x + self.margin
|
||||
total_height = y + self.margin
|
||||
self.svg["width"] = "{}mm".format(total_width)
|
||||
|
||||
@@ -102,16 +102,16 @@ void angle_circle_head(
|
||||
in vec4 circle_start, in float circle_angle,
|
||||
in bool counterclockwise,
|
||||
out vec4 head[CIRCLE_SEGS+1], out float angle_segs) {
|
||||
|
||||
|
||||
// 1 added to CIRCLE_SEGS because we're number of vertices
|
||||
// for n segments is n+1
|
||||
|
||||
|
||||
float angle_d;
|
||||
angle_d = PI * 2 / CIRCLE_SEGS; // 30d
|
||||
// need to bottom clamp it to 1, otherwise it causes Blender crash at extruding the curve
|
||||
angle_segs = max(1, ceil(circle_angle / angle_d));
|
||||
angle_d = circle_angle / angle_segs;
|
||||
|
||||
|
||||
for(int i = 0; i < (angle_segs + 1); i++) {
|
||||
float angle = angle_d * i;
|
||||
if (counterclockwise) {
|
||||
@@ -143,7 +143,7 @@ void cross_head(in vec4 dir, in float size, out vec4 head[3]) {
|
||||
#define do_vertex(pos, e) (do_vertex_util(pos, vec2(-(e).y, (e).x) / winsize.xy))
|
||||
#define do_vertex_win(pos, e) ( do_vertex( WIN2CLIP( pos ), e ) )
|
||||
|
||||
// if vertex is shared by two segments of the line still need to emit it twice
|
||||
// if vertex is shared by two segments of the line still need to emit it twice
|
||||
// to avoid smoothing artifacts
|
||||
// don't forget to initialize `vec2 EDGE_DIR` for macro to work
|
||||
// `pos0` / `pos1` - vertex position in clip space
|
||||
@@ -197,10 +197,13 @@ void do_circle_head(vec4 pos_w, vec4 head[CIRCLE_SEGS]) {
|
||||
|
||||
def add_verts_sequence(verts, start_i, output_verts, output_edges, closed=False):
|
||||
"""Add sequence of verts to output lists, returns next vertex index"""
|
||||
i = None
|
||||
for i, v in enumerate(verts[:-1], start_i):
|
||||
output_verts.append(v)
|
||||
output_edges.append((i, i + 1))
|
||||
output_verts.append(verts[-1])
|
||||
assert i is not None
|
||||
|
||||
if closed:
|
||||
output_edges.append((i + 1, start_i))
|
||||
return i + 2
|
||||
@@ -273,7 +276,7 @@ class BaseShader:
|
||||
FRAG_GLSL = """
|
||||
uniform vec4 color;
|
||||
uniform float lineWidth;
|
||||
|
||||
|
||||
in float smoothline;
|
||||
out vec4 fragColor;
|
||||
void main() {
|
||||
|
||||
@@ -1449,6 +1449,7 @@ class SvgWriter:
|
||||
angle_tg = rise / run
|
||||
angle = round(degrees(atan(angle_tg)))
|
||||
else:
|
||||
angle_tg = None
|
||||
angle = 90
|
||||
|
||||
# ues SLOPE_ANGLE as default
|
||||
@@ -1462,6 +1463,7 @@ class SvgWriter:
|
||||
elif object_type == "SLOPE_PERCENT":
|
||||
if angle == 90:
|
||||
return "-"
|
||||
assert angle_tg is not None
|
||||
return f"{round(angle_tg * 100)} %"
|
||||
|
||||
tag = element.Description or get_label_text()
|
||||
|
||||
@@ -113,6 +113,19 @@ class BIM_PT_camera(Panel):
|
||||
row.prop(props, "fill_mode")
|
||||
row = self.layout.row()
|
||||
row.prop(props, "cut_mode")
|
||||
|
||||
row = self.layout.row()
|
||||
row.prop(props, "use_edge_classification")
|
||||
if props.use_edge_classification:
|
||||
row = self.layout.row()
|
||||
row.prop(props, "render_creases")
|
||||
row.prop(props, "valley_angle_min_degrees")
|
||||
row = self.layout.row()
|
||||
row.prop(props, "render_sharp")
|
||||
row.prop(props, "ridge_angle_min_degrees")
|
||||
row = self.layout.row()
|
||||
row.prop(props, "render_flush")
|
||||
|
||||
row = self.layout.row()
|
||||
row.prop(props, "width")
|
||||
row = self.layout.row()
|
||||
@@ -319,6 +332,8 @@ class BIM_PT_drawings(Panel):
|
||||
|
||||
row3.separator(factor=0.5, type="SPACE")
|
||||
|
||||
row3.operator("bim.copy_annotation_to_drawing", icon="PASTEDOWN", text="")
|
||||
|
||||
row3.operator("bim.select_all_drawings", icon="CHECKBOX_HLT", text="")
|
||||
row3.operator("bim.create_drawing", text="", icon="OUTPUT")
|
||||
row3.operator("bim.convert_svg_to_dxf", text="", icon="SEQ_PREVIEW").view = active_drawing.name
|
||||
@@ -326,6 +341,7 @@ class BIM_PT_drawings(Panel):
|
||||
self.layout.template_list(
|
||||
"BIM_UL_drawinglist", "", self.props, "drawings", self.props, "active_drawing_index"
|
||||
)
|
||||
self.layout.prop(self.props, "show_drawings_on_sheets_only")
|
||||
|
||||
|
||||
class BIM_PT_schedules(Panel):
|
||||
@@ -858,8 +874,8 @@ class BIM_UL_drawinglist(bpy.types.UIList):
|
||||
layout.label(text="", translate=False)
|
||||
return
|
||||
|
||||
row = layout.row(align=True)
|
||||
if item.is_drawing:
|
||||
row = layout.row(align=True)
|
||||
row.label(text="", icon="BLANK1")
|
||||
selected_icon = "CHECKBOX_HLT" if item.is_selected else "CHECKBOX_DEHLT"
|
||||
row.prop(item, "is_selected", text="", icon=selected_icon, emboss=False)
|
||||
@@ -880,6 +896,9 @@ class BIM_UL_drawinglist(bpy.types.UIList):
|
||||
item.ifc_definition_id
|
||||
)
|
||||
else:
|
||||
# Give category headers a distinct inset background so they stand out from drawing rows.
|
||||
box = layout.box()
|
||||
row = box.row(align=True)
|
||||
if item.target_view == "PLAN_VIEW":
|
||||
icon = "UV_FACESEL"
|
||||
elif item.target_view == "ELEVATION_VIEW":
|
||||
@@ -900,7 +919,55 @@ class BIM_UL_drawinglist(bpy.types.UIList):
|
||||
op = row.operator("bim.toggle_target_view", text="", emboss=False, icon="DISCLOSURE_TRI_RIGHT")
|
||||
op.target_view = item.target_view
|
||||
op.option = "EXPAND"
|
||||
row.prop(item, "name", text="", icon=icon, emboss=False)
|
||||
group = tool.Drawing.get_visible_drawings_in_category(item.target_view)
|
||||
all_selected = bool(group) and all(d.is_selected for d in group)
|
||||
row.operator(
|
||||
"bim.toggle_drawing_category_selection",
|
||||
text="",
|
||||
icon="CHECKBOX_HLT" if all_selected else "CHECKBOX_DEHLT",
|
||||
emboss=False,
|
||||
).target_view = item.target_view
|
||||
row.separator(factor=0.5, type="SPACE")
|
||||
# Clicking the header name toggles expand/contract, same as the disclosure triangle.
|
||||
op = row.operator("bim.toggle_target_view", text=item.name, icon=icon, emboss=False)
|
||||
op.target_view = item.target_view
|
||||
op.option = "CONTRACT" if item.is_expanded else "EXPAND"
|
||||
|
||||
def filter_items(self, context, data: DocProperties, propname: str):
|
||||
drawings = getattr(data, propname)
|
||||
helper_funcs = bpy.types.UI_UL_list
|
||||
|
||||
flt_flags = []
|
||||
flt_neworder = []
|
||||
|
||||
if self.filter_name:
|
||||
flt_flags = helper_funcs.filter_items_by_name(
|
||||
self.filter_name,
|
||||
self.bitflag_filter_item,
|
||||
drawings,
|
||||
"name",
|
||||
reverse=self.use_filter_sort_reverse,
|
||||
)
|
||||
if not flt_flags:
|
||||
flt_flags = [self.bitflag_filter_item] * len(drawings)
|
||||
|
||||
props = tool.Drawing.get_document_props()
|
||||
if props.show_drawings_on_sheets_only:
|
||||
ifc_file = tool.Ifc.get()
|
||||
sheeted_ids = tool.Drawing.get_sheeted_drawing_ids()
|
||||
# Target view headers are only shown if they contain a sheeted drawing.
|
||||
sheeted_target_views = {
|
||||
tool.Drawing.get_drawing_target_view(ifc_file.by_id(drawing_id)) for drawing_id in sheeted_ids
|
||||
}
|
||||
for i, item in enumerate(drawings):
|
||||
if item.is_drawing:
|
||||
is_visible = item.ifc_definition_id in sheeted_ids
|
||||
else:
|
||||
is_visible = item.target_view in sheeted_target_views
|
||||
if not is_visible:
|
||||
flt_flags[i] &= ~self.bitflag_filter_item
|
||||
|
||||
return flt_flags, flt_neworder
|
||||
|
||||
|
||||
class BIM_UL_sheets(bpy.types.UIList):
|
||||
@@ -964,14 +1031,14 @@ class BIM_UL_sheets(bpy.types.UIList):
|
||||
|
||||
if self.filter_name:
|
||||
filter_name = self.filter_name.lower()
|
||||
active_sheet = None
|
||||
active_sheet_index = None
|
||||
for sheet in data.sheets:
|
||||
if sheet.is_sheet:
|
||||
active_sheet = sheet
|
||||
active_sheet_index = len(flt_flags)
|
||||
if filter_name in sheet.name.lower() or filter_name in sheet.identification.lower():
|
||||
flt_flags.append(self.bitflag_filter_item)
|
||||
if not sheet.is_sheet:
|
||||
assert active_sheet_index is not None
|
||||
flt_flags[active_sheet_index] = self.bitflag_filter_item
|
||||
else:
|
||||
flt_flags.append(0)
|
||||
|
||||
@@ -225,6 +225,9 @@ class AnnotationToolUI:
|
||||
def draw_edit_object_interface(cls, context):
|
||||
if DecoratorData.get_text_data(bpy.context.active_object):
|
||||
add_layout_hotkey_operator(cls.layout, "Edit Text", "S_E", "")
|
||||
if bpy.ops.bim.copy_annotation_to_drawing.poll():
|
||||
row = cls.layout.row(align=True)
|
||||
row.operator("bim.copy_annotation_to_drawing", icon="PASTEDOWN", text="Copy To Drawing")
|
||||
|
||||
@classmethod
|
||||
def draw_type_selection_interface(cls):
|
||||
|
||||
@@ -75,9 +75,13 @@ class Helper:
|
||||
for face in bm.faces:
|
||||
if len(face.verts) > 4:
|
||||
potential_faces.append(face)
|
||||
|
||||
# TODO: replace with next(..., None)
|
||||
face = None
|
||||
for face in potential_faces:
|
||||
if face.normal.z < -0.1:
|
||||
break
|
||||
assert face is not None
|
||||
|
||||
profile = [l.vert.index for l in face.loops]
|
||||
extrusion = self.detect_extrusion_edge(bm, face)
|
||||
@@ -108,10 +112,12 @@ class Helper:
|
||||
if not potential_faces:
|
||||
potential_faces = bm.faces
|
||||
|
||||
# TODO: replace with next(..., None)
|
||||
face = None
|
||||
for face in potential_faces:
|
||||
if face.normal.z < -0.1:
|
||||
break
|
||||
|
||||
assert face is not None
|
||||
profile = [l.vert.index for l in face.loops]
|
||||
extrusion = self.detect_extrusion_edge(bm, face)
|
||||
|
||||
@@ -145,9 +151,12 @@ class Helper:
|
||||
if total_verts > 4:
|
||||
potential_faces.append(face)
|
||||
|
||||
# TODO: replace with next(..., None)
|
||||
face = None
|
||||
for face in potential_faces:
|
||||
if face.normal.z < -0.1:
|
||||
break
|
||||
assert face is not None
|
||||
|
||||
end_faces = []
|
||||
end_face_normal = face.normal
|
||||
|
||||
@@ -581,7 +581,11 @@ class UpdateRepresentation(bpy.types.Operator, tool.Ifc.Operator):
|
||||
if has_openings and not self.apply_openings:
|
||||
# Meshlike things with openings can only be updated without openings applied.
|
||||
if self.from_ui:
|
||||
self.report({"ERROR"}, f"Object '{obj.name}' has openings - representation cannot be updated.")
|
||||
self.report(
|
||||
{"ERROR"},
|
||||
f"Object '{obj.name}' has openings. "
|
||||
"ALT+click the button to bake the openings into the new representation.",
|
||||
)
|
||||
return
|
||||
|
||||
if not product.is_a("IfcGridAxis"):
|
||||
@@ -3523,12 +3527,15 @@ class EditRepresentationItemShapeAspect(bpy.types.Operator, tool.Ifc.Operator):
|
||||
if props.representation_item_shape_aspect == "NEW":
|
||||
active_representation = tool.Geometry.get_active_representation(obj)
|
||||
# find IfcProductRepresentationSelect based on current representation
|
||||
product_shape = None
|
||||
if hasattr(element, "Representation"): # IfcProduct
|
||||
product_shape = element.Representation
|
||||
else: # IfcTypeProduct
|
||||
for representation_map in element.RepresentationMaps:
|
||||
if representation_map.MappedRepresentation == active_representation:
|
||||
product_shape = representation_map
|
||||
assert product_shape is not None
|
||||
|
||||
previous_shape_aspect_id = props.active_item.shape_aspect_id
|
||||
# will be None if item didn't had a shape aspect
|
||||
previous_shape_aspect = tool.Ifc.get_entity_by_id(previous_shape_aspect_id)
|
||||
@@ -3878,6 +3885,8 @@ class AddSweptAreaSolidItem(bpy.types.Operator, tool.Ifc.Operator):
|
||||
curve = builder.rectangle(size=Vector((0.5, 0.5)) / unit_scale)
|
||||
elif self.shape == "CYLINDER":
|
||||
curve = builder.circle(radius=0.25 / unit_scale)
|
||||
else:
|
||||
assert False, self.shape
|
||||
item = builder.extrude(
|
||||
curve,
|
||||
magnitude=0.5 / unit_scale,
|
||||
@@ -4115,6 +4124,31 @@ class OverrideMoveSelect(bpy.types.Operator):
|
||||
self.new_active_obj = obj
|
||||
return {"FINISHED"}
|
||||
|
||||
# Get arrays
|
||||
ifc_file = tool.Ifc.get()
|
||||
array_parents_to_move: list[bpy.types.Object] = []
|
||||
for obj in list(context.selected_objects):
|
||||
element = tool.Ifc.get_entity(obj)
|
||||
if not element:
|
||||
continue
|
||||
pset = ifcopenshell.util.element.get_pset(element, "BBIM_Array")
|
||||
if not pset:
|
||||
continue
|
||||
parent_element = ifc_file.by_guid(pset["Parent"])
|
||||
parent_obj = tool.Ifc.get_object(parent_element)
|
||||
if parent_obj not in array_parents_to_move:
|
||||
array_parents_to_move.append(parent_obj)
|
||||
if element.GlobalId != pset["Parent"]:
|
||||
obj.select_set(False)
|
||||
|
||||
if array_parents_to_move:
|
||||
for parent_obj in array_parents_to_move:
|
||||
parent_element = tool.Ifc.get_entity(parent_obj)
|
||||
for array_obj in tool.Array.get_all_objects(parent_element):
|
||||
array_obj.select_set(True)
|
||||
self.new_active_obj = parent_obj
|
||||
return {"FINISHED"}
|
||||
|
||||
# Get nests
|
||||
props = tool.Nest.get_nest_props()
|
||||
not_editing_objs = [o.obj for o in props.not_editing_objects]
|
||||
|
||||
@@ -163,14 +163,52 @@ class AssignGroup(bpy.types.Operator, tool.Ifc.Operator):
|
||||
def _execute(self, context):
|
||||
if not self.is_assigning:
|
||||
return bpy.ops.bim.unassign_group(group=self.group)
|
||||
ifc_file = tool.Ifc.get()
|
||||
group = ifc_file.by_id(self.group)
|
||||
products = [
|
||||
element
|
||||
for o in tool.Blender.get_selected_objects(include_active=False)
|
||||
if (element := tool.Ifc.get_entity(o))
|
||||
]
|
||||
ifcopenshell.api.group.assign_group(tool.Ifc.get(), products=products, group=tool.Ifc.get().by_id(self.group))
|
||||
relocated_annotations = self.unassign_from_previous_drawing(ifc_file, group, products)
|
||||
ifcopenshell.api.group.assign_group(ifc_file, products=products, group=group)
|
||||
self.relocate_annotations_to_drawing(relocated_annotations, group)
|
||||
self.report({"INFO"}, f"Assigned {len(products)} objects to group.")
|
||||
|
||||
def unassign_from_previous_drawing(self, ifc_file, group, products) -> list[ifcopenshell.entity_instance]:
|
||||
"""Assigning an annotation to a group that represents a drawing means the
|
||||
annotation should belong to that drawing only, so it needs to leave
|
||||
whichever drawing it was previously part of, instead of ending up
|
||||
visible in both at once.
|
||||
"""
|
||||
new_drawing = tool.Drawing.get_group_drawing(group)
|
||||
if not new_drawing:
|
||||
return []
|
||||
relocated = []
|
||||
for product in products:
|
||||
if not product.is_a("IfcAnnotation") or product.ObjectType == "DRAWING":
|
||||
continue
|
||||
old_drawing = tool.Drawing.get_annotation_drawing(product)
|
||||
if not old_drawing or old_drawing.id() == new_drawing.id():
|
||||
continue
|
||||
if old_group := tool.Drawing.get_drawing_group(old_drawing):
|
||||
ifcopenshell.api.group.unassign_group(ifc_file, products=[product], group=old_group)
|
||||
relocated.append(product)
|
||||
return relocated
|
||||
|
||||
def relocate_annotations_to_drawing(self, products, group) -> None:
|
||||
"""Move the relocated annotations into the new drawing's collection and
|
||||
depth, now that they have actually been assigned to its group.
|
||||
"""
|
||||
if not products:
|
||||
return
|
||||
new_drawing = tool.Drawing.get_group_drawing(group)
|
||||
new_camera = tool.Ifc.get_object(new_drawing) or tool.Drawing.import_drawing(new_drawing)
|
||||
for product in products:
|
||||
if obj := tool.Ifc.get_object(product):
|
||||
tool.Drawing.ensure_annotation_in_drawing_plane(obj, camera=new_camera)
|
||||
tool.Collector.assign(obj)
|
||||
|
||||
|
||||
class UnassignGroup(bpy.types.Operator, tool.Ifc.Operator):
|
||||
bl_idname = "bim.unassign_group"
|
||||
|
||||
@@ -156,6 +156,7 @@ class RadianceRender(bpy.types.Operator):
|
||||
print(f"Quality: {quality}, Detail: {detail}, Variability: {variability}")
|
||||
print(f"Output directory: {output_dir}")
|
||||
|
||||
hdr_image_path, hdr_mask_path, sky_map_cal_path = None, None
|
||||
if use_hdr:
|
||||
hdr_image = "noon_grass_2k.hdr"
|
||||
hdr_mask = "noon_grass_2k_mask.hdr"
|
||||
@@ -254,6 +255,9 @@ class RadianceRender(bpy.types.Operator):
|
||||
# 4 0 0 -1 180
|
||||
|
||||
if use_hdr and choose_hdr_image == "Noon":
|
||||
assert hdr_image_path is not None
|
||||
assert hdr_mask_path is not None
|
||||
assert sky_map_cal_path is not None
|
||||
|
||||
with open(sky_file_path, "w") as f:
|
||||
f.write(sky_description_str)
|
||||
|
||||
@@ -564,6 +564,7 @@ class SelectAllArrayObjects(bpy.types.Operator):
|
||||
except RuntimeError:
|
||||
self.report({"ERROR"}, f"Objects that don't have an array parent, were deselected.")
|
||||
object.select_set(False)
|
||||
continue
|
||||
|
||||
array_objects = tool.Array.get_all_objects(parent_element)
|
||||
tool.Blender.set_objects_selection(
|
||||
|
||||
@@ -93,6 +93,30 @@ def _stroke_lines_alpha(
|
||||
gpu.state.blend_set("NONE")
|
||||
|
||||
|
||||
def _connected_components(
|
||||
vertex_groups: dict[int, list[bmesh.types.BMVert]],
|
||||
) -> list[list[bmesh.types.BMVert]]:
|
||||
"""Split each vertex group's members into their connected components,
|
||||
since a duplicated arc/circle loop shares its source loop's group index."""
|
||||
components = []
|
||||
for verts in vertex_groups.values():
|
||||
remaining = set(verts)
|
||||
while remaining:
|
||||
seed = remaining.pop()
|
||||
stack = [seed]
|
||||
component = [seed]
|
||||
while stack:
|
||||
v = stack.pop()
|
||||
for edge in v.link_edges:
|
||||
other = edge.other_vert(v)
|
||||
if other in remaining:
|
||||
remaining.discard(other)
|
||||
stack.append(other)
|
||||
component.append(other)
|
||||
components.append(component)
|
||||
return components
|
||||
|
||||
|
||||
class ProfileDecorator:
|
||||
installed = None
|
||||
|
||||
@@ -265,7 +289,7 @@ class ProfileDecorator:
|
||||
# Draw arcs
|
||||
arc_centroids = []
|
||||
arc_segments = []
|
||||
for arc in arcs.values():
|
||||
for arc in _connected_components(arcs):
|
||||
if len(arc) != 3:
|
||||
continue
|
||||
sorted_arc = [None, None, None]
|
||||
@@ -292,7 +316,7 @@ class ProfileDecorator:
|
||||
# Draw circles
|
||||
circle_centroids = []
|
||||
circle_segments = []
|
||||
for circle in circles.values():
|
||||
for circle in _connected_components(circles):
|
||||
if len(circle) != 2:
|
||||
continue
|
||||
p1 = obj.matrix_world @ circle[0].co
|
||||
|
||||
@@ -408,6 +408,8 @@ class MEPGenerator:
|
||||
compare = tool.Cad.is_x(requested_value, fitting_value, compare_precision)
|
||||
elif isinstance(fitting_value, list):
|
||||
compare = tool.Cad.are_vectors_equal(requested_value, Vector(fitting_value), precision)
|
||||
else:
|
||||
assert False, f"{key} {second_key}"
|
||||
return compare
|
||||
|
||||
ignore_keys = []
|
||||
@@ -476,11 +478,13 @@ class MEPGenerator:
|
||||
if predefined_type == "OBSTRUCTION":
|
||||
return packed_data
|
||||
|
||||
start_port = None
|
||||
for port in ports:
|
||||
port_local_position = V(*port.ObjectPlacement.RelativePlacement.Location.Coordinates)
|
||||
if tool.Cad.is_x(port_local_position.length, 0.0):
|
||||
start_port = port
|
||||
break
|
||||
assert start_port is not None
|
||||
|
||||
connected_port = tool.System.get_connected_port(start_port)
|
||||
connected_element = tool.System.get_port_relating_element(connected_port)
|
||||
|
||||
@@ -325,7 +325,7 @@ class AddOccurrence(bpy.types.Operator, tool.Ifc.Operator):
|
||||
if self.from_invoke and str(self.relating_type_id) in AuthoringData.data["relating_type_id"]:
|
||||
props.relating_type_id = str(self.relating_type_id)
|
||||
|
||||
building_obj = None
|
||||
building_obj, building_element = None, None
|
||||
if len(context.selected_objects) == 1 and context.active_object:
|
||||
building_obj = context.active_object
|
||||
building_element = tool.Ifc.get_entity(building_obj)
|
||||
|
||||
@@ -593,6 +593,8 @@ class DumbProfileJoiner:
|
||||
axisl = (profile2.matrix_world.inverted() @ axis1[1]) - (profile2.matrix_world.inverted() @ axis1[0])
|
||||
elif connection1 == "ATSTART":
|
||||
axisl = (profile2.matrix_world.inverted() @ axis1[0]) - (profile2.matrix_world.inverted() @ axis1[1])
|
||||
else:
|
||||
assert False, connection1
|
||||
xy_angle = degrees(Vector((1, 0)).angle_signed(axisl.normalized().to_2d()))
|
||||
if xy_angle >= -135 and xy_angle <= -45:
|
||||
closest_plane = "bottom"
|
||||
@@ -617,6 +619,8 @@ class DumbProfileJoiner:
|
||||
axisl = (profile1.matrix_world.inverted() @ axis2[1]) - (profile1.matrix_world.inverted() @ axis2[0])
|
||||
elif connection2 == "ATSTART":
|
||||
axisl = (profile1.matrix_world.inverted() @ axis2[0]) - (profile1.matrix_world.inverted() @ axis2[1])
|
||||
else:
|
||||
assert False, connection2
|
||||
xy_angle2 = degrees(Vector((1, 0)).angle_signed(axisl.normalized().to_2d()))
|
||||
if xy_angle2 >= -135 and xy_angle2 <= -45:
|
||||
closest_plane2 = "bottom"
|
||||
@@ -844,6 +848,8 @@ class DumbProfileJoiner:
|
||||
else:
|
||||
y_axis = obj.matrix_world.to_quaternion() @ Vector((0, 1, 0))
|
||||
z_axis = obj.matrix_world.to_quaternion() @ Vector((-1, 0, 0))
|
||||
else:
|
||||
assert False, plane
|
||||
return self.create_matrix(p, x_axis, y_axis, z_axis)
|
||||
|
||||
def create_matrix(self, p: Vector, x: Vector, y: Vector, z: Vector) -> Matrix:
|
||||
|
||||
@@ -508,6 +508,7 @@ class EditSketchExtrusionProfile(bpy.types.Operator, tool.Ifc.Operator):
|
||||
converter.run()
|
||||
|
||||
profile = tool.Ifc.get().createIfcArbitraryClosedProfileDef("AREA")
|
||||
curve = None
|
||||
for path in converter.paths:
|
||||
points = []
|
||||
lines = path[0]
|
||||
@@ -517,6 +518,7 @@ class EditSketchExtrusionProfile(bpy.types.Operator, tool.Ifc.Operator):
|
||||
points.append(tool.Ifc.get().createIfcCartesianPoint(local_point))
|
||||
points.append(points[0])
|
||||
curve = tool.Ifc.get().createIfcPolyline(points)
|
||||
assert curve
|
||||
profile.OuterCurve = curve
|
||||
|
||||
old_profile = extrusion.SweptArea
|
||||
|
||||
@@ -1577,6 +1577,7 @@ class DumbWallJoiner:
|
||||
# Get the ATEND connection from wall1 to use it in wall2
|
||||
relating_element = None
|
||||
connections = element1.ConnectedTo
|
||||
relating_connection, description = ..., ...
|
||||
for conn in connections:
|
||||
if conn.is_a("IfcRelConnectsPathElements") and conn.RelatingConnectionType == "ATEND":
|
||||
relating_element = conn.RelatedElement
|
||||
@@ -1591,6 +1592,7 @@ class DumbWallJoiner:
|
||||
description = conn.Description
|
||||
bonsai.core.geometry.remove_connection(tool.Geometry, connection=conn)
|
||||
if relating_element:
|
||||
assert relating_connection is not ... and description is not ...
|
||||
ifcopenshell.api.geometry.connect_path(
|
||||
tool.Ifc.get(),
|
||||
relating_element=relating_element,
|
||||
|
||||
@@ -714,6 +714,8 @@ class AppendLibraryElement(bpy.types.Operator, tool.Ifc.Operator):
|
||||
representations = element.RepresentationMaps or []
|
||||
elif element.is_a("IfcProduct"):
|
||||
representations = [element.Representation] if element.Representation else []
|
||||
else:
|
||||
assert False, element
|
||||
for representation in representations or []:
|
||||
for element in self.file.traverse(representation):
|
||||
if not element.is_a("IfcRepresentationItem") or not element.StyledByItem:
|
||||
@@ -2029,6 +2031,7 @@ class ExportIFC(bpy.types.Operator, ExportHelper):
|
||||
project_props = tool.Project.get_project_props()
|
||||
prefs = tool.Blender.get_addon_preferences()
|
||||
project_props.use_relative_project_path = self.use_relative_path
|
||||
old_history_size, old_undo_steps = None, None
|
||||
if prefs.should_disable_undo_on_save:
|
||||
old_history_size = tool.Ifc.get().history_size
|
||||
old_undo_steps = context.preferences.edit.undo_steps
|
||||
@@ -2036,6 +2039,7 @@ class ExportIFC(bpy.types.Operator, ExportHelper):
|
||||
context.preferences.edit.undo_steps = 0
|
||||
IfcStore.execute_ifc_operator(self, context)
|
||||
if prefs.should_disable_undo_on_save:
|
||||
assert old_history_size is not None and old_undo_steps is not None
|
||||
tool.Ifc.get().history_size = old_history_size
|
||||
context.preferences.edit.undo_steps = old_undo_steps
|
||||
return {"FINISHED"}
|
||||
|
||||
@@ -113,6 +113,8 @@ class EditPset(bpy.types.Operator, tool.Ifc.Operator):
|
||||
elif props.active_pset_type == "QTO":
|
||||
pset = ifcopenshell.api.pset.add_qto(self.file, product=element, name=props.active_pset_name)
|
||||
props.active_pset_id = pset.id()
|
||||
else:
|
||||
assert False
|
||||
|
||||
if self.properties:
|
||||
properties = json.loads(self.properties)
|
||||
|
||||
@@ -228,6 +228,8 @@ def get_qto_name(self: "PsetProperties", context: bpy.types.Context) -> tool.Ble
|
||||
if "bpy.data.objects" in pset_type:
|
||||
if prop_type == "PsetProperties":
|
||||
results = get_object_qto_name(self, context)
|
||||
else:
|
||||
assert False
|
||||
elif prop_type == "TaskPsetProperties":
|
||||
results = get_task_qto_names(self, context)
|
||||
elif prop_type == "ResourcePsetProperties":
|
||||
|
||||
@@ -480,6 +480,7 @@ class BIM_PT_material_psets(Panel):
|
||||
def draw(self, context):
|
||||
assert self.layout
|
||||
props = tool.Material.get_material_props()
|
||||
ifc_definition_id = None
|
||||
if material := props.active_material:
|
||||
ifc_definition_id = material.ifc_definition_id
|
||||
|
||||
|
||||
@@ -225,7 +225,7 @@ def get_opening_depth(obj: bpy.types.Object) -> float:
|
||||
if is_opening_horizontal(obj):
|
||||
return get_height(obj)
|
||||
else:
|
||||
return get_width(obj)
|
||||
return get_y(obj)
|
||||
|
||||
|
||||
def get_opening_mapping_area(obj: bpy.types.Object) -> float:
|
||||
|
||||
@@ -27,6 +27,7 @@ import ifcopenshell.api.material
|
||||
import ifcopenshell.api.pset
|
||||
import ifcopenshell.api.root
|
||||
import ifcopenshell.util.element
|
||||
import ifcopenshell.util.representation
|
||||
import ifcopenshell.util.schema
|
||||
import ifcopenshell.util.shape_builder
|
||||
import ifcopenshell.util.type
|
||||
@@ -129,13 +130,25 @@ class ReassignClass(bpy.types.Operator, tool.Ifc.Operator):
|
||||
same_ifc_product = element.is_a(ifc_product)
|
||||
|
||||
if not same_ifc_product:
|
||||
if not (element.is_a("IfcElement") and ifc_product == "IfcElementType") and not (
|
||||
element.is_a("IfcElementType") and ifc_product == "IfcElement"
|
||||
):
|
||||
self.report(
|
||||
{"ERROR"}, f"Not supported class reassignment for object '{obj.name}' -> {ifc_product}."
|
||||
# A spatial element (e.g. IfcSite) anchors the containment
|
||||
# hierarchy, so only allow reassigning it to another family when
|
||||
# it actually carries geometry - i.e. it's a real modelled thing
|
||||
# (a bench dropped onto IfcSite -> IfcFurniture) rather than an
|
||||
# empty spatial container we'd be turning into a loose element.
|
||||
# IfcSpatialStructureElement covers IFC2X3, which has no
|
||||
# IfcSpatialElement supertype.
|
||||
is_spatial = element.is_a("IfcSpatialElement") or element.is_a("IfcSpatialStructureElement")
|
||||
if is_spatial:
|
||||
has_geometry = (
|
||||
next(ifcopenshell.util.representation.get_representations_iter(element), None) is not None
|
||||
)
|
||||
return {"CANCELLED"}
|
||||
if not has_geometry:
|
||||
self.report(
|
||||
{"ERROR"},
|
||||
f"Cannot reassign '{obj.name}' ({element.is_a()}) to {ifc_product}: "
|
||||
"a spatial element can only be reassigned to another class when it has geometry.",
|
||||
)
|
||||
return {"CANCELLED"}
|
||||
|
||||
props = tool.Blender.get_object_bim_props(obj)
|
||||
props.is_reassigning_class = False
|
||||
@@ -400,12 +413,13 @@ class UnlinkObject(bpy.types.Operator, tool.Ifc.Operator):
|
||||
skip_invoke: bpy.props.BoolProperty(default=False, options={"SKIP_SAVE"})
|
||||
|
||||
def _execute(self, context):
|
||||
objects: list[bpy.types.Object]
|
||||
if self.obj:
|
||||
objects = [bpy.data.objects.get(self.obj)]
|
||||
requested_obj = bpy.data.objects.get(self.obj)
|
||||
objects = [requested_obj] if requested_obj is not None else []
|
||||
else:
|
||||
objects = context.selected_objects
|
||||
|
||||
objects: list[bpy.types.Object]
|
||||
for obj in objects:
|
||||
was_active_object = obj == context.active_object
|
||||
|
||||
@@ -617,10 +631,13 @@ class AddElement(bpy.types.Operator, tool.Ifc.Operator):
|
||||
local_z = wall_matrix.to_3x3() @ Vector((0, 0, 1))
|
||||
direction_sense = getattr(usage, "DirectionSense", "POSITIVE")
|
||||
|
||||
if usage.LayerSetDirection == "AXIS2":
|
||||
layer_set_direction = usage.LayerSetDirection
|
||||
if layer_set_direction == "AXIS2":
|
||||
z_axis = tuple(local_y) if direction_sense == "POSITIVE" else tuple(-local_y)
|
||||
elif usage.LayerSetDirection == "AXIS3":
|
||||
elif layer_set_direction == "AXIS3":
|
||||
z_axis = tuple(local_z) if direction_sense == "POSITIVE" else tuple(-local_z)
|
||||
else:
|
||||
assert False, layer_set_direction
|
||||
|
||||
item = builder.extrude(
|
||||
profile,
|
||||
@@ -750,6 +767,8 @@ class AddElement(bpy.types.Operator, tool.Ifc.Operator):
|
||||
WebThickness=default_web_thickness / unit_scale,
|
||||
FlangeThickness=default_flange_thickness / unit_scale,
|
||||
)
|
||||
else:
|
||||
assert False, representation_template
|
||||
|
||||
rel = ifcopenshell.api.material.assign_material(
|
||||
tool.Ifc.get(), products=[element], type="IfcMaterialProfileSet"
|
||||
|
||||
@@ -1009,6 +1009,7 @@ class ColourByProperty(Operator):
|
||||
palette = props.palette
|
||||
is_qualitative = palette in ("tab10", "paired")
|
||||
|
||||
colours = None
|
||||
if is_qualitative:
|
||||
colours = tool.Search.get_qualitative_palette(palette)
|
||||
|
||||
@@ -1035,6 +1036,7 @@ class ColourByProperty(Operator):
|
||||
if value in colourscheme:
|
||||
colourscheme[value]["total"] += 1
|
||||
else:
|
||||
assert colours is not None
|
||||
colourscheme[value] = {"colour": next(colours)[0:3], "total": 1}
|
||||
obj.color = (*colourscheme[value]["colour"], 1)
|
||||
else:
|
||||
@@ -1139,6 +1141,7 @@ class SelectByProperty(Operator):
|
||||
|
||||
is_qualitative = palette in ("tab10", "paired")
|
||||
|
||||
values = None
|
||||
if not is_qualitative:
|
||||
values = []
|
||||
for colour in props.colourscheme:
|
||||
|
||||
@@ -12,7 +12,7 @@ function create_gantt_chart(json_data) {
|
||||
vShowTaskInfoLink: 1, // Show link in tool tip (0/1)
|
||||
vShowEndWeekDate: 0, // Show/Hide the date for the last day of the week in header for daily
|
||||
vUseSingleCell: 10000, // Set the threshold cell per table row (Helps performance for large data.
|
||||
vFormatArr: ['Day', 'Week', 'Month', 'Quarter'], // Even with setUseSingleCell using Hour format on such a large chart can cause issues in some browsers,
|
||||
vFormatArr: ['Hour', 'Day', 'Week', 'Month', 'Quarter'], // vUseSingleCell keeps Hour usable on large charts.
|
||||
vShowRes: true, // Disable the resource column.
|
||||
vShowComp: false, // Disable the completion column.
|
||||
vShowDur: false, // Disable the duration column, because jsgantt doesn't calculate durations the way we want.
|
||||
|
||||
@@ -281,11 +281,11 @@ class BIM_PT_work_schedules(Panel):
|
||||
def draw_task_operators(self) -> None:
|
||||
row = self.layout.row(align=True)
|
||||
row.alignment = "RIGHT"
|
||||
ifc_definition_id = None
|
||||
task, ifc_definition_id = None, None
|
||||
if self.tprops.tasks and self.props.active_task_index < len(self.tprops.tasks):
|
||||
task = self.tprops.tasks[self.props.active_task_index]
|
||||
ifc_definition_id = task.ifc_definition_id
|
||||
if ifc_definition_id:
|
||||
if task and ifc_definition_id:
|
||||
if self.props.active_task_id:
|
||||
if self.props.editing_task_type == "TASKTIME":
|
||||
row.operator("bim.edit_task_time", text="", icon="CHECKMARK")
|
||||
@@ -341,6 +341,8 @@ class BIM_PT_work_schedules(Panel):
|
||||
row.prop(self.props, "other_columns", text="")
|
||||
column_type, name = self.props.other_columns.split(".")
|
||||
data_type = "string"
|
||||
else:
|
||||
assert False, column_type
|
||||
row.operator("bim.set_task_sort_column", text="", icon="SORTALPHA").column = f"{column_type}.{name}"
|
||||
row.prop(
|
||||
self.props, "is_sort_reversed", text="", icon="SORT_DESC" if self.props.is_sort_reversed else "SORT_ASC"
|
||||
|
||||
@@ -516,7 +516,7 @@ class SetContainerVisibility(bpy.types.Operator):
|
||||
if self.mode == "ISOLATE":
|
||||
if tool.Ifc.get_schema() == "IFC2X3":
|
||||
containers = tool.Ifc.get().by_type("IfcSpatialStructureElement")
|
||||
elif tool.Ifc.get_schema() != "IFC2X3":
|
||||
else:
|
||||
containers = set(tool.Ifc.get().by_type("IfcSpatialElement"))
|
||||
containers -= set(tool.Ifc.get().by_type("IfcSpatialZone"))
|
||||
for container in containers:
|
||||
|
||||
@@ -125,6 +125,7 @@ class BIM_PT_spatial_decomposition(Panel):
|
||||
row.label(text="Warning: No Default Container", icon="ERROR")
|
||||
row.operator("bim.import_spatial_decomposition", icon="FILE_REFRESH", text="")
|
||||
|
||||
ifc_definition_id = None
|
||||
if self.props.active_container:
|
||||
ifc_definition_id = self.props.active_container.ifc_definition_id
|
||||
row = self.layout.row(align=True)
|
||||
@@ -170,6 +171,7 @@ class BIM_PT_spatial_decomposition(Panel):
|
||||
|
||||
if not self.props.active_container:
|
||||
return
|
||||
assert ifc_definition_id is not None
|
||||
|
||||
container_has_elements = bool(self.props.total_elements)
|
||||
if container_has_elements:
|
||||
|
||||
@@ -102,6 +102,7 @@ class BIM_PT_styles(Panel):
|
||||
|
||||
# style ui tools
|
||||
if active_style:
|
||||
style = active_style
|
||||
row = self.layout.row(align=True)
|
||||
if material := style.blender_material:
|
||||
msprops = tool.Style.get_material_style_props(material)
|
||||
|
||||
@@ -20,6 +20,7 @@ from typing import TYPE_CHECKING
|
||||
|
||||
import bpy
|
||||
import ifcopenshell.api.attribute
|
||||
import ifcopenshell.api.material
|
||||
import ifcopenshell.api.type
|
||||
import ifcopenshell.util.element
|
||||
import ifcopenshell.util.representation
|
||||
@@ -115,51 +116,94 @@ class UnassignType(bpy.types.Operator, tool.Ifc.Operator):
|
||||
if TYPE_CHECKING:
|
||||
related_object: str
|
||||
|
||||
def _execute(self, context):
|
||||
@staticmethod
|
||||
def _reattach_styles(file: ifcopenshell.file, copied_entities: dict[int, ifcopenshell.entity_instance]) -> None:
|
||||
"""copy_deep only follows forward references, so IfcStyledItem (an inverse,
|
||||
``StyledByItem``) is not carried onto the copied geometry. Re-create a
|
||||
styled item on each copy that points at the same presentation styles as
|
||||
the original, so the unmapped occurrence keeps its appearance."""
|
||||
for original_id, copied in copied_entities.items():
|
||||
original = file.by_id(original_id)
|
||||
for styled_item in getattr(original, "StyledByItem", None) or []:
|
||||
file.create_entity(
|
||||
"IfcStyledItem",
|
||||
Item=copied,
|
||||
Styles=styled_item.Styles,
|
||||
Name=styled_item.Name,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def unassign_and_unmap(obj: bpy.types.Object) -> None:
|
||||
"""Unassign the type from ``obj`` and bake a private copy of any mapped
|
||||
representation onto it, so the occurrence keeps its geometry, styles, and
|
||||
material once the type (the source of all three) is gone."""
|
||||
|
||||
def exclude_callback(attribute):
|
||||
return attribute.is_a("IfcProfileDef") and attribute.ProfileName
|
||||
|
||||
self.file = tool.Ifc.get()
|
||||
file = tool.Ifc.get()
|
||||
element = tool.Ifc.get_entity(obj)
|
||||
if not element or not element.is_a("IfcObject"):
|
||||
return
|
||||
|
||||
# Capture the material inherited from the type before we sever the link,
|
||||
# but only if the occurrence has no material of its own to override it.
|
||||
own_material = ifcopenshell.util.element.get_material(element, should_inherit=False)
|
||||
inherited_material = ifcopenshell.util.element.get_material(element, should_inherit=True)
|
||||
|
||||
ifcopenshell.api.type.unassign_type(file, related_objects=[element])
|
||||
|
||||
if element.Representation:
|
||||
new_active_representation = None
|
||||
active_representation = tool.Geometry.get_active_representation(obj)
|
||||
active_context = active_representation.ContextOfItems
|
||||
representations = []
|
||||
for representation in element.Representation.Representations:
|
||||
resolved_representation = ifcopenshell.util.representation.resolve_representation(representation)
|
||||
if representation == resolved_representation:
|
||||
representations.append(representation)
|
||||
else:
|
||||
# We must unmap representations, carrying over their styles.
|
||||
copied_entities: dict[int, ifcopenshell.entity_instance] = {}
|
||||
copied_representation = ifcopenshell.util.element.copy_deep(
|
||||
file,
|
||||
resolved_representation,
|
||||
exclude=["IfcGeometricRepresentationContext"],
|
||||
exclude_callback=exclude_callback,
|
||||
copied_entities=copied_entities,
|
||||
)
|
||||
UnassignType._reattach_styles(file, copied_entities)
|
||||
representations.append(copied_representation)
|
||||
if representation.ContextOfItems == active_context:
|
||||
new_active_representation = copied_representation
|
||||
element.Representation.Representations = representations
|
||||
|
||||
if new_active_representation:
|
||||
bonsai.core.geometry.switch_representation(
|
||||
tool.Ifc,
|
||||
tool.Geometry,
|
||||
obj=obj,
|
||||
representation=new_active_representation,
|
||||
)
|
||||
|
||||
# Bake the inherited material down onto the occurrence now that its type
|
||||
# link (and, in the delete-type case, the type itself) is gone. Usages are
|
||||
# occurrence-specific and never inherited, so they need no handling here.
|
||||
if inherited_material is not None and own_material is None:
|
||||
material_type = inherited_material.is_a()
|
||||
if material_type not in ("IfcMaterialLayerSetUsage", "IfcMaterialProfileSetUsage"):
|
||||
ifcopenshell.api.material.assign_material(
|
||||
file, products=[element], type=material_type, material=inherited_material
|
||||
)
|
||||
|
||||
def _execute(self, context):
|
||||
if self.related_object:
|
||||
related_objects = [bpy.data.objects[self.related_object]]
|
||||
else:
|
||||
related_objects = tool.Blender.get_selected_objects()
|
||||
|
||||
for obj in related_objects:
|
||||
element = tool.Ifc.get_entity(obj)
|
||||
if not element or not element.is_a("IfcObject"):
|
||||
continue
|
||||
ifcopenshell.api.type.unassign_type(self.file, related_objects=[element])
|
||||
|
||||
if element.Representation:
|
||||
new_active_representation = None
|
||||
active_representation = tool.Geometry.get_active_representation(obj)
|
||||
active_context = active_representation.ContextOfItems
|
||||
representations = []
|
||||
for representation in element.Representation.Representations:
|
||||
resolved_representation = ifcopenshell.util.representation.resolve_representation(representation)
|
||||
if representation == resolved_representation:
|
||||
representations.append(representation)
|
||||
else:
|
||||
# We must unmap representations.
|
||||
copied_representation = ifcopenshell.util.element.copy_deep(
|
||||
tool.Ifc.get(),
|
||||
resolved_representation,
|
||||
exclude=["IfcGeometricRepresentationContext"],
|
||||
exclude_callback=exclude_callback,
|
||||
)
|
||||
representations.append(copied_representation)
|
||||
if representation.ContextOfItems == active_context:
|
||||
new_active_representation = copied_representation
|
||||
element.Representation.Representations = representations
|
||||
|
||||
if new_active_representation:
|
||||
bonsai.core.geometry.switch_representation(
|
||||
tool.Ifc,
|
||||
tool.Geometry,
|
||||
obj=obj,
|
||||
representation=new_active_representation,
|
||||
)
|
||||
self.unassign_and_unmap(obj)
|
||||
return {"FINISHED"}
|
||||
|
||||
|
||||
@@ -305,14 +349,82 @@ class SelectTypeObjects(bpy.types.Operator):
|
||||
|
||||
class RemoveType(bpy.types.Operator, tool.Ifc.Operator):
|
||||
bl_idname = "bim.remove_type"
|
||||
bl_label = "Remove Type"
|
||||
bl_label = "Delete Type"
|
||||
bl_description = (
|
||||
"Delete this type. Its occurrences are kept but become untyped.\n\n"
|
||||
"SHIFT+Click to also delete every occurrence of this type in the project"
|
||||
)
|
||||
bl_options = {"REGISTER", "UNDO"}
|
||||
element: bpy.props.IntProperty()
|
||||
also_delete_instances: bpy.props.BoolProperty(default=False, options={"SKIP_SAVE"})
|
||||
|
||||
if TYPE_CHECKING:
|
||||
element: int
|
||||
also_delete_instances: bool
|
||||
|
||||
@staticmethod
|
||||
def _detach_type_material_set(element: ifcopenshell.entity_instance) -> None:
|
||||
"""Cascade-free removal of the type's IfcMaterialLayerSet / IfcMaterialProfileSet
|
||||
association, called just before the type is deleted.
|
||||
|
||||
``remove_product`` would otherwise route the type's material association
|
||||
through ``unassign_material``, which deletes *every* usage of that set
|
||||
across the model (documented behaviour, with an upstream TODO calling it
|
||||
too aggressive) — stripping the material off the very occurrences we are
|
||||
trying to keep. By unhooking the type<->set link by hand here, the type
|
||||
has no material at delete time, so that cascade never fires and the set
|
||||
plus the occurrences' usages survive intact."""
|
||||
file = tool.Ifc.get()
|
||||
material = ifcopenshell.util.element.get_material(element, should_inherit=False)
|
||||
if not material or material.is_a() not in ("IfcMaterialLayerSet", "IfcMaterialProfileSet"):
|
||||
return
|
||||
for rel in list(getattr(element, "HasAssociations", None) or []):
|
||||
if not (rel.is_a("IfcRelAssociatesMaterial") and rel.RelatingMaterial == material):
|
||||
continue
|
||||
remaining = [o for o in rel.RelatedObjects if o != element]
|
||||
if remaining:
|
||||
rel.RelatedObjects = remaining
|
||||
else:
|
||||
history = rel.OwnerHistory
|
||||
file.remove(rel)
|
||||
if history:
|
||||
ifcopenshell.util.element.remove_deep2(file, history)
|
||||
|
||||
def invoke(self, context, event):
|
||||
self.also_delete_instances = event.shift
|
||||
if self.also_delete_instances:
|
||||
element = tool.Ifc.get().by_id(self.element)
|
||||
count = len(ifcopenshell.util.element.get_types(element))
|
||||
return context.window_manager.invoke_confirm(
|
||||
self,
|
||||
event,
|
||||
title="Delete Type and Occurrences",
|
||||
message=f"This will delete the type and all {count} of its occurrences.",
|
||||
confirm_text="Delete",
|
||||
)
|
||||
return self.execute(context)
|
||||
|
||||
def _execute(self, context):
|
||||
element = tool.Ifc.get().by_id(self.element)
|
||||
occurrences = ifcopenshell.util.element.get_types(element)
|
||||
if self.also_delete_instances:
|
||||
for occurrence in occurrences:
|
||||
occurrence_obj = tool.Ifc.get_object(occurrence)
|
||||
if occurrence_obj:
|
||||
tool.Geometry.delete_ifc_object(occurrence_obj)
|
||||
else:
|
||||
# Keep the occurrences: bake their (previously type-mapped) geometry,
|
||||
# styles, and inherited material onto each one so nothing is lost when
|
||||
# the type is deleted...
|
||||
for occurrence in occurrences:
|
||||
occ_obj = tool.Ifc.get_object(occurrence)
|
||||
if occ_obj:
|
||||
UnassignType.unassign_and_unmap(occ_obj)
|
||||
# ...and keep any layer/profile-set material usages alive across the deletion.
|
||||
self._detach_type_material_set(element)
|
||||
obj = tool.Ifc.get_object(element)
|
||||
tool.Geometry.delete_ifc_object(obj)
|
||||
if obj:
|
||||
tool.Geometry.delete_ifc_object(obj)
|
||||
|
||||
|
||||
class RenameType(bpy.types.Operator, tool.Ifc.Operator):
|
||||
|
||||
@@ -144,8 +144,10 @@ class BIM_PT_type_attributes(Panel):
|
||||
|
||||
bonsai.bim.helper.draw_attributes(props.type_attributes, layout)
|
||||
else:
|
||||
row = layout.row()
|
||||
row = layout.row(align=True)
|
||||
row.operator("bim.enable_editing_type_attributes", icon="GREASEPENCIL", text="Edit")
|
||||
op = row.operator("bim.remove_type", icon="TRASH", text="")
|
||||
op.element = TypeData.data["relating_type"]["id"]
|
||||
|
||||
for attribute in TypeData.data["relating_type_attributes"]:
|
||||
row = layout.row(align=True)
|
||||
|
||||
@@ -72,6 +72,7 @@ class AddOpening(bpy.types.Operator, tool.Ifc.Operator):
|
||||
|
||||
opening_objects = [obj for obj in selected_objects if obj != target_object]
|
||||
|
||||
obj1 = ...
|
||||
for opening_obj in opening_objects:
|
||||
element1 = tool.Ifc.get_entity(target_object)
|
||||
obj1 = target_object
|
||||
@@ -196,6 +197,7 @@ class AddOpening(bpy.types.Operator, tool.Ifc.Operator):
|
||||
bpy.data.objects.remove(obj2)
|
||||
|
||||
tool.Model.purge_scene_openings()
|
||||
assert obj1 is not ...
|
||||
context.view_layer.objects.active = obj1
|
||||
return {"FINISHED"}
|
||||
|
||||
|
||||
@@ -284,11 +284,13 @@ class GizmoPreferences(bpy.types.PropertyGroup):
|
||||
draw_gizmos_in_3d_viewport: bool
|
||||
|
||||
|
||||
_gizmo_pref_entry = None
|
||||
for _gizmo_pref_entry in tool.Parametric.EDIT_TYPES:
|
||||
GizmoPreferences.__annotations__[_gizmo_pref_entry.name] = BoolProperty(
|
||||
name=_gizmo_pref_entry.name.replace("_", " ").title(),
|
||||
default=True,
|
||||
)
|
||||
assert _gizmo_pref_entry is not None
|
||||
del _gizmo_pref_entry
|
||||
|
||||
|
||||
@@ -394,12 +396,14 @@ class DefaultParameters(bpy.types.PropertyGroup):
|
||||
and gives the create operator a preset to copy from."""
|
||||
|
||||
|
||||
_default_params_entry = None
|
||||
for _default_params_entry in tool.Parametric.EDIT_TYPES:
|
||||
if not _default_params_entry.has_default_parameters:
|
||||
continue
|
||||
DefaultParameters.__annotations__[_default_params_entry.name] = bpy.props.PointerProperty(
|
||||
type=getattr(_model_prop, _default_params_entry.props_attr),
|
||||
)
|
||||
assert _default_params_entry is not None
|
||||
del _default_params_entry
|
||||
|
||||
|
||||
|
||||
@@ -74,10 +74,11 @@ def add_instance_ceiling_covering_from_cursor(
|
||||
if not relating_type.is_a("IfcCoveringType"):
|
||||
relating_type = None
|
||||
|
||||
ceiling_height = None
|
||||
if selected_objects and active_obj:
|
||||
x, y, z, h, mat = spatial.get_x_y_z_h_mat_from_obj(active_obj)
|
||||
x, y, z, _, _ = spatial.get_x_y_z_h_mat_from_obj(active_obj)
|
||||
else:
|
||||
x, y, z, h, mat = spatial.get_x_y_z_h_mat_from_cursor()
|
||||
x, y, z, _, _ = spatial.get_x_y_z_h_mat_from_cursor()
|
||||
ceiling_height = covering.get_z_from_ceiling_height()
|
||||
|
||||
space_polygon = spatial.get_space_polygon_from_context_visible_objects(x, y)
|
||||
@@ -87,6 +88,7 @@ def add_instance_ceiling_covering_from_cursor(
|
||||
|
||||
obj = spatial.create_object("Covering")
|
||||
spatial.set_obj_origin_to_cursor_position_and_zero_elevation(obj)
|
||||
assert ceiling_height is not None
|
||||
spatial.translate_obj_to_z_location(obj, z + ceiling_height)
|
||||
spatial.assign_type_to_obj(obj)
|
||||
spatial.set_covering_representation_from_polygon(obj, space_polygon, polygon_is_si=True)
|
||||
@@ -100,7 +102,9 @@ def regen_selected_covering_object(root: type[tool.Root], spatial: type[tool.Spa
|
||||
selected_objects = spatial.get_selected_objects()
|
||||
|
||||
if selected_objects and active_obj:
|
||||
x, y, z, h, mat = spatial.get_x_y_z_h_mat_from_obj(active_obj)
|
||||
x, y, _, _, _ = spatial.get_x_y_z_h_mat_from_obj(active_obj)
|
||||
else:
|
||||
assert False, "Object has to be active and selected."
|
||||
|
||||
space_polygon = spatial.get_space_polygon_from_context_visible_objects(x, y)
|
||||
|
||||
|
||||
@@ -411,6 +411,37 @@ def duplicate_drawing(
|
||||
return new_drawing
|
||||
|
||||
|
||||
def copy_annotations_to_drawing(
|
||||
ifc: type[tool.Ifc],
|
||||
collector: type[tool.Collector],
|
||||
drawing_tool: type[tool.Drawing],
|
||||
geometry: type[tool.Geometry],
|
||||
annotations: list[ifcopenshell.entity_instance],
|
||||
target_drawing: ifcopenshell.entity_instance,
|
||||
) -> list[ifcopenshell.entity_instance]:
|
||||
"""Duplicate annotations into another drawing, leaving the originals untouched."""
|
||||
target_group = drawing_tool.get_drawing_group(target_drawing)
|
||||
if not target_group:
|
||||
return []
|
||||
annotations = [a for a in annotations if drawing_tool.get_annotation_drawing(a) != target_drawing]
|
||||
annotation_objs = [obj for a in annotations if (obj := ifc.get_object(a))]
|
||||
if not annotation_objs:
|
||||
return []
|
||||
camera = ifc.get_object(target_drawing) or drawing_tool.import_drawing(target_drawing)
|
||||
old_to_new, _ = geometry.duplicate_ifc_objects(annotation_objs)
|
||||
copied: list[ifcopenshell.entity_instance] = []
|
||||
for new_elements in old_to_new.values():
|
||||
for new_element in new_elements:
|
||||
if old_group := drawing_tool.get_drawing_group(new_element):
|
||||
ifc.run("group.unassign_group", group=old_group, products=[new_element])
|
||||
ifc.run("group.assign_group", group=target_group, products=[new_element])
|
||||
new_obj = ifc.get_object(new_element)
|
||||
drawing_tool.ensure_annotation_in_drawing_plane(new_obj, camera)
|
||||
collector.assign(new_obj, should_clean_users_collection=True)
|
||||
copied.append(new_element)
|
||||
return copied
|
||||
|
||||
|
||||
def remove_drawing(
|
||||
ifc: type[tool.Ifc], drawing_tool: type[tool.Drawing], drawing: ifcopenshell.entity_instance
|
||||
) -> None:
|
||||
@@ -497,6 +528,7 @@ def add_annotation(
|
||||
drawing_tool.show_decorations()
|
||||
obj = drawing_tool.create_annotation_object(drawing, object_type)
|
||||
element = ifc.get_entity(obj)
|
||||
relating_type_rep = None
|
||||
if not element: # Brand new annotation
|
||||
relating_type_rep = drawing_tool.get_annotation_representation(relating_type) if relating_type else None
|
||||
element = drawing_tool.run_root_assign_class(
|
||||
|
||||
@@ -354,6 +354,7 @@ class Drawing:
|
||||
def enable_editing_schedules(cls): pass
|
||||
def enable_editing_sheets(cls): pass
|
||||
def enable_editing_text(cls, obj): pass
|
||||
def ensure_annotation_in_drawing_plane(cls, obj, camera=None): pass
|
||||
def ensure_drawings_parent_document(cls): pass
|
||||
def ensure_drawings_parent_group(cls): pass
|
||||
def ensure_unique_drawing_name(cls, name): pass
|
||||
@@ -367,6 +368,7 @@ class Drawing:
|
||||
def generate_reference_attributes(cls, reference, **attributes): pass
|
||||
def generate_sheet_identification(cls): pass
|
||||
def get_annotation_context(cls, target_view, object_type=None): pass
|
||||
def get_annotation_drawing(cls, element): pass
|
||||
def get_annotation_representation(cls, element_type): pass
|
||||
def get_assigned_product(cls, element): pass
|
||||
def get_assigned_product_workaround(cls, element): pass
|
||||
@@ -384,6 +386,7 @@ class Drawing:
|
||||
def get_drawing_group(cls, drawing): pass
|
||||
def get_drawing_references(cls, drawing): pass
|
||||
def get_drawing_target_view(cls, drawing): pass
|
||||
def get_group_drawing(cls, group): pass
|
||||
def get_group_elements(cls, group): pass
|
||||
def get_ifc_representation_class(cls, object_type): pass
|
||||
def get_name(cls, element): pass
|
||||
@@ -397,6 +400,7 @@ class Drawing:
|
||||
def get_unit_system(cls): pass
|
||||
def import_assigned_product(cls, obj): pass
|
||||
def import_documents(cls, document_type): pass
|
||||
def import_drawing(cls, drawing): pass
|
||||
def import_drawings(cls): pass
|
||||
def import_sheets(cls): pass
|
||||
def import_text_attributes(cls, obj): pass
|
||||
|
||||
@@ -981,6 +981,7 @@ class Cad:
|
||||
has_found_connected_edge = True
|
||||
loops.append(loop)
|
||||
|
||||
new_verts = None
|
||||
for loop in loops:
|
||||
all_verts = {v.index for e in loop for v in e.verts}
|
||||
possible_v1s = []
|
||||
@@ -1084,6 +1085,7 @@ class Cad:
|
||||
break
|
||||
|
||||
v1 = v2
|
||||
assert new_verts is not None
|
||||
|
||||
return new_verts
|
||||
|
||||
|
||||
@@ -280,6 +280,8 @@ class Cost(bonsai.core.tool.Cost):
|
||||
new = props.cost_item_processes.add()
|
||||
elif related_object.is_a("IfcResource"):
|
||||
new = props.cost_item_resources.add()
|
||||
else:
|
||||
assert False, related_object
|
||||
new.ifc_definition_id = related_object.id()
|
||||
new.name = related_object.Name or "Unnamed"
|
||||
|
||||
|
||||
@@ -756,6 +756,17 @@ class Drawing(bonsai.core.tool.Drawing):
|
||||
if rel.is_a("IfcRelAssignsToGroup") and rel.RelatingGroup.ObjectType == "DRAWING":
|
||||
return rel.RelatingGroup
|
||||
|
||||
@classmethod
|
||||
def get_group_drawing(cls, group: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]:
|
||||
"""Get the drawing that owns this group, if the group represents a drawing."""
|
||||
if group.ObjectType != "DRAWING":
|
||||
return None
|
||||
for rel in group.IsGroupedBy or []:
|
||||
for related_object in rel.RelatedObjects:
|
||||
if related_object.is_a("IfcAnnotation") and related_object.ObjectType == "DRAWING":
|
||||
return related_object
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def get_drawing_document(cls, drawing: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance:
|
||||
for rel in drawing.HasAssociations:
|
||||
@@ -1072,6 +1083,12 @@ class Drawing(bonsai.core.tool.Drawing):
|
||||
camera_props.has_annotation = True
|
||||
camera_props.target_view = "PLAN_VIEW"
|
||||
camera_props.is_nts = False
|
||||
camera_props.use_edge_classification = False
|
||||
camera_props.render_creases = True
|
||||
camera_props.valley_angle_min_degrees = 12.0
|
||||
camera_props.render_sharp = True
|
||||
camera_props.ridge_angle_min_degrees = 45.0
|
||||
camera_props.render_flush = False
|
||||
camera.shift_x = 0.0
|
||||
camera.shift_y = 0.0
|
||||
|
||||
@@ -1101,6 +1118,18 @@ class Drawing(bonsai.core.tool.Drawing):
|
||||
camera_props.has_annotation = bool(pset["HasAnnotation"])
|
||||
if "IsNTS" in pset:
|
||||
camera_props.is_nts = bool(pset["IsNTS"])
|
||||
if "UseEdgeClassification" in pset:
|
||||
camera_props.use_edge_classification = bool(pset["UseEdgeClassification"])
|
||||
if "RenderCreases" in pset:
|
||||
camera_props.render_creases = bool(pset["RenderCreases"])
|
||||
if "ValleyAngleMinDegrees" in pset:
|
||||
camera_props.valley_angle_min_degrees = float(pset["ValleyAngleMinDegrees"])
|
||||
if "RenderSharp" in pset:
|
||||
camera_props.render_sharp = bool(pset["RenderSharp"])
|
||||
if "RidgeAngleMinDegrees" in pset:
|
||||
camera_props.ridge_angle_min_degrees = float(pset["RidgeAngleMinDegrees"])
|
||||
if "RenderFlush" in pset:
|
||||
camera_props.render_flush = bool(pset["RenderFlush"])
|
||||
if "DPI" in pset:
|
||||
camera_props.dpi = int(pset["DPI"])
|
||||
if "LineworkMode" in pset:
|
||||
@@ -2575,16 +2604,15 @@ class Drawing(bonsai.core.tool.Drawing):
|
||||
if not obj:
|
||||
continue
|
||||
current_representation = tool.Geometry.get_active_representation(obj)
|
||||
current_representation_subcontext = None
|
||||
if current_representation:
|
||||
subcontext = current_representation.ContextOfItems
|
||||
current_representation_subcontext = tool.Geometry.get_subcontext_parameters(subcontext)
|
||||
|
||||
has_context = False
|
||||
for subcontext in subcontexts:
|
||||
# prioritize already active representation if it matches the subcontext
|
||||
# (element could have multiple representations in the same subcontext)
|
||||
if current_representation and subcontext == current_representation_subcontext:
|
||||
has_context = True
|
||||
if current_representation_subcontext and subcontext == current_representation_subcontext:
|
||||
break
|
||||
priority_representation = ifcopenshell.util.representation.get_representation(element, *subcontext)
|
||||
if priority_representation:
|
||||
@@ -2594,7 +2622,6 @@ class Drawing(bonsai.core.tool.Drawing):
|
||||
obj=obj,
|
||||
representation=priority_representation,
|
||||
)
|
||||
has_context = True
|
||||
break
|
||||
|
||||
linked_handles: set[bpy.types.Object] = set()
|
||||
@@ -2860,6 +2887,50 @@ class Drawing(bonsai.core.tool.Drawing):
|
||||
break
|
||||
return sheet_references
|
||||
|
||||
@classmethod
|
||||
def get_sheeted_drawing_ids(cls) -> set[int]:
|
||||
"""Get the IFC ids of all drawings that are placed on at least one sheet."""
|
||||
ifc_file = tool.Ifc.get()
|
||||
sheet_locations: set[Union[str, None]] = set()
|
||||
for sheet in ifc_file.by_type("IfcDocumentInformation"):
|
||||
if sheet.Scope != "SHEET":
|
||||
continue
|
||||
for reference in cls.get_document_references(sheet):
|
||||
sheet_locations.add(reference.Location)
|
||||
if not sheet_locations:
|
||||
return set()
|
||||
result: set[int] = set()
|
||||
for drawing in ifc_file.by_type("IfcAnnotation"):
|
||||
if drawing.ObjectType != "DRAWING":
|
||||
continue
|
||||
drawing_document = cls.get_drawing_document(drawing)
|
||||
if drawing_document and drawing_document.Location in sheet_locations:
|
||||
result.add(drawing.id())
|
||||
return result
|
||||
|
||||
@classmethod
|
||||
def get_visible_drawings_in_category(cls, target_view: str) -> list[DrawingProperties]:
|
||||
"""Get the drawing items in a target view category that are currently visible in the drawing list.
|
||||
|
||||
Grouping is positional: individual drawing items don't carry their own ``target_view``, they belong to
|
||||
the most recent header item above them. Only expanded categories contribute drawing items to the
|
||||
collection, so a collapsed category yields an empty list. Respects the ``show_drawings_on_sheets_only``
|
||||
filter so that select-all only affects visible drawings.
|
||||
"""
|
||||
props = cls.get_document_props()
|
||||
drawings: list[DrawingProperties] = []
|
||||
in_category = False
|
||||
for item in props.drawings:
|
||||
if not item.is_drawing:
|
||||
# Header row: we're inside the requested category until the next header.
|
||||
in_category = item.target_view == target_view
|
||||
elif in_category:
|
||||
drawings.append(item)
|
||||
if props.show_drawings_on_sheets_only:
|
||||
sheeted_ids = cls.get_sheeted_drawing_ids()
|
||||
drawings = [d for d in drawings if d.ifc_definition_id in sheeted_ids]
|
||||
return drawings
|
||||
|
||||
@classmethod
|
||||
def get_camera_matrix(cls, camera: bpy.types.Object) -> Matrix:
|
||||
matrix_world = camera.matrix_world.copy().normalized()
|
||||
|
||||
@@ -23,7 +23,6 @@ from typing import TYPE_CHECKING
|
||||
|
||||
import bpy
|
||||
import ifcopenshell.api.feature
|
||||
import ifcopenshell.util.representation
|
||||
|
||||
import bonsai.core.geometry
|
||||
import bonsai.core.tool
|
||||
@@ -50,6 +49,7 @@ class Feature(bonsai.core.tool.Feature):
|
||||
has_visible_openings = True
|
||||
break
|
||||
|
||||
element_had_openings = None
|
||||
for feature_obj in feature_objs:
|
||||
feature_element = tool.Ifc.get_entity(feature_obj)
|
||||
|
||||
@@ -58,7 +58,6 @@ class Feature(bonsai.core.tool.Feature):
|
||||
bonsai.core.geometry.edit_object_placement(tool.Ifc, tool.Geometry, tool.Surveyor, obj=featured_obj)
|
||||
|
||||
element_had_openings = tool.Geometry.has_openings(featured_element)
|
||||
body_context = ifcopenshell.util.representation.get_context(tool.Ifc.get(), "Model", "Body")
|
||||
ifcopenshell.api.feature.add_feature(tool.Ifc.get(), feature=feature_element, element=featured_element)
|
||||
|
||||
if tool.Ifc.is_moved(feature_obj):
|
||||
@@ -73,6 +72,7 @@ class Feature(bonsai.core.tool.Feature):
|
||||
if voided_obj.data:
|
||||
if tool.Ifc.is_edited(voided_obj):
|
||||
voided_element_ = tool.Ifc.get_entity(voided_obj)
|
||||
assert element_had_openings is not None
|
||||
if element_had_openings or (voided_element_ != featured_element and voided_element_.HasOpenings):
|
||||
voided_obj.scale = (1.0, 1.0, 1.0)
|
||||
tool.Ifc.finish_edit(voided_obj)
|
||||
|
||||
@@ -757,6 +757,7 @@ class Geometry(bonsai.core.tool.Geometry):
|
||||
# its centroid not obscured (tested via raycasting) by any other
|
||||
# face.
|
||||
distance = max(obj.dimensions.xyz)
|
||||
min_y, max_z = None, None
|
||||
if axis == "+Z":
|
||||
max_z = max([co[2] for co in obj.bound_box]) + 0.002
|
||||
direction = Vector((0, 0, -1))
|
||||
@@ -771,8 +772,10 @@ class Geometry(bonsai.core.tool.Geometry):
|
||||
if direction.dot(face.normal) > 0:
|
||||
continue
|
||||
if axis == "+Z":
|
||||
assert max_z is not None
|
||||
face_centroid_at_max = Vector((*face.calc_center_median().xy, max_z))
|
||||
elif axis == "-Y":
|
||||
assert min_y is not None
|
||||
centroid = face.calc_center_median()
|
||||
face_centroid_at_max = Vector((centroid.x, min_y, centroid.z))
|
||||
face_centroid_at_max = obj.matrix_world @ face_centroid_at_max
|
||||
@@ -1148,6 +1151,9 @@ class Geometry(bonsai.core.tool.Geometry):
|
||||
settings.set("layerset-first", True)
|
||||
settings.set("keep-bounding-boxes", True)
|
||||
settings.set("dimensionality", ifcopenshell.ifcopenshell_wrapper.CURVES_SURFACES_AND_SOLIDS)
|
||||
settings.set("mesher-linear-deflection", ifc_import_settings.deflection_tolerance)
|
||||
settings.set("mesher-angular-deflection", ifc_import_settings.angular_tolerance)
|
||||
geometry_library = ifc_import_settings.geometry_library
|
||||
|
||||
ifc_importer = bonsai.bim.import_ifc.IfcImporter(ifc_import_settings)
|
||||
ifc_importer.file = tool.Ifc.get()
|
||||
@@ -1159,7 +1165,11 @@ class Geometry(bonsai.core.tool.Geometry):
|
||||
shape = None
|
||||
if elements:
|
||||
iterator = ifcopenshell.geom.iterator(
|
||||
settings, tool.Ifc.get(), multiprocessing.cpu_count(), include=elements
|
||||
settings,
|
||||
tool.Ifc.get(),
|
||||
multiprocessing.cpu_count(),
|
||||
include=elements,
|
||||
geometry_library=geometry_library,
|
||||
)
|
||||
else:
|
||||
iterator = None # For example, when switching representation of a type with no occurrences
|
||||
@@ -1214,7 +1224,9 @@ class Geometry(bonsai.core.tool.Geometry):
|
||||
for element in element_types:
|
||||
if obj := tool.Ifc.get_object(element):
|
||||
if representation := ifcopenshell.util.representation.get_representation(element, context):
|
||||
geometry = ifcopenshell.geom.create_shape(settings, representation)
|
||||
geometry = ifcopenshell.geom.create_shape(
|
||||
settings, representation, geometry_library=geometry_library
|
||||
)
|
||||
mesh_name = tool.Loader.get_mesh_name_from_shape(geometry)
|
||||
mesh = meshes.get(mesh_name)
|
||||
if mesh is None:
|
||||
@@ -1885,6 +1897,7 @@ class Geometry(bonsai.core.tool.Geometry):
|
||||
"""NOTE: we assume that all items belonged to the same representation and to the same shape aspect"""
|
||||
ifc_file = tool.Ifc.get()
|
||||
previous_shape_aspect = None
|
||||
base_representation = None
|
||||
for inverse in ifc_file.get_inverse(representation_items[0]):
|
||||
if inverse.is_a("IfcShapeRepresentation"):
|
||||
if inverse.OfShapeAspect:
|
||||
@@ -1894,6 +1907,7 @@ class Geometry(bonsai.core.tool.Geometry):
|
||||
previous_shape_aspect = inverse.OfShapeAspect[0]
|
||||
else:
|
||||
base_representation = inverse
|
||||
assert base_representation
|
||||
|
||||
# remove item from previous shape aspect
|
||||
if previous_shape_aspect:
|
||||
@@ -2211,6 +2225,7 @@ class Geometry(bonsai.core.tool.Geometry):
|
||||
assert item
|
||||
obj.data.clear_geometry()
|
||||
|
||||
cartesian_point_offset = None
|
||||
if item.is_a("IfcHalfSpaceSolid"):
|
||||
bm = bmesh.new()
|
||||
bmesh.ops.create_grid(bm, size=0.5)
|
||||
|
||||
@@ -1087,18 +1087,21 @@ class Loader(bonsai.core.tool.Loader):
|
||||
bm = bmesh.new()
|
||||
bm.from_mesh(mesh)
|
||||
prev_co = None
|
||||
if usage.LayerSetDirection == "AXIS2":
|
||||
layer_set_direction = usage.LayerSetDirection
|
||||
if layer_set_direction == "AXIS2":
|
||||
co = Vector((0.0, offset, 0.0))
|
||||
no = cls.get_extrusion_vector(element).normalized()
|
||||
no = no.cross(Vector([1.0, 0.0, 0.0]))
|
||||
elif usage.LayerSetDirection == "AXIS3":
|
||||
elif layer_set_direction == "AXIS3":
|
||||
co = Vector((0.0, 0.0, offset))
|
||||
no = cls.get_extrusion_vector(element).normalized()
|
||||
no = Vector([0.0, 0.0, 1.0])
|
||||
elif usage.LayerSetDirection == "AXIS1":
|
||||
elif layer_set_direction == "AXIS1":
|
||||
co = Vector((0.0, 0.0, offset))
|
||||
no = cls.get_extrusion_vector(element).normalized()
|
||||
no = Vector([1.0, 0.0, 0.0])
|
||||
else:
|
||||
assert False, layer_set_direction
|
||||
no *= sense_factor
|
||||
# Cache this
|
||||
body = ifcopenshell.util.representation.get_context(tool.Ifc.get(), "Model", "Body", "MODEL_VIEW")
|
||||
@@ -1108,6 +1111,7 @@ class Loader(bonsai.core.tool.Loader):
|
||||
if style := tool.Ifc.get_entity(material):
|
||||
styles[style] = i
|
||||
last_i = len(layer_set.MaterialLayers) - 1
|
||||
bisect_geom = None
|
||||
for i, layer in enumerate(layer_set.MaterialLayers):
|
||||
if i != last_i:
|
||||
prev_co = co.copy()
|
||||
@@ -1121,6 +1125,7 @@ class Loader(bonsai.core.tool.Loader):
|
||||
if (material_index := styles.get(style, None)) is None:
|
||||
material_index = len(mesh.materials)
|
||||
mesh.materials.append(tool.Ifc.get_object(style))
|
||||
assert bisect_geom is not None
|
||||
if i == last_i:
|
||||
for face in bisect_geom["geom"]:
|
||||
if isinstance(face, bmesh.types.BMFace):
|
||||
@@ -1286,6 +1291,7 @@ class Loader(bonsai.core.tool.Loader):
|
||||
polyline.material_index = material_index
|
||||
return polyline
|
||||
|
||||
item = None
|
||||
for item_data, item_style in zip(rep_items, item_styles):
|
||||
item = item_data["item"]
|
||||
|
||||
@@ -1313,6 +1319,7 @@ class Loader(bonsai.core.tool.Loader):
|
||||
polyline.points.add(1)
|
||||
polyline.points[-1].co = native_data["matrix"] @ Vector(v2)
|
||||
|
||||
assert item is not None
|
||||
curve.bevel_depth = unit_scale * item.Radius
|
||||
thickness = None
|
||||
if (inner_radius := item.InnerRadius) and (thickness := max(item.Radius - inner_radius, 0)):
|
||||
|
||||
@@ -220,10 +220,12 @@ class Misc(bonsai.core.tool.Misc):
|
||||
related_objects.append((element, ifcopenshell.util.placement.get_storey_elevation(element)))
|
||||
related_objects = sorted(related_objects, key=lambda e: e[1])
|
||||
storey_elevation = None
|
||||
i = None
|
||||
for i, related_object in enumerate(related_objects):
|
||||
if related_object[0] == storey:
|
||||
storey_elevation = related_object[1]
|
||||
break
|
||||
assert i is not None
|
||||
if i + total_storeys < len(related_objects):
|
||||
next_storey_elevation = related_objects[i + total_storeys][1]
|
||||
unit_scale = ifcopenshell.util.unit.calculate_unit_scale(tool.Ifc.get())
|
||||
|
||||
@@ -2292,32 +2292,18 @@ class Model(bonsai.core.tool.Model):
|
||||
deform_layer = bm.verts.layers.deform.active
|
||||
|
||||
# Sanity check
|
||||
group_verts = {"IFCARCINDEX": {}, "IFCCIRCLE": {}}
|
||||
if deform_layer:
|
||||
for vert in bm.verts:
|
||||
vert_group_indices = tool.Blender.bmesh_get_vertex_groups(vert, deform_layer)
|
||||
is_circle = False
|
||||
for group_index in vert_group_indices:
|
||||
group_type = "IFCARCINDEX" if group_index in groups["IFCARCINDEX"] else "IFCCIRCLE"
|
||||
group_verts[group_type].setdefault(group_index, 0)
|
||||
group_verts[group_type][group_index] += 1
|
||||
if group_type == "IFCCIRCLE":
|
||||
is_circle = True
|
||||
is_circle = any(gi in groups["IFCCIRCLE"] for gi in vert_group_indices)
|
||||
is_arc = any(gi in groups["IFCARCINDEX"] for gi in vert_group_indices)
|
||||
if (is_circle or is_arc) and not vert.link_edges:
|
||||
return (False, "CIRCLE" if is_circle else "3POINT_ARC")
|
||||
if is_circle:
|
||||
pass # Circles are allowed to be unclosed
|
||||
elif len(vert.link_edges) != 2: # Unclosed loop or forked loop
|
||||
return (False, "UNCLOSED_LOOP")
|
||||
|
||||
for group_type, group_counts in group_verts.items():
|
||||
if group_type == "IFCARCINDEX":
|
||||
for group_count in group_counts.values():
|
||||
if group_count != 3: # Each arc needs 3 verts
|
||||
return (False, "3POINT_ARC")
|
||||
elif group_type == "IFCCIRCLE":
|
||||
for group_count in group_counts.values():
|
||||
if group_count != 2: # Each circle needs 2 verts
|
||||
return (False, "CIRCLE")
|
||||
|
||||
loop_edges = list(bm.edges)
|
||||
|
||||
# Create loops from edges
|
||||
@@ -2340,6 +2326,28 @@ class Model(bonsai.core.tool.Model):
|
||||
has_found_connected_edge = True
|
||||
loops.append(loop)
|
||||
|
||||
# Sanity check, per loop rather than across the whole mesh
|
||||
if deform_layer:
|
||||
for loop in loops:
|
||||
loop_group_counts = {"IFCARCINDEX": {}, "IFCCIRCLE": {}}
|
||||
loop_verts = {v for edge in loop for v in edge.verts}
|
||||
for vert in loop_verts:
|
||||
for group_index in tool.Blender.bmesh_get_vertex_groups(vert, deform_layer):
|
||||
if group_index in groups["IFCARCINDEX"]:
|
||||
group_type = "IFCARCINDEX"
|
||||
elif group_index in groups["IFCCIRCLE"]:
|
||||
group_type = "IFCCIRCLE"
|
||||
else:
|
||||
continue
|
||||
loop_group_counts[group_type].setdefault(group_index, 0)
|
||||
loop_group_counts[group_type][group_index] += 1
|
||||
for group_count in loop_group_counts["IFCARCINDEX"].values():
|
||||
if group_count != 3: # Each arc needs 3 verts
|
||||
return (False, "3POINT_ARC")
|
||||
for group_count in loop_group_counts["IFCCIRCLE"].values():
|
||||
if group_count != 2: # Each circle needs 2 verts
|
||||
return (False, "CIRCLE")
|
||||
|
||||
tmp = ifcopenshell.file(schema=tool.Ifc.get().schema)
|
||||
|
||||
def is_in_group(v: bmesh.types.BMVert, group_name: str) -> bool:
|
||||
@@ -2520,27 +2528,11 @@ class Model(bonsai.core.tool.Model):
|
||||
deform_layer = bm.verts.layers.deform.active
|
||||
|
||||
# Sanity check
|
||||
group_verts = {"IFCARCINDEX": {}, "IFCCIRCLE": {}}
|
||||
if deform_layer:
|
||||
for vert in bm.verts:
|
||||
vert_group_indices = tool.Blender.bmesh_get_vertex_groups(vert, deform_layer)
|
||||
for group_index in vert_group_indices:
|
||||
group_type = "IFCARCINDEX" if group_index in groups["IFCARCINDEX"] else "IFCCIRCLE"
|
||||
group_verts[group_type].setdefault(group_index, 0)
|
||||
group_verts[group_type][group_index] += 1
|
||||
if len(vert.link_edges) > 2: # Forked loop
|
||||
return (False, "FORKED_LOOP")
|
||||
|
||||
for group_type, group_counts in group_verts.items():
|
||||
if group_type == "IFCARCINDEX":
|
||||
for group_count in group_counts.values():
|
||||
if group_count != 3: # Each arc needs 3 verts
|
||||
return (False, "3POINT_ARC")
|
||||
elif group_type == "IFCCIRCLE":
|
||||
for group_count in group_counts.values():
|
||||
if group_count != 2: # Each circle needs 2 verts
|
||||
return (False, "CIRCLE")
|
||||
|
||||
loop_edges = list(bm.edges)
|
||||
|
||||
# Create loops from edges
|
||||
@@ -2563,6 +2555,28 @@ class Model(bonsai.core.tool.Model):
|
||||
has_found_connected_edge = True
|
||||
loops.append(loop)
|
||||
|
||||
# Sanity check, per loop rather than across the whole mesh
|
||||
if deform_layer:
|
||||
for loop in loops:
|
||||
loop_group_counts = {"IFCARCINDEX": {}, "IFCCIRCLE": {}}
|
||||
loop_verts = {v for edge in loop for v in edge.verts}
|
||||
for vert in loop_verts:
|
||||
for group_index in tool.Blender.bmesh_get_vertex_groups(vert, deform_layer):
|
||||
if group_index in groups["IFCARCINDEX"]:
|
||||
group_type = "IFCARCINDEX"
|
||||
elif group_index in groups["IFCCIRCLE"]:
|
||||
group_type = "IFCCIRCLE"
|
||||
else:
|
||||
continue
|
||||
loop_group_counts[group_type].setdefault(group_index, 0)
|
||||
loop_group_counts[group_type][group_index] += 1
|
||||
for group_count in loop_group_counts["IFCARCINDEX"].values():
|
||||
if group_count != 3: # Each arc needs 3 verts
|
||||
return (False, "3POINT_ARC")
|
||||
for group_count in loop_group_counts["IFCCIRCLE"].values():
|
||||
if group_count != 2: # Each circle needs 2 verts
|
||||
return (False, "CIRCLE")
|
||||
|
||||
tmp = ifcopenshell.file(schema=tool.Ifc.get().schema)
|
||||
|
||||
def is_in_group(v: bmesh.types.BMVert, group_name: str) -> bool:
|
||||
|
||||
@@ -641,6 +641,8 @@ del _edit_type_names
|
||||
# call sites can reference ``tool.Parametric.ROOF`` directly. Renaming a
|
||||
# registry entry renames the constant; a typo at the call site surfaces as
|
||||
# AttributeError at module load.
|
||||
_entry = None
|
||||
for _entry in Parametric.EDIT_TYPES:
|
||||
setattr(Parametric, _entry.name.upper(), _entry)
|
||||
assert _entry is not None
|
||||
del _entry
|
||||
|
||||
@@ -168,6 +168,7 @@ class Polyline(bonsai.core.tool.Polyline):
|
||||
distance = (mouse_vector - last_point).length
|
||||
if distance < 0:
|
||||
return
|
||||
angle, orientation_angle, angle_round_threshold = None, None, None
|
||||
if distance > 0:
|
||||
angle = tool.Cad.angle_3_vectors(
|
||||
second_to_last_point, last_point, mouse_vector, new_angle=None, degrees=True
|
||||
@@ -188,6 +189,7 @@ class Polyline(bonsai.core.tool.Polyline):
|
||||
angle = 0
|
||||
orientation_angle = 0
|
||||
if input_ui:
|
||||
assert angle is not None and orientation_angle is not None and angle_round_threshold is not None
|
||||
if should_round:
|
||||
angle_snap = tool.Snap.get_angle_snap_value(context)
|
||||
angle = angle_snap * round(angle / angle_snap) if distance < angle_round_threshold else angle
|
||||
|
||||
@@ -370,18 +370,21 @@ class Project(bonsai.core.tool.Project):
|
||||
props = cls.get_project_props()
|
||||
active_library_breadcrumb = props.get_active_library_breadcrumb()
|
||||
change_back = False
|
||||
breadcrumb = None
|
||||
if active_library_breadcrumb:
|
||||
name = active_library_breadcrumb.name
|
||||
breadcrumb_type = active_library_breadcrumb.breadcrumb_type
|
||||
library_id = active_library_breadcrumb.library_id
|
||||
breadcrumb = (name, breadcrumb_type, library_id)
|
||||
change_back = True
|
||||
|
||||
bpy.ops.bim.rewind_library()
|
||||
if change_back:
|
||||
assert breadcrumb
|
||||
bpy.ops.bim.change_library_element(
|
||||
element_name=name,
|
||||
breadcrumb_type=breadcrumb_type,
|
||||
library_id=library_id,
|
||||
element_name=breadcrumb[0],
|
||||
breadcrumb_type=breadcrumb[1],
|
||||
library_id=breadcrumb[2],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -124,6 +124,9 @@ class Pset(bonsai.core.tool.Pset):
|
||||
return bpy.context.scene.GroupPsetProperties
|
||||
elif obj_type == "Zone":
|
||||
return bpy.context.scene.ZonePsetProperties
|
||||
elif obj_type == "Cost":
|
||||
# No psets for cost items currently.
|
||||
assert False, obj_type
|
||||
assert_never(obj_type)
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -505,6 +505,8 @@ class Search(bonsai.core.tool.Search):
|
||||
(0.773, 0.922, 0.816),
|
||||
(0.871, 0.957, 0.894),
|
||||
]
|
||||
else:
|
||||
assert False, theme
|
||||
|
||||
if value < min_val:
|
||||
value = min_val
|
||||
@@ -574,8 +576,10 @@ class ImportFilterQueryTransformer(lark.Transformer):
|
||||
new = self.filter_groups.add()
|
||||
global_ids = []
|
||||
is_first_group = len(self.filter_groups) == 1
|
||||
new2 = None
|
||||
for filter_index, arg in enumerate(args):
|
||||
if arg["type"] == "instance" and global_ids:
|
||||
assert new2
|
||||
if "bpy.data.texts" in new2.value:
|
||||
data_name = new2.value.split("bpy.data.texts")[1][2:-2]
|
||||
bpy.data.texts[data_name].write("," + arg["value"])
|
||||
|
||||
@@ -23,7 +23,7 @@ import re
|
||||
from collections.abc import Iterable
|
||||
from datetime import datetime
|
||||
from datetime import time as datetime_time
|
||||
from typing import TYPE_CHECKING, Any, Literal, Optional, Union
|
||||
from typing import TYPE_CHECKING, Any, Literal, Optional, Union, assert_never
|
||||
|
||||
import bpy
|
||||
import ifcopenshell
|
||||
@@ -1127,7 +1127,8 @@ class Sequence(bonsai.core.tool.Sequence):
|
||||
|
||||
@classmethod
|
||||
def load_default_animation_color_scheme(cls):
|
||||
groups = {
|
||||
GroupType = Literal["CREATION", "OPERATION", "MOVEMENT_TO", "DESTRUCTION", "MOVEMENT_FROM", "USERDEFINED"]
|
||||
groups: dict[GroupType, dict[str, Any]] = {
|
||||
"CREATION": {
|
||||
"PredefinedType": ["CONSTRUCTION", "INSTALLATION"],
|
||||
"Color": (0.0, 1.0, 0.0),
|
||||
@@ -1158,15 +1159,17 @@ class Sequence(bonsai.core.tool.Sequence):
|
||||
props.task_input_colors.clear()
|
||||
for group, data in groups.items():
|
||||
for predefined_type in data["PredefinedType"]:
|
||||
if group in ["CREATION", "OPERATION", "MOVEMENT_TO"]:
|
||||
if group in ("CREATION", "OPERATION", "MOVEMENT_TO"):
|
||||
predefined_type_item = props.task_output_colors.add()
|
||||
elif group in ["MOVEMENT_FROM"]:
|
||||
elif group in ("MOVEMENT_FROM",):
|
||||
predefined_type_item = props.task_input_colors.add()
|
||||
elif group in ["USERDEFINED", "DESTRUCTION"]:
|
||||
elif group in ("USERDEFINED", "DESTRUCTION"):
|
||||
predefined_type_item = props.task_input_colors.add()
|
||||
predefined_type_item2 = props.task_output_colors.add()
|
||||
predefined_type_item2.name = predefined_type
|
||||
predefined_type_item2.color = data["Color"]
|
||||
else:
|
||||
assert_never(group)
|
||||
# TO DO: consider cases where users confuses inputs and outputs
|
||||
predefined_type_item.name = predefined_type
|
||||
predefined_type_item.color = data["Color"]
|
||||
|
||||
@@ -225,6 +225,7 @@ class Snap(bonsai.core.tool.Snap):
|
||||
# Get axis that are closer than the stick factor threshold
|
||||
elegible_axis = []
|
||||
|
||||
axis = None
|
||||
for axis in snap_axis:
|
||||
if not axis:
|
||||
continue
|
||||
@@ -326,6 +327,7 @@ class Snap(bonsai.core.tool.Snap):
|
||||
detected_snaps: list[dict[str, Any]] = []
|
||||
|
||||
def select_plane_method():
|
||||
plane_origin, plane_normal = None, None
|
||||
if not last_polyline_point:
|
||||
plane_origin = Vector((0, 0, 0))
|
||||
plane_normal = Vector((0, 0, 1))
|
||||
@@ -357,6 +359,7 @@ class Snap(bonsai.core.tool.Snap):
|
||||
plane_origin = Vector((last_polyline_point.x, last_polyline_point.y, last_polyline_point.z))
|
||||
plane_normal = Vector((1, 0, 0))
|
||||
|
||||
assert plane_origin and plane_normal
|
||||
plane_normal = tool.Polyline.use_transform_orientations(plane_normal)
|
||||
return plane_origin, plane_normal
|
||||
|
||||
@@ -583,6 +586,7 @@ class Snap(bonsai.core.tool.Snap):
|
||||
|
||||
snaps_by_group = filter_snapping_points_by_group(detected_snaps)
|
||||
edges = [] # Get edges to create edge-intersection snap
|
||||
axis_start, axis_end = ..., ...
|
||||
for snapping_point in snaps_by_group:
|
||||
if snapping_point["group"] in {"Polyline", "Measure", "Wireframe", "Object"}:
|
||||
if snapping_point["type"] == "Edge":
|
||||
@@ -607,6 +611,7 @@ class Snap(bonsai.core.tool.Snap):
|
||||
if point["type"] == "Axis":
|
||||
if ordered_snaps[0]["type"] not in {"Axis", "Plane"}:
|
||||
obj = ordered_snaps[0]["object"]
|
||||
assert axis_start is not ... and axis_end is not ...
|
||||
mixed_snap = cls.mix_snap_and_axis(ordered_snaps[0], axis_start, axis_end)
|
||||
for mixed_point in mixed_snap:
|
||||
snap_point = {
|
||||
|
||||
@@ -304,12 +304,14 @@ class Spatial(bonsai.core.tool.Spatial):
|
||||
|
||||
while True:
|
||||
has_parent = None
|
||||
new_current_results = None
|
||||
for key in current_results:
|
||||
if flat_key.startswith(key):
|
||||
has_parent = True
|
||||
new_current_results = current_results[key]["children"]
|
||||
break
|
||||
if has_parent:
|
||||
assert new_current_results is not None
|
||||
current_results = new_current_results
|
||||
else:
|
||||
break
|
||||
@@ -978,19 +980,24 @@ class Spatial(bonsai.core.tool.Spatial):
|
||||
interiors_list = []
|
||||
|
||||
if union_geom.geom_type == "MultiPolygon":
|
||||
poly = None
|
||||
for poly in union_geom.geoms:
|
||||
interiors_list = cls.get_poly_valid_interior_list(
|
||||
poly=poly, min_area=min_area, interiors_list=interiors_list
|
||||
)
|
||||
|
||||
assert poly
|
||||
new_poly = Polygon(poly.exterior.coords, holes=interiors_list)
|
||||
|
||||
if union_geom.geom_type == "Polygon":
|
||||
elif union_geom.geom_type == "Polygon":
|
||||
interiors_list = cls.get_poly_valid_interior_list(
|
||||
poly=union_geom, min_area=min_area, interiors_list=interiors_list
|
||||
)
|
||||
new_poly = Polygon(union_geom.exterior.coords, holes=interiors_list)
|
||||
|
||||
else:
|
||||
assert False, union_geom.geom_type
|
||||
|
||||
return new_poly
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -360,6 +360,10 @@ class Style(bonsai.core.tool.Style):
|
||||
material_output = tool.Blender.get_material_node(obj, "OUTPUT_MATERIAL", {"is_active_output": True})
|
||||
surface_output = get_input_node(material_output, "Surface")
|
||||
|
||||
# TODO: this variable is not really needed,
|
||||
# just workaround a for ty issue detecting unresolved refs.
|
||||
bsdf = None
|
||||
|
||||
if surface_output and surface_output.type == "MIX_SHADER":
|
||||
mix_shader = surface_output
|
||||
if (
|
||||
@@ -388,6 +392,7 @@ class Style(bonsai.core.tool.Style):
|
||||
and (bsdf := get_input_node(surface_output, input_index=1, of_type="BSDF_PRINCIPLED"))
|
||||
)
|
||||
):
|
||||
assert bsdf
|
||||
report(f"Because of {BLUE}BSDF_PRINCIPLED{R} node reflectance method identified as {BLUE}PHYSICAL{R}")
|
||||
attributes["ReflectanceMethod"] = "NOTDEFINED" if tool.Ifc.get_schema() != "IFC4X3" else "PHYSICAL"
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ Blender versions:
|
||||
- 64-bit MacOS Intel (``macos-x64``)
|
||||
- 64-bit MacOS Silicon (``macos-arm64``)
|
||||
- 64-bit Windows (``windows-x64``)
|
||||
- Blender 4.3, 4.4, or 4.5 with Python 3.11
|
||||
- Blender 5.1 or 5.2 with Python 3.13
|
||||
|
||||
Developer builds may exist for different versions of Python but there will be
|
||||
no guarantee of the uptime or stability of these builds.
|
||||
|
||||
@@ -216,6 +216,7 @@ def update_translations_from_po(po_directory: Path, translations_module: Path):
|
||||
|
||||
|
||||
if BPY_IS_LOADED:
|
||||
import bpy
|
||||
|
||||
class SetupTranslationUI(bpy.types.Operator):
|
||||
bl_idname = "bim.setup_translation_ui"
|
||||
|
||||
@@ -82,6 +82,7 @@ class Generator:
|
||||
}
|
||||
""".replace("{entity}", location.split("#")[-1]))
|
||||
# filter parents for the brick entity
|
||||
parent = None
|
||||
for row in query:
|
||||
parent = row.get("parent").toPython()
|
||||
if "brickschema.org" in parent and parent in references.keys():
|
||||
|
||||
@@ -16,20 +16,26 @@
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with Bonsai. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import argparse
|
||||
|
||||
import ezdxf
|
||||
import ifcopenshell
|
||||
import ifcopenshell.guid
|
||||
|
||||
|
||||
class Dxf2Ifc:
|
||||
def __init__(self, dxf_path, outfile):
|
||||
self.dxf_path = dxf_path
|
||||
self.outfile = outfile
|
||||
|
||||
def execute(self):
|
||||
self.create_ifc_file()
|
||||
doc = ezdxf.readfile("input.dxf")
|
||||
doc = ezdxf.readfile(self.dxf_path)
|
||||
model = doc.modelspace()
|
||||
products = []
|
||||
for entity in model:
|
||||
print(entity)
|
||||
if entity.get_mode() == "AcDbPolyFaceMesh":
|
||||
if entity.dxftype() == "POLYLINE" and entity.is_poly_face_mesh:
|
||||
ifc_faces = []
|
||||
for face in entity.faces():
|
||||
ifc_faces.append(
|
||||
@@ -67,15 +73,18 @@ class Dxf2Ifc:
|
||||
"Name": entity.dxf.layer,
|
||||
"ObjectPlacement": self.placement,
|
||||
"Representation": representation,
|
||||
}
|
||||
},
|
||||
)
|
||||
)
|
||||
else:
|
||||
print("Not yet implemented")
|
||||
self.file.createIfcRelContainedInSpatialStructure(
|
||||
ifcopenshell.guid.new(), None, None, None, products, self.site
|
||||
)
|
||||
self.file.write("test.ifc")
|
||||
print(f"Skipping unsupported entity: {entity.dxftype()}")
|
||||
if products:
|
||||
self.file.createIfcRelContainedInSpatialStructure(
|
||||
ifcopenshell.guid.new(), None, None, None, products, self.site
|
||||
)
|
||||
else:
|
||||
print("No AcDbPolyFaceMesh entities found, writing an empty IFC")
|
||||
self.file.write(self.outfile)
|
||||
|
||||
def create_ifc_file(self):
|
||||
self.file = ifcopenshell.file()
|
||||
@@ -97,14 +106,20 @@ class Dxf2Ifc:
|
||||
"Name": "DXF Conversion",
|
||||
"RepresentationContexts": [self.context],
|
||||
"UnitsInContext": units,
|
||||
}
|
||||
},
|
||||
)
|
||||
self.site = self.file.create_entity(
|
||||
"IfcSite",
|
||||
**{"GlobalId": ifcopenshell.guid.new(), "Name": "DXF Conversion Site", "ObjectPlacement": self.placement}
|
||||
**{"GlobalId": ifcopenshell.guid.new(), "Name": "DXF Conversion Site", "ObjectPlacement": self.placement},
|
||||
)
|
||||
self.file.createIfcRelAggregates(ifcopenshell.guid.new(), None, None, None, self.project, [self.site])
|
||||
|
||||
|
||||
dxf2ifc = Dxf2Ifc()
|
||||
dxf2ifc.execute()
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description="Converts DXF polyface meshes (AcDbPolyFaceMesh) to an IFC")
|
||||
parser.add_argument("dxf", type=str, help="The input DXF file")
|
||||
parser.add_argument("-o", "--output", type=str, help="The output IFC file", default="out.ifc")
|
||||
args = parser.parse_args()
|
||||
|
||||
dxf2ifc = Dxf2Ifc(args.dxf, args.output)
|
||||
dxf2ifc.execute()
|
||||
|
||||
@@ -1036,6 +1036,7 @@ class LibraryGenerator:
|
||||
seat_width_offset = 0.7 * width / 2 if cistern_depth else width / 2
|
||||
seat_start_width_offset = 0.6 * width
|
||||
|
||||
cistern_3d = None
|
||||
if cistern_height:
|
||||
cistern = builder.rectangle(size=V(width, cistern_depth), position=shift_to_center)
|
||||
cistern_3d = ifcopenshell.util.element.copy_deep(self.file, cistern)
|
||||
@@ -1118,6 +1119,7 @@ class LibraryGenerator:
|
||||
|
||||
# cistern
|
||||
if cistern_height:
|
||||
assert cistern_3d
|
||||
cistern_3d = builder.extrude(
|
||||
cistern_3d, cistern_height + seat_level / 2, position=V(0, 0, seat_level / 2)
|
||||
)
|
||||
|
||||
@@ -143,6 +143,7 @@ class LibraryGenerator:
|
||||
if "unused" in ifc_params:
|
||||
del ifc_params["unused"]
|
||||
|
||||
profiles_gap = ...
|
||||
if prof_type == "profile_hollow*_square":
|
||||
ifc_params["YDim"] = ifc_params["XDim"]
|
||||
elif ifc_profile_name == "IfcCircleHollowProfileDef":
|
||||
@@ -160,6 +161,7 @@ class LibraryGenerator:
|
||||
profile = self.file.create_entity(ifc_profile_name, ProfileName=prof_name, ProfileType="AREA", **ifc_params)
|
||||
|
||||
if prof_type == "profile_l*lbeam_2l":
|
||||
assert profiles_gap is not ...
|
||||
profile.ProfileName = None # to avoid name confusion
|
||||
mode = "SLBB" if prof_name.endswith("_SLBB") else "LLBB"
|
||||
profile = self.create_double_l_profile(profile, prof_name, profiles_gap, mode)
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
# Bonsai - OpenBIM Blender Add-on
|
||||
# Copyright (C) 2026
|
||||
#
|
||||
# This file is part of Bonsai.
|
||||
#
|
||||
# Bonsai is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Bonsai is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with Bonsai. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
|
||||
"""Regression tests for ``ProfileDecorator``'s ``_connected_components`` helper.
|
||||
|
||||
Duplicating a circle/arc void's loop in Edit Mode (Tab, Tab, select the
|
||||
loop, Shift+D) copies the ``IFCARCINDEX``/``IFCCIRCLE`` vertex-group
|
||||
weights onto the new geometry, since Blender's mesh duplicate never
|
||||
allocates a new vertex group. Before this fix, ``ProfileDecorator``
|
||||
grouped arc/circle vertices by group index alone, so the duplicate's
|
||||
vertices piled into the same entry as the source loop's, failing the
|
||||
"exactly 2/3 verts" check and silently dropping *both* loops from the
|
||||
decorator until the mesh was re-imported (e.g. by leaving and re-entering
|
||||
Edit Mode). ``_connected_components`` splits each group's vertices back
|
||||
into their connected loops so a duplicate is drawn immediately, see #6944."""
|
||||
|
||||
import bmesh
|
||||
import bpy
|
||||
import pytest
|
||||
|
||||
from bonsai.bim.module.model.decorator import _connected_components
|
||||
|
||||
pytestmark = pytest.mark.model
|
||||
|
||||
|
||||
def _bm_with_groups(verts, edges, groups):
|
||||
"""Build a standalone bmesh with a deform layer, and populate ``groups``:
|
||||
a list of (group_index, [vert_indices]) pairs, mirroring how
|
||||
``tool.Model.import_profile``/``convert_curve_to_mesh`` assign one
|
||||
vertex group per circle/arc loop."""
|
||||
bm = bmesh.new()
|
||||
deform_layer = bm.verts.layers.deform.new()
|
||||
bm_verts = [bm.verts.new(v) for v in verts]
|
||||
bm.verts.ensure_lookup_table()
|
||||
for a, b in edges:
|
||||
bm.edges.new((bm_verts[a], bm_verts[b]))
|
||||
bm.verts.ensure_lookup_table()
|
||||
bm_verts = list(bm.verts)
|
||||
for group_index, vert_indices in groups:
|
||||
for vi in vert_indices:
|
||||
bm_verts[vi][deform_layer][group_index] = 1.0
|
||||
return bm, bm_verts, deform_layer
|
||||
|
||||
|
||||
def _group_dict(bm_verts, deform_layer, group_index, vert_indices):
|
||||
return {group_index: [bm_verts[i] for i in vert_indices]}
|
||||
|
||||
|
||||
def test_single_circle_loop_is_one_component():
|
||||
# A circle is exactly 2 verts joined by 1 edge (tool.Model.convert_curve_to_mesh).
|
||||
bm, bm_verts, deform_layer = _bm_with_groups(
|
||||
verts=[(0, -1, 0), (0, 1, 0)],
|
||||
edges=[(0, 1)],
|
||||
groups=[(0, [0, 1])],
|
||||
)
|
||||
circles = _group_dict(bm_verts, deform_layer, 0, [0, 1])
|
||||
components = _connected_components(circles)
|
||||
assert len(components) == 1
|
||||
assert len(components[0]) == 2
|
||||
bm.free()
|
||||
|
||||
|
||||
def test_single_arc_loop_is_one_component():
|
||||
# An arc is exactly 3 verts: endpoint-midpoint-endpoint (2 edges).
|
||||
bm, bm_verts, deform_layer = _bm_with_groups(
|
||||
verts=[(0, -1, 0), (0, 0, 0.3), (0, 1, 0)],
|
||||
edges=[(0, 1), (1, 2)],
|
||||
groups=[(0, [0, 1, 2])],
|
||||
)
|
||||
arcs = _group_dict(bm_verts, deform_layer, 0, [0, 1, 2])
|
||||
components = _connected_components(arcs)
|
||||
assert len(components) == 1
|
||||
assert len(components[0]) == 3
|
||||
bm.free()
|
||||
|
||||
|
||||
def test_duplicated_circle_loop_splits_into_two_components():
|
||||
# Duplicating verts 0-1 (Shift+D) yields verts 2-3, connected to each
|
||||
# other but NOT to the source loop, while keeping the same group index
|
||||
# (0) -- exactly what bmesh.ops.duplicate produces mid Edit-Mode.
|
||||
bm, bm_verts, deform_layer = _bm_with_groups(
|
||||
verts=[(0, -1, 0), (0, 1, 0), (5, -1, 0), (5, 1, 0)],
|
||||
edges=[(0, 1), (2, 3)],
|
||||
groups=[(0, [0, 1, 2, 3])],
|
||||
)
|
||||
circles = _group_dict(bm_verts, deform_layer, 0, [0, 1, 2, 3])
|
||||
components = _connected_components(circles)
|
||||
assert len(components) == 2
|
||||
assert sorted(len(c) for c in components) == [2, 2]
|
||||
bm.free()
|
||||
|
||||
|
||||
def test_duplicated_arc_loop_splits_into_two_components():
|
||||
bm, bm_verts, deform_layer = _bm_with_groups(
|
||||
verts=[(0, -1, 0), (0, 0, 0.3), (0, 1, 0), (5, -1, 0), (5, 0, 0.3), (5, 1, 0)],
|
||||
edges=[(0, 1), (1, 2), (3, 4), (4, 5)],
|
||||
groups=[(0, [0, 1, 2, 3, 4, 5])],
|
||||
)
|
||||
arcs = _group_dict(bm_verts, deform_layer, 0, [0, 1, 2, 3, 4, 5])
|
||||
components = _connected_components(arcs)
|
||||
assert len(components) == 2
|
||||
assert sorted(len(c) for c in components) == [3, 3]
|
||||
bm.free()
|
||||
|
||||
|
||||
def test_distinct_circle_groups_stay_separate_and_correctly_sized():
|
||||
# Multiple genuinely different circles (distinct group indices) must
|
||||
# each still resolve to their own single 2-vert component.
|
||||
verts = []
|
||||
edges = []
|
||||
groups = []
|
||||
for i in range(5):
|
||||
base = len(verts)
|
||||
verts += [(i * 3, -1, 0), (i * 3, 1, 0)]
|
||||
edges.append((base, base + 1))
|
||||
groups.append((i, [base, base + 1]))
|
||||
bm, bm_verts, deform_layer = _bm_with_groups(verts, edges, groups)
|
||||
circles = {}
|
||||
for group_index, vert_indices in groups:
|
||||
circles[group_index] = [bm_verts[i] for i in vert_indices]
|
||||
components = _connected_components(circles)
|
||||
assert len(components) == 5
|
||||
assert all(len(c) == 2 for c in components)
|
||||
bm.free()
|
||||
@@ -453,6 +453,59 @@ class TestDuplicateDrawing:
|
||||
subject.duplicate_drawing(ifc, blender, drawing, geometry, drawing="drawing", should_duplicate_annotations=True)
|
||||
|
||||
|
||||
class TestCopyAnnotationsToDrawing:
|
||||
def test_run(self, ifc: Prophecy, collector: Prophecy, drawing: Prophecy, geometry: Prophecy):
|
||||
drawing.get_drawing_group("target_drawing").should_be_called().will_return("target_group")
|
||||
drawing.get_annotation_drawing("annotation").should_be_called().will_return("source_drawing")
|
||||
ifc.get_object("annotation").should_be_called().will_return("annotation_obj")
|
||||
ifc.get_object("target_drawing").should_be_called().will_return("camera")
|
||||
geometry.duplicate_ifc_objects(["annotation_obj"]).should_be_called().will_return(
|
||||
({"annotation": ["new_annotation"]}, None)
|
||||
)
|
||||
drawing.get_drawing_group("new_annotation").should_be_called().will_return("source_group")
|
||||
ifc.run("group.unassign_group", group="source_group", products=["new_annotation"]).should_be_called()
|
||||
ifc.run("group.assign_group", group="target_group", products=["new_annotation"]).should_be_called()
|
||||
ifc.get_object("new_annotation").should_be_called().will_return("new_annotation_obj")
|
||||
drawing.ensure_annotation_in_drawing_plane("new_annotation_obj", "camera").should_be_called()
|
||||
collector.assign("new_annotation_obj", should_clean_users_collection=True).should_be_called()
|
||||
assert subject.copy_annotations_to_drawing(
|
||||
ifc, collector, drawing, geometry, annotations=["annotation"], target_drawing="target_drawing"
|
||||
) == ["new_annotation"]
|
||||
|
||||
def test_skipping_annotations_already_in_the_target_drawing(
|
||||
self, ifc: Prophecy, collector: Prophecy, drawing: Prophecy, geometry: Prophecy
|
||||
):
|
||||
drawing.get_drawing_group("target_drawing").should_be_called().will_return("target_group")
|
||||
drawing.get_annotation_drawing("annotation").should_be_called().will_return("target_drawing")
|
||||
assert (
|
||||
subject.copy_annotations_to_drawing(
|
||||
ifc, collector, drawing, geometry, annotations=["annotation"], target_drawing="target_drawing"
|
||||
)
|
||||
== []
|
||||
)
|
||||
|
||||
def test_importing_the_target_camera_when_it_is_not_loaded(
|
||||
self, ifc: Prophecy, collector: Prophecy, drawing: Prophecy, geometry: Prophecy
|
||||
):
|
||||
drawing.get_drawing_group("target_drawing").should_be_called().will_return("target_group")
|
||||
drawing.get_annotation_drawing("annotation").should_be_called().will_return("source_drawing")
|
||||
ifc.get_object("annotation").should_be_called().will_return("annotation_obj")
|
||||
ifc.get_object("target_drawing").should_be_called().will_return(None)
|
||||
drawing.import_drawing("target_drawing").should_be_called().will_return("camera")
|
||||
geometry.duplicate_ifc_objects(["annotation_obj"]).should_be_called().will_return(
|
||||
({"annotation": ["new_annotation"]}, None)
|
||||
)
|
||||
drawing.get_drawing_group("new_annotation").should_be_called().will_return("source_group")
|
||||
ifc.run("group.unassign_group", group="source_group", products=["new_annotation"]).should_be_called()
|
||||
ifc.run("group.assign_group", group="target_group", products=["new_annotation"]).should_be_called()
|
||||
ifc.get_object("new_annotation").should_be_called().will_return("new_annotation_obj")
|
||||
drawing.ensure_annotation_in_drawing_plane("new_annotation_obj", "camera").should_be_called()
|
||||
collector.assign("new_annotation_obj", should_clean_users_collection=True).should_be_called()
|
||||
assert subject.copy_annotations_to_drawing(
|
||||
ifc, collector, drawing, geometry, annotations=["annotation"], target_drawing="target_drawing"
|
||||
) == ["new_annotation"]
|
||||
|
||||
|
||||
class TestRemoveDrawing:
|
||||
def test_run(self, ifc, drawing):
|
||||
drawing.is_active_drawing("drawing").should_be_called().will_return(True)
|
||||
|
||||
@@ -112,6 +112,51 @@ class TestImportCameraProps(NewFile):
|
||||
assert camera.shift_x == 0.0
|
||||
assert camera.shift_y == 0.0
|
||||
|
||||
def test_defaults_edge_classification_props_when_pset_is_absent(self):
|
||||
ifc = ifcopenshell.file()
|
||||
tool.Ifc.set(ifc)
|
||||
drawing = ifc.createIfcAnnotation(ObjectType="DRAWING")
|
||||
camera = bpy.data.cameras.new("Camera")
|
||||
|
||||
subject.import_camera_props(drawing, camera)
|
||||
|
||||
props = subject.get_camera_props(camera)
|
||||
assert props.use_edge_classification is False
|
||||
assert props.render_creases is True
|
||||
assert props.valley_angle_min_degrees == pytest.approx(12.0)
|
||||
assert props.render_sharp is True
|
||||
assert props.ridge_angle_min_degrees == pytest.approx(45.0)
|
||||
assert props.render_flush is False
|
||||
|
||||
def test_imports_edge_classification_props_from_drawing_pset(self):
|
||||
ifc = ifcopenshell.file()
|
||||
tool.Ifc.set(ifc)
|
||||
drawing = ifc.createIfcAnnotation(ObjectType="DRAWING")
|
||||
pset = ifcopenshell.api.pset.add_pset(ifc, product=drawing, name="EPset_Drawing")
|
||||
ifcopenshell.api.pset.edit_pset(
|
||||
ifc,
|
||||
pset=pset,
|
||||
properties={
|
||||
"UseEdgeClassification": True,
|
||||
"RenderCreases": False,
|
||||
"ValleyAngleMinDegrees": 8.0,
|
||||
"RenderSharp": False,
|
||||
"RidgeAngleMinDegrees": 30.0,
|
||||
"RenderFlush": True,
|
||||
},
|
||||
)
|
||||
camera = bpy.data.cameras.new("Camera")
|
||||
|
||||
subject.import_camera_props(drawing, camera)
|
||||
|
||||
props = subject.get_camera_props(camera)
|
||||
assert props.use_edge_classification is True
|
||||
assert props.render_creases is False
|
||||
assert props.valley_angle_min_degrees == pytest.approx(8.0)
|
||||
assert props.render_sharp is False
|
||||
assert props.ridge_angle_min_degrees == pytest.approx(30.0)
|
||||
assert props.render_flush is True
|
||||
|
||||
|
||||
class TestSyncPerspectiveCameraShifts(NewFile):
|
||||
def test_round_trips_perspective_camera_shifts_through_drawing_pset(self):
|
||||
@@ -461,6 +506,25 @@ class TestGetDrawingGroup(NewFile):
|
||||
assert subject.get_drawing_group(element) == group
|
||||
|
||||
|
||||
class TestGetGroupDrawing(NewFile):
|
||||
def test_run(self):
|
||||
ifc = ifcopenshell.file()
|
||||
tool.Ifc.set(ifc)
|
||||
drawing = ifc.createIfcAnnotation(ObjectType="DRAWING")
|
||||
group = ifcopenshell.api.group.add_group(ifc)
|
||||
group.ObjectType = "DRAWING"
|
||||
ifcopenshell.api.group.assign_group(ifc, products=[drawing], group=group)
|
||||
assert subject.get_group_drawing(group) == drawing
|
||||
|
||||
def test_ignores_groups_that_are_not_drawings(self):
|
||||
ifc = ifcopenshell.file()
|
||||
tool.Ifc.set(ifc)
|
||||
drawing = ifc.createIfcAnnotation(ObjectType="DRAWING")
|
||||
group = ifcopenshell.api.group.add_group(ifc)
|
||||
ifcopenshell.api.group.assign_group(ifc, products=[drawing], group=group)
|
||||
assert subject.get_group_drawing(group) is None
|
||||
|
||||
|
||||
class TestGetDrawingTargetView(NewFile):
|
||||
def test_run(self):
|
||||
ifc = ifcopenshell.file()
|
||||
|
||||
@@ -6,10 +6,10 @@ Files and scripts for the use of [`Code_Aster`](https://code-aster.org) in IFC-d
|
||||
## Scripts:
|
||||
|
||||
- [`ifc2ca.py`](ifc2ca.py): a python script to extract and create a `json` file from an `ifc` file
|
||||
- [`scriptSalome.py`](scriptSalome.py): a python script to run in the [`Salome-Meca`](https://www.code-aster.org/spip.php?article303) environment. Creates the geometry and the mesh of the structure
|
||||
- [`scriptSalome.py`](templates/salome/scriptSalome.py): a python script to run in the [`Salome-Meca`](https://www.code-aster.org/spip.php?article303) environment. Creates the geometry and the mesh of the structure
|
||||
- [`scriptCodeAster.py`](scriptCodeAster.py): a python script to create the input file (`.comm`) for Code_Aster
|
||||
- [`scriptSalomeBonded.py`](scriptSalomeBonded.py): a python script to run in the [`Salome-Meca`](https://www.code-aster.org/spip.php?article303) environment. Creates the geometry and the mesh of the structure by bonding together all structural elements (no connections are considered)
|
||||
- [`scriptCodeAsterBonded.py`](scriptCodeAsterBonded.py): a python script to create the input file (`.comm`) for Code_Aster for the "bonded" case
|
||||
- [`scriptSalomeBonded.py`](_deprecated/scriptSalomeBonded.py): a python script to run in the [`Salome-Meca`](https://www.code-aster.org/spip.php?article303) environment. Creates the geometry and the mesh of the structure by bonding together all structural elements (no connections are considered). Located under `_deprecated/`.
|
||||
- [`scriptCodeAsterBonded.py`](_deprecated/scriptCodeAsterBonded.py): a python script to create the input file (`.comm`) for Code_Aster for the "bonded" case. Located under `_deprecated/`.
|
||||
|
||||
## Analysis Models
|
||||
|
||||
|
||||
@@ -27,10 +27,12 @@ flatten = itertools.chain.from_iterable
|
||||
|
||||
def get_element_data(model, name, element):
|
||||
if element["geometry_type"] == "Edge":
|
||||
cell_tags, cell_block = None, None
|
||||
for i, cell_block in enumerate(model.cells):
|
||||
if cell_block.type == "line":
|
||||
cell_tags = model.cell_data["cell_tags"][i]
|
||||
break
|
||||
assert cell_tags is not None and cell_block is not None
|
||||
rows = []
|
||||
for i_row, i in enumerate(cell_tags):
|
||||
if i == 0:
|
||||
@@ -59,6 +61,7 @@ def get_element_data(model, name, element):
|
||||
elif element["geometry_type"] == "Face":
|
||||
triangle_cell_tags = None
|
||||
quad_cell_tags = None
|
||||
points, cell_block = None, None
|
||||
for i, cell_block in enumerate(model.cells):
|
||||
if cell_block.type == "triangle":
|
||||
triangle_cell_tags = model.cell_data["cell_tags"][i]
|
||||
@@ -78,8 +81,10 @@ def get_element_data(model, name, element):
|
||||
if not len(rows):
|
||||
points = []
|
||||
else:
|
||||
assert cell_block is not None
|
||||
points = list(flatten([cell_block.data[c] for c in rows]))
|
||||
|
||||
cell_block = None
|
||||
for i, cell_block in enumerate(model.cells):
|
||||
if cell_block.type == "quad":
|
||||
quad_cell_tags = model.cell_data["cell_tags"][i]
|
||||
@@ -97,6 +102,7 @@ def get_element_data(model, name, element):
|
||||
rows.append(i_row)
|
||||
break
|
||||
if len(rows):
|
||||
assert cell_block is not None and points is not None
|
||||
points.extend(list(flatten([cell_block.data[c] for c in rows])))
|
||||
|
||||
points = list(set(points))
|
||||
@@ -172,6 +178,8 @@ def results_to_ifc(ifc_file, ifc_model, rmed_path, global_case, field_types, dat
|
||||
model_cases = data["load_cases"]
|
||||
elif global_case == "COMB":
|
||||
model_cases = data["load_combinations"]
|
||||
else:
|
||||
assert False, global_case
|
||||
for field in field_types:
|
||||
if field == "InternalForces":
|
||||
_parsed_data = internal_forces_to_ifc(ifc_file, ifc_model, result, model_cases, data["elements"])
|
||||
|
||||
+19
-2
@@ -283,7 +283,7 @@ class Ifc2CA:
|
||||
geometry = [x.EdgeStart.VertexGeometry.Coordinates for x in repr_item.Bounds[0].Bound.EdgeList]
|
||||
|
||||
else:
|
||||
print(representation)
|
||||
assert False, representation
|
||||
return geometry
|
||||
|
||||
def parse_material(self, material: ios.entity_instance):
|
||||
@@ -399,6 +399,9 @@ class Ifc2CA:
|
||||
elif element.is_a("IfcStructuralSurfaceMember"):
|
||||
placement = ifcopenshell.util.placement.get_axis2placement(repr_item.FaceSurface.Position)
|
||||
|
||||
else:
|
||||
assert False, element
|
||||
|
||||
origin, orientation = self.parse_transformation_matrix(placement)
|
||||
data["origin"] = origin
|
||||
data["orientation"] = orientation
|
||||
@@ -436,7 +439,7 @@ class Ifc2CA:
|
||||
for i, v in enumerate(placement[:3]):
|
||||
v[3] = data["geometry"][i]
|
||||
|
||||
if connection.is_a("IfcStructuralCurveConnection"):
|
||||
elif connection.is_a("IfcStructuralCurveConnection"):
|
||||
placement = ifcopenshell.util.placement.a2p(
|
||||
data["geometry"][0],
|
||||
connection.Axis.DirectionRatios,
|
||||
@@ -446,6 +449,9 @@ class Ifc2CA:
|
||||
elif connection.is_a("IfcStructuralSurfaceConnection"):
|
||||
placement = ifcopenshell.util.placement.get_axis2placement(repr_item.FaceSurface.Position)
|
||||
|
||||
else:
|
||||
assert False, connection
|
||||
|
||||
origin, orientation = self.parse_transformation_matrix(placement)
|
||||
data["origin"] = origin
|
||||
data["orientation"] = orientation
|
||||
@@ -552,6 +558,9 @@ class Ifc2CA:
|
||||
},
|
||||
}
|
||||
|
||||
else:
|
||||
assert False, element["geometry_type"]
|
||||
|
||||
for action in actions:
|
||||
self.add_action_loads(element, action, data, load_cases)
|
||||
|
||||
@@ -586,6 +595,7 @@ class Ifc2CA:
|
||||
|
||||
data["actions"].append(action.get_info() | {"AppliedLoad": action.AppliedLoad.get_info()})
|
||||
if element["geometry_type"] in ["Vertex", "Edge"]:
|
||||
force_projection_coeff, moment_projection_coeff = None, None
|
||||
if action.is_a("IfcStructuralPointAction") and load.is_a("IfcStructuralLoadSingleForce"):
|
||||
FX = tempFX = load.ForceX if load.ForceX is not None else 0.0
|
||||
FY = tempFY = load.ForceY if load.ForceY is not None else 0.0
|
||||
@@ -639,8 +649,12 @@ class Ifc2CA:
|
||||
force_projection_coeff = 1.0
|
||||
moment_projection_coeff = 1.0
|
||||
|
||||
else:
|
||||
assert False, action
|
||||
|
||||
for iLC, load_case in enumerate(load_cases):
|
||||
if load_case.id() in active_load_case_ids:
|
||||
assert force_projection_coeff is not None and moment_projection_coeff is not None
|
||||
load_case_coeff = 1.0 if load_case.Coefficient is None else load_case.Coefficient
|
||||
data["loadGroups"].append(load_group.Name)
|
||||
data["loadsLC"]["FX"][iLC] += FX * load_group_coeff * load_case_coeff * force_projection_coeff
|
||||
@@ -672,6 +686,9 @@ class Ifc2CA:
|
||||
else:
|
||||
force_projection_coeff = 1.0
|
||||
|
||||
else:
|
||||
assert False, action
|
||||
|
||||
for iLC, load_case in enumerate(load_cases):
|
||||
if load_case.id() in active_load_case_ids:
|
||||
load_case_coeff = 1.0 if load_case.Coefficient is None else load_case.Coefficient
|
||||
|
||||
@@ -383,11 +383,11 @@
|
||||
},
|
||||
"IfcOpeningElement": {
|
||||
"Qto_OpeningElementBaseQuantities": {
|
||||
"Area": "gross_get_max_side_area",
|
||||
"Depth": "gross_get_z",
|
||||
"Height": "gross_get_y",
|
||||
"Area": "gross_get_opening_area",
|
||||
"Depth": "gross_get_opening_depth",
|
||||
"Height": "gross_get_opening_height",
|
||||
"Volume": "gross_get_volume",
|
||||
"Width": "gross_get_x"
|
||||
"Width": "gross_get_opening_width"
|
||||
}
|
||||
},
|
||||
"IfcOutlet": {
|
||||
|
||||
@@ -387,7 +387,7 @@
|
||||
"Depth": "get_opening_depth",
|
||||
"Height": "get_opening_height",
|
||||
"Volume": "get_net_volume",
|
||||
"Width": "get_length"
|
||||
"Width": "get_x"
|
||||
}
|
||||
},
|
||||
"IfcOutlet": {
|
||||
|
||||
@@ -472,11 +472,11 @@
|
||||
},
|
||||
"IfcOpeningElement": {
|
||||
"Qto_OpeningElementBaseQuantities": {
|
||||
"Area": "gross_get_max_side_area",
|
||||
"Depth": "gross_get_z",
|
||||
"Height": "gross_get_y",
|
||||
"Area": "gross_get_opening_area",
|
||||
"Depth": "gross_get_opening_depth",
|
||||
"Height": "gross_get_opening_height",
|
||||
"Volume": "gross_get_volume",
|
||||
"Width": "gross_get_x"
|
||||
"Width": "gross_get_opening_width"
|
||||
}
|
||||
},
|
||||
"IfcOutlet + IfcOutletType": {
|
||||
|
||||
@@ -476,7 +476,7 @@
|
||||
"Depth": "get_opening_depth",
|
||||
"Height": "get_opening_height",
|
||||
"Volume": "get_net_volume",
|
||||
"Width": "get_length"
|
||||
"Width": "get_x"
|
||||
}
|
||||
},
|
||||
"IfcOutlet + IfcOutletType": {
|
||||
|
||||
@@ -109,6 +109,8 @@ class ifc5D2json:
|
||||
values = root_element.CostValues
|
||||
elif root_element.is_a("IfcConstructionResource"):
|
||||
values = root_element.BaseCosts
|
||||
else:
|
||||
assert False, root_element
|
||||
for cost_value in values or []:
|
||||
self.extract_cost_value(root_element, data, cost_value)
|
||||
# data["CostValues"].append(cost_value.id())
|
||||
|
||||
@@ -478,6 +478,8 @@ class Ifc5DOdsWriter(Ifc5Dwriter):
|
||||
cell.addElement(P(text=value))
|
||||
elif type == "formula":
|
||||
cell = TableCell(formula=value, stylename=style)
|
||||
else:
|
||||
assert False, type
|
||||
row.addElement(cell)
|
||||
|
||||
def add_cost_item_rows(table, cost_data):
|
||||
@@ -715,6 +717,8 @@ if __name__ == "__main__":
|
||||
writer = Ifc5DOdsWriter(args["input"], args["output"])
|
||||
elif args["format"] == "XLSX":
|
||||
writer = Ifc5DXlsxWriter(args["input"], args["output"])
|
||||
else:
|
||||
assert False, args
|
||||
writer.write()
|
||||
|
||||
logger.info("Finished conversion in %ss", time.time() - start)
|
||||
|
||||
@@ -254,6 +254,17 @@ class IfcOpenShell(QtoCalculator):
|
||||
"get_segment_length": Function(
|
||||
"IfcLengthMeasure", "Segment Length", "Intelligently guesses the length of flow segments"
|
||||
),
|
||||
"get_opening_width": Function(
|
||||
"IfcLengthMeasure", "Opening Width", "The width of an opening, guessing the opening orientation"
|
||||
),
|
||||
"get_opening_height": Function(
|
||||
"IfcLengthMeasure", "Opening Height", "The height of an opening, guessing the opening orientation"
|
||||
),
|
||||
"get_opening_depth": Function(
|
||||
"IfcLengthMeasure",
|
||||
"Opening Depth",
|
||||
"The depth of an opening (through the voided element), guessing the opening orientation",
|
||||
),
|
||||
# IfcAreaMeasure
|
||||
"get_area": Function("IfcAreaMeasure", "Area", "The total surface area of the element"),
|
||||
"get_footprint_area": Function(
|
||||
@@ -276,6 +287,9 @@ class IfcOpenShell(QtoCalculator):
|
||||
"Side area",
|
||||
"The side (non-projected) are of the shape as seen from the local Y-axis",
|
||||
),
|
||||
"get_opening_area": Function(
|
||||
"IfcAreaMeasure", "Opening Area", "The area of an opening, guessing the opening orientation"
|
||||
),
|
||||
"get_top_area": Function(
|
||||
"IfcAreaMeasure",
|
||||
"Top area",
|
||||
@@ -301,6 +315,10 @@ class IfcOpenShell(QtoCalculator):
|
||||
internal_functions = (
|
||||
"get_segment_length",
|
||||
"get_weight",
|
||||
"get_opening_width",
|
||||
"get_opening_height",
|
||||
"get_opening_depth",
|
||||
"get_opening_area",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
@@ -365,6 +383,9 @@ class IfcOpenShell(QtoCalculator):
|
||||
value = cls.get_weight(element, geometry, calculation_type)
|
||||
if value is None:
|
||||
continue
|
||||
elif formula.startswith("get_opening_"):
|
||||
value = cls.get_opening_quantity(geometry, formula)
|
||||
value = cls.unit_converter.convert(value, IfcOpenShell.raw_functions[formula].measure)
|
||||
else:
|
||||
value = formula_functions[formula](geometry)
|
||||
assert isinstance(value, (float, int))
|
||||
@@ -389,6 +410,34 @@ class IfcOpenShell(QtoCalculator):
|
||||
)
|
||||
return iterators
|
||||
|
||||
@classmethod
|
||||
def get_opening_quantity(cls, geometry: ifcopenshell.geom.ShapeType, formula: str) -> float:
|
||||
"""Get an opening dimension or area, guessing the opening orientation.
|
||||
|
||||
Vertical (wall) openings are measured in a Z-up local frame: X along
|
||||
the voided element, Y through it, Z vertical. An opening is treated as
|
||||
horizontal (e.g. voiding a slab) when its Z extent is smaller than
|
||||
both X and Y, matching the Blender calculator's heuristic.
|
||||
|
||||
:param geometry: Geometry output calculated by IfcOpenShell
|
||||
:param formula: One of the ``get_opening_*`` internal function names.
|
||||
:return: The dimension or area in SI units.
|
||||
"""
|
||||
x = ifcopenshell.util.shape.get_x(geometry)
|
||||
y = ifcopenshell.util.shape.get_y(geometry)
|
||||
z = ifcopenshell.util.shape.get_z(geometry)
|
||||
is_horizontal = z < x and z < y
|
||||
if formula == "get_opening_width":
|
||||
return x
|
||||
if formula == "get_opening_height":
|
||||
return min(x, y) if is_horizontal else z
|
||||
if formula == "get_opening_depth":
|
||||
return z if is_horizontal else y
|
||||
assert formula == "get_opening_area"
|
||||
if is_horizontal:
|
||||
return ifcopenshell.util.shape.get_footprint_area(geometry)
|
||||
return ifcopenshell.util.shape.get_side_area(geometry)
|
||||
|
||||
@classmethod
|
||||
def get_segment_length(cls, element: ifcopenshell.entity_instance) -> Union[float, None]:
|
||||
"""Get segment length.
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
# Ifc5D - IFC costing utility
|
||||
# Copyright (C) 2026 Dion Moult <dion@thinkmoult.com>
|
||||
#
|
||||
# This file is part of Ifc5D.
|
||||
#
|
||||
# Ifc5D is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Ifc5D is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with Ifc5D. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
|
||||
import ifcopenshell
|
||||
import ifcopenshell.api.context
|
||||
import ifcopenshell.api.root
|
||||
import ifcopenshell.api.unit
|
||||
import pytest
|
||||
|
||||
import ifc5d.qto
|
||||
|
||||
|
||||
class TestOpeningQuantities:
|
||||
"""Openings authored in a Z-up local frame, as produced by Bonsai (#6835)."""
|
||||
|
||||
def setup_method(self):
|
||||
self.file = ifcopenshell.file(schema="IFC4X3")
|
||||
ifcopenshell.api.root.create_entity(self.file, ifc_class="IfcProject", name="Test")
|
||||
f = self.file
|
||||
units = [
|
||||
f.createIfcSIUnit(None, "LENGTHUNIT", None, "METRE"),
|
||||
f.createIfcSIUnit(None, "AREAUNIT", None, "SQUARE_METRE"),
|
||||
f.createIfcSIUnit(None, "VOLUMEUNIT", None, "CUBIC_METRE"),
|
||||
]
|
||||
ifcopenshell.api.unit.assign_unit(self.file, units=units)
|
||||
model = ifcopenshell.api.context.add_context(self.file, context_type="Model")
|
||||
self.body = ifcopenshell.api.context.add_context(
|
||||
self.file, context_type="Model", context_identifier="Body", target_view="MODEL_VIEW", parent=model
|
||||
)
|
||||
|
||||
def create_opening(self, profile_x: float, profile_y: float, position, extrude_dir, depth: float):
|
||||
f = self.file
|
||||
opening = ifcopenshell.api.root.create_entity(f, ifc_class="IfcOpeningElement")
|
||||
opening.ObjectPlacement = f.createIfcLocalPlacement(
|
||||
None, f.createIfcAxis2Placement3D(f.createIfcCartesianPoint((0.0, 0.0, 0.0)), None, None)
|
||||
)
|
||||
profile = f.createIfcRectangleProfileDef("AREA", None, None, profile_x, profile_y)
|
||||
solid = f.createIfcExtrudedAreaSolid(profile, position, f.createIfcDirection(extrude_dir), depth)
|
||||
rep = f.createIfcShapeRepresentation(self.body, "Body", "SweptSolid", [solid])
|
||||
opening.Representation = f.createIfcProductDefinitionShape(None, None, [rep])
|
||||
return opening
|
||||
|
||||
def quantify(self, opening) -> dict[str, float]:
|
||||
rules = ifc5d.qto.rules["IFC4X3QtoBaseQuantities"]
|
||||
results = ifc5d.qto.quantify(self.file, {opening}, rules)
|
||||
return results[opening]["Qto_OpeningElementBaseQuantities"]
|
||||
|
||||
def test_vertical_wall_opening(self):
|
||||
# A 0.9 x 2.0 door opening voiding a wall along +Y, with Bonsai's
|
||||
# oversized 1.2m void depth: local extents x=0.9, y=1.2, z=2.0.
|
||||
f = self.file
|
||||
position = f.createIfcAxis2Placement3D(
|
||||
f.createIfcCartesianPoint((0.0, -0.6, 1.0)),
|
||||
f.createIfcDirection((0.0, -1.0, 0.0)),
|
||||
f.createIfcDirection((1.0, 0.0, 0.0)),
|
||||
)
|
||||
opening = self.create_opening(0.9, 2.0, position, (0.0, 0.0, -1.0), 1.2)
|
||||
quantities = self.quantify(opening)
|
||||
assert quantities["Width"] == pytest.approx(0.9)
|
||||
assert quantities["Height"] == pytest.approx(2.0)
|
||||
assert quantities["Depth"] == pytest.approx(1.2)
|
||||
assert quantities["Area"] == pytest.approx(1.8)
|
||||
assert quantities["Volume"] == pytest.approx(2.16)
|
||||
|
||||
def test_horizontal_slab_opening(self):
|
||||
# A 1.0 x 0.5 opening voiding a 0.3 thick slab: extents x=1.0, y=0.5, z=0.3.
|
||||
f = self.file
|
||||
position = f.createIfcAxis2Placement3D(f.createIfcCartesianPoint((0.0, 0.0, 0.0)), None, None)
|
||||
opening = self.create_opening(1.0, 0.5, position, (0.0, 0.0, -1.0), 0.3)
|
||||
quantities = self.quantify(opening)
|
||||
assert quantities["Width"] == pytest.approx(1.0)
|
||||
assert quantities["Height"] == pytest.approx(0.5)
|
||||
assert quantities["Depth"] == pytest.approx(0.3)
|
||||
assert quantities["Area"] == pytest.approx(0.5)
|
||||
assert quantities["Volume"] == pytest.approx(0.15)
|
||||
@@ -675,7 +675,7 @@ int main(int argc, char** argv) {
|
||||
time_t start, end;
|
||||
time(&start);
|
||||
if (output_extension == XML) {
|
||||
XmlSerializer s(ifc_file, IfcUtil::path::to_utf8(output_temp_filename), logger);
|
||||
XmlSerializer s(ifc_file, IfcUtil::path::to_utf8(output_temp_filename), &logger);
|
||||
logger.Status("Writing XML output...");
|
||||
s.finalize();
|
||||
} else {
|
||||
@@ -834,14 +834,14 @@ int main(int argc, char** argv) {
|
||||
if (output_extension == OBJ) {
|
||||
// Do not use temp file for MTL as it's such a small file.
|
||||
const path_t mtl_filename = change_extension(output_filename, MTL);
|
||||
serializer = boost::make_shared<WaveFrontOBJSerializer>(IfcUtil::path::to_utf8(output_temp_filename), IfcUtil::path::to_utf8(mtl_filename), geometry_settings, serializer_settings, logger);
|
||||
serializer = boost::make_shared<WaveFrontOBJSerializer>(IfcUtil::path::to_utf8(output_temp_filename), IfcUtil::path::to_utf8(mtl_filename), geometry_settings, serializer_settings, &logger);
|
||||
#ifdef WITH_OPENCOLLADA
|
||||
} else if (output_extension == DAE) {
|
||||
serializer = boost::make_shared<ColladaSerializer>(IfcUtil::path::to_utf8(output_temp_filename), geometry_settings, serializer_settings, logger);
|
||||
serializer = boost::make_shared<ColladaSerializer>(IfcUtil::path::to_utf8(output_temp_filename), geometry_settings, serializer_settings, &logger);
|
||||
#endif
|
||||
#ifdef WITH_GLTF
|
||||
} else if (output_extension == GLB) {
|
||||
serializer = boost::make_shared<GltfSerializer>(IfcUtil::path::to_utf8(output_temp_filename), geometry_settings, serializer_settings, logger);
|
||||
serializer = boost::make_shared<GltfSerializer>(IfcUtil::path::to_utf8(output_temp_filename), geometry_settings, serializer_settings, &logger);
|
||||
#endif
|
||||
#ifdef WITH_USD
|
||||
} else if (output_extension == USD || output_extension == USDA || output_extension == USDC) {
|
||||
@@ -858,15 +858,15 @@ int main(int argc, char** argv) {
|
||||
serializer = boost::make_shared<IgesSerializer>(IfcUtil::path::to_utf8(output_temp_filename), geometry_settings, serializer_settings, logger);
|
||||
} else if (output_extension == SVG) {
|
||||
geometry_settings.get<ifcopenshell::geometry::settings::IteratorOutput>().value = ifcopenshell::geometry::settings::NATIVE;
|
||||
serializer = boost::make_shared<SvgSerializer>(IfcUtil::path::to_utf8(output_temp_filename), geometry_settings, serializer_settings, logger);
|
||||
serializer = boost::make_shared<SvgSerializer>(IfcUtil::path::to_utf8(output_temp_filename), geometry_settings, serializer_settings, &logger);
|
||||
#ifdef WITH_HDF5
|
||||
} else if (output_extension == HDF) {
|
||||
geometry_settings.get<ifcopenshell::geometry::settings::IteratorOutput>().value = ifcopenshell::geometry::settings::NATIVE;
|
||||
serializer = boost::make_shared<HdfSerializer>(IfcUtil::path::to_utf8(output_temp_filename), geometry_settings, serializer_settings, false, logger);
|
||||
serializer = boost::make_shared<HdfSerializer>(IfcUtil::path::to_utf8(output_temp_filename), geometry_settings, serializer_settings, false, &logger);
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
} else if (output_extension == TTL) {
|
||||
serializer = boost::make_shared<TtlWktSerializer>(IfcUtil::path::to_utf8(output_temp_filename), geometry_settings, serializer_settings, logger);
|
||||
serializer = boost::make_shared<TtlWktSerializer>(IfcUtil::path::to_utf8(output_temp_filename), geometry_settings, serializer_settings, &logger);
|
||||
} else {
|
||||
cerr_ << "[Error] Unknown output filename extension '" << output_extension << "'\n";
|
||||
write_log(!quiet);
|
||||
@@ -1011,7 +1011,7 @@ int main(int argc, char** argv) {
|
||||
if (!vmap.count("cache-file")) {
|
||||
cache_file = input_filename + CACHE + HDF;
|
||||
}
|
||||
cache.reset(new HdfSerializer(IfcUtil::path::to_utf8(cache_file), geometry_settings, serializer_settings, false, logger));
|
||||
cache.reset(new HdfSerializer(IfcUtil::path::to_utf8(cache_file), geometry_settings, serializer_settings, false, &logger));
|
||||
context_iterator->set_cache(cache.get());
|
||||
}
|
||||
#endif
|
||||
@@ -1290,7 +1290,7 @@ bool init_input_file(const std::string& filename, IfcParse::IfcFile*& ifc_file,
|
||||
|
||||
#ifdef WITH_IFCXML
|
||||
if (boost::ends_with(boost::to_lower_copy(filename), ".ifcxml")) {
|
||||
ifc_file = IfcParse::parse_ifcxml(filename, logger);
|
||||
ifc_file = IfcParse::parse_ifcxml(filename, &logger);
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
|
||||
@@ -25,9 +25,10 @@ import re
|
||||
from collections import defaultdict
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Literal, Union
|
||||
from typing import TYPE_CHECKING, Any, Literal, Union, cast
|
||||
|
||||
import ifcopenshell.util.selector
|
||||
from typing_extensions import assert_never
|
||||
|
||||
try:
|
||||
from openpyxl import Workbook
|
||||
@@ -100,8 +101,9 @@ class Parser:
|
||||
def parse(self, ifc_file: ifcopenshell.file, name=None):
|
||||
for category_name, category_config in self.config["categories"].items():
|
||||
for element in category_config["get_category_elements"](ifc_file):
|
||||
get_element_data: Union[GetElementDataCallBack, dict[str, Any]]
|
||||
get_element_data = category_config["get_element_data"]
|
||||
get_element_data = cast(
|
||||
Union[GetElementDataCallBack, dict[str, Any]], category_config["get_element_data"]
|
||||
)
|
||||
|
||||
if isinstance(get_element_data, dict):
|
||||
data = {}
|
||||
@@ -109,14 +111,18 @@ class Parser:
|
||||
data[key] = ifcopenshell.util.selector.get_element_value(element, query)
|
||||
elif isinstance(get_element_data, Callable):
|
||||
data = get_element_data(ifc_file, element) or {}
|
||||
else:
|
||||
assert_never(get_element_data)
|
||||
|
||||
get_custom_element_data = self.get_custom_element_data.get(category_name, lambda x, y: None)
|
||||
get_custom_element_data = self.get_custom_element_data.get(category_name, lambda *_: None)
|
||||
if isinstance(get_custom_element_data, dict):
|
||||
custom_data = {}
|
||||
for key, query in get_custom_element_data.items():
|
||||
custom_data[key] = ifcopenshell.util.selector.get_element_value(element, query)
|
||||
elif isinstance(get_custom_element_data, Callable):
|
||||
custom_data = get_custom_element_data(ifc_file, element) or {}
|
||||
else:
|
||||
assert_never(get_custom_element_data)
|
||||
|
||||
data.update(custom_data)
|
||||
|
||||
|
||||
@@ -271,6 +271,8 @@ def get_contact_data(ifc_file: ifcopenshell.file, element: ifcopenshell.entity_i
|
||||
pao = the_actor
|
||||
person = the_actor.ThePerson
|
||||
organization = the_actor.TheOrganization
|
||||
else:
|
||||
assert False, the_actor
|
||||
|
||||
email = get_email_from_pao(person, organization)
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ dependencies = [
|
||||
"openpyxl",
|
||||
"odfpy",
|
||||
"pandas",
|
||||
"typing-extensions",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
|
||||
@@ -371,6 +371,42 @@ namespace ifcopenshell {
|
||||
static constexpr double defaultvalue = -1.;
|
||||
};
|
||||
|
||||
struct SvgRidgeAngleMinDegrees : public SettingBase<SvgRidgeAngleMinDegrees, double> {
|
||||
static constexpr const char* const name = "svg-ridge-angle-min-degrees";
|
||||
static constexpr const char* const description = "SVG edge classification (issue #3668): minimum convex dihedral deviation from flat, in degrees, for a projection edge to be classified as 'sharp' rather than 'flush'.";
|
||||
static constexpr double defaultvalue = 45.;
|
||||
};
|
||||
|
||||
struct SvgValleyAngleMinDegrees : public SettingBase<SvgValleyAngleMinDegrees, double> {
|
||||
static constexpr const char* const name = "svg-valley-angle-min-degrees";
|
||||
static constexpr const char* const description = "SVG edge classification (issue #3668): minimum concave dihedral deviation from flat, in degrees, for a projection edge to be classified as 'crease' rather than 'flush'.";
|
||||
static constexpr double defaultvalue = 12.;
|
||||
};
|
||||
|
||||
struct SvgEmitFlushEdges : public SettingBase<SvgEmitFlushEdges, bool> {
|
||||
static constexpr const char* const name = "svg-emit-flush-edges";
|
||||
static constexpr const char* const description = "SVG edge classification (issue #3668): whether to emit 'flush' projection edges (dihedral deviation below both ridge/valley thresholds). Defaults to false, i.e. flush edges are omitted from the output.";
|
||||
static constexpr bool defaultvalue = false;
|
||||
};
|
||||
|
||||
struct SvgUseEdgeClassification : public SettingBase<SvgUseEdgeClassification, bool> {
|
||||
static constexpr const char* const name = "svg-use-edge-classification";
|
||||
static constexpr const char* const description = "SVG edge classification (issue #3668): enable the 5-class boundary/outline/sharp/crease/flush scheme. When false (the default), falls back to the original unclassified linework.";
|
||||
static constexpr bool defaultvalue = false;
|
||||
};
|
||||
|
||||
struct SvgRenderCreaseEdges : public SettingBase<SvgRenderCreaseEdges, bool> {
|
||||
static constexpr const char* const name = "svg-render-crease-edges";
|
||||
static constexpr const char* const description = "SVG edge classification (issue #3668): whether to emit 'crease' (concave) projection edges. Only relevant when svg-use-edge-classification is enabled.";
|
||||
static constexpr bool defaultvalue = true;
|
||||
};
|
||||
|
||||
struct SvgRenderSharpEdges : public SettingBase<SvgRenderSharpEdges, bool> {
|
||||
static constexpr const char* const name = "svg-render-sharp-edges";
|
||||
static constexpr const char* const description = "SVG edge classification (issue #3668): whether to emit 'sharp' (convex) projection edges. Only relevant when svg-use-edge-classification is enabled.";
|
||||
static constexpr bool defaultvalue = true;
|
||||
};
|
||||
|
||||
struct KeepBoundingBoxes : public SettingBase<KeepBoundingBoxes, bool> {
|
||||
static constexpr const char* const name = "keep-bounding-boxes";
|
||||
static constexpr const char* const description =
|
||||
@@ -653,7 +689,7 @@ namespace ifcopenshell {
|
||||
};
|
||||
|
||||
class Settings : public SettingsContainer<
|
||||
std::tuple<MesherLinearDeflection, MesherAngularDeflection, ReorientShells, LengthUnit, PlaneUnit, Precision, OutputDimensionality, LayersetFirst, DisableBooleanResult, NoWireIntersectionCheck, NoWireIntersectionTolerance, PrecisionFactor, DebugBooleanOperations, BooleanAttempt2d, SurfaceColour, WeldVertices, UseWorldCoords, UnifyShapes, UseMaterialNames, ConvertBackUnits, ContextIds, ContextTypes, ContextIdentifiers, IteratorOutput, DisableOpeningSubtractions, ApplyDefaultMaterials, DontEmitNormals, GenerateUvs, ApplyLayerSets, UseElementHierarchy, ValidateQuantities, EdgeArrows, BuildingLocalPlacement, SiteLocalPlacement, ForceSpaceTransparency, CircleSegments, CgalSmoothAngleDegrees, KeepBoundingBoxes, ComputeCurvature, FunctionStepType, FunctionStepParam, NoParallelMapping, PermissiveShapeReuse, ModelOffset, ModelRotation, TriangulationType, CgalEmitOriginalEdges, OcctNoCleanTriangulation, CacheShapes, DeferProcessingFirstElement, MaxOffset, MaxOffsetDeviation, ApplyOffset, MakeVolume>
|
||||
std::tuple<MesherLinearDeflection, MesherAngularDeflection, ReorientShells, LengthUnit, PlaneUnit, Precision, OutputDimensionality, LayersetFirst, DisableBooleanResult, NoWireIntersectionCheck, NoWireIntersectionTolerance, PrecisionFactor, DebugBooleanOperations, BooleanAttempt2d, SurfaceColour, WeldVertices, UseWorldCoords, UnifyShapes, UseMaterialNames, ConvertBackUnits, ContextIds, ContextTypes, ContextIdentifiers, IteratorOutput, DisableOpeningSubtractions, ApplyDefaultMaterials, DontEmitNormals, GenerateUvs, ApplyLayerSets, UseElementHierarchy, ValidateQuantities, EdgeArrows, BuildingLocalPlacement, SiteLocalPlacement, ForceSpaceTransparency, CircleSegments, CgalSmoothAngleDegrees, SvgRidgeAngleMinDegrees, SvgValleyAngleMinDegrees, SvgEmitFlushEdges, SvgUseEdgeClassification, SvgRenderCreaseEdges, SvgRenderSharpEdges, KeepBoundingBoxes, ComputeCurvature, FunctionStepType, FunctionStepParam, NoParallelMapping, PermissiveShapeReuse, ModelOffset, ModelRotation, TriangulationType, CgalEmitOriginalEdges, OcctNoCleanTriangulation, CacheShapes, DeferProcessingFirstElement, MaxOffset, MaxOffsetDeviation, ApplyOffset, MakeVolume>
|
||||
>
|
||||
{};
|
||||
}
|
||||
|
||||
@@ -48,6 +48,7 @@ bool IfcGeom::OpenCascadeKernel::convert_openings(const IfcUtil::IfcBaseEntity*
|
||||
bst.attempt_2d = settings_.get<settings::BooleanAttempt2d>().get();
|
||||
bst.debug = settings_.get<settings::DebugBooleanOperations>().get();
|
||||
bst.precision = settings_.get<settings::Precision>().get();
|
||||
bst.logger = &logger_;
|
||||
|
||||
std::vector< std::pair<double, TopoDS_Shape> > opening_vector;
|
||||
|
||||
@@ -118,7 +119,7 @@ bool IfcGeom::OpenCascadeKernel::convert_openings(const IfcUtil::IfcBaseEntity*
|
||||
|
||||
auto it3_shape = std::static_pointer_cast<OpenCascadeShape>(it3->Shape())->shape();
|
||||
if (it3_shape.IsNull()) {
|
||||
Logger::Root().Error("GEO", 187, "Null operand");
|
||||
logger_.Error("GEO", 187, "Null operand");
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -143,7 +144,7 @@ bool IfcGeom::OpenCascadeKernel::convert_openings(const IfcUtil::IfcBaseEntity*
|
||||
IfcGeom::util::create_solid_from_faces(list, entity_part, settings_.get<settings::Precision>().get(), true);
|
||||
is_manifold = util::is_manifold(entity_part);
|
||||
if (is_manifold) {
|
||||
Logger::Root().Warning("GEO", 188, "Successfully sewed non-manifold first operand");
|
||||
logger_.Warning("GEO", 188, "Successfully sewed non-manifold first operand");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,17 +162,17 @@ bool IfcGeom::OpenCascadeKernel::convert_openings(const IfcUtil::IfcBaseEntity*
|
||||
failure = "Empty result (no faces) for BOPAlgo_MakerVolume; original was " + std::to_string(IfcGeom::util::count(entity_part, TopAbs_FACE));
|
||||
} else {
|
||||
is_manifold = util::is_manifold(entity_part_2);
|
||||
Logger::Root().Warning("GEO", 189, std::string("Sucessfully detected exterior volume to non-manifold first operand; shape is now ") + (is_manifold ? std::string("manifold") : std::string("non-manifold")));
|
||||
logger_.Warning("GEO", 189, std::string("Sucessfully detected exterior volume to non-manifold first operand; shape is now ") + (is_manifold ? std::string("manifold") : std::string("non-manifold")));
|
||||
entity_part = entity_part_2;
|
||||
}
|
||||
} catch (const Standard_Failure& e) {
|
||||
failure.emplace(e.GetMessageString());
|
||||
}
|
||||
if (failure) {
|
||||
Logger::Root().Warning("GEO", 190, "MakeVolume failed: " + *failure, entity);
|
||||
logger_.Warning("GEO", 190, "MakeVolume failed: " + *failure, entity);
|
||||
}
|
||||
} else {
|
||||
Logger::Root().Warning("GEO", 191, "Non-manifold first operand, use --make-volume to try and make manifold");
|
||||
logger_.Warning("GEO", 191, "Non-manifold first operand, use --make-volume to try and make manifold");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,7 +215,7 @@ bool IfcGeom::OpenCascadeKernel::convert_openings(const IfcUtil::IfcBaseEntity*
|
||||
if (util::boolean_operation(bst, result, opening_list, BOPAlgo_CUT, intermediate_result)) {
|
||||
result = intermediate_result;
|
||||
} else {
|
||||
Logger::Root().Message(Logger::LOG_ERROR, "GEO", 192, "Opening subtraction failed for " + boost::lexical_cast<std::string>(std::distance(jt, it)) + " openings", entity);
|
||||
logger_.Message(Logger::LOG_ERROR, "GEO", 192, "Opening subtraction failed for " + boost::lexical_cast<std::string>(std::distance(jt, it)) + " openings", entity);
|
||||
}
|
||||
|
||||
jt = it;
|
||||
@@ -235,7 +236,7 @@ bool IfcGeom::OpenCascadeKernel::convert_openings(const IfcUtil::IfcBaseEntity*
|
||||
// where we keep the first operand as is (a compound of faces probably,
|
||||
// unless --orient-shells was activated in which case we're already lost).
|
||||
if (!is_manifold) {
|
||||
Logger::Root().Warning("GEO", 193, "Retrying boolean operation on individual faces");
|
||||
logger_.Warning("GEO", 193, "Retrying boolean operation on individual faces");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -118,14 +118,14 @@ bool OpenCascadeKernel::convert_impl(const taxonomy::boolean_result::ptr br, Con
|
||||
|
||||
const double first_operand_volume = util::shape_volume(a);
|
||||
if (first_operand_volume <= ALMOST_ZERO) {
|
||||
Logger::Root().Message(Logger::LOG_WARNING, "GEO", 119, "Empty solid for:", c->instance);
|
||||
logger_.Message(Logger::LOG_WARNING, "GEO", 119, "Empty solid for:", c->instance);
|
||||
}
|
||||
} else {
|
||||
|
||||
for (auto& r : cr) {
|
||||
auto S = std::static_pointer_cast<OpenCascadeShape>(r.Shape())->shape();
|
||||
if (S.IsNull()) {
|
||||
Logger::Root().Error("GEO", 120, "Null operand");
|
||||
logger_.Error("GEO", 120, "Null operand");
|
||||
continue;
|
||||
}
|
||||
gp_GTrsf trsf;
|
||||
@@ -140,7 +140,7 @@ bool OpenCascadeKernel::convert_impl(const taxonomy::boolean_result::ptr br, Con
|
||||
// #2665 we also set a precision-independent threshold, because in the boolean op routine
|
||||
// the working fuzziness might still be increased.
|
||||
if (d < tol * 20. || d < 0.00002) {
|
||||
Logger::Root().Message(Logger::LOG_WARNING, "GEO", 121, "Halfspace subtraction yields unchanged volume:", c->instance);
|
||||
logger_.Message(Logger::LOG_WARNING, "GEO", 121, "Halfspace subtraction yields unchanged volume:", c->instance);
|
||||
continue;
|
||||
} else {
|
||||
S = result;
|
||||
@@ -159,6 +159,7 @@ bool OpenCascadeKernel::convert_impl(const taxonomy::boolean_result::ptr br, Con
|
||||
bst.attempt_2d = settings_.get<settings::BooleanAttempt2d>().get();
|
||||
bst.debug = settings_.get<settings::DebugBooleanOperations>().get();
|
||||
bst.precision = settings_.get<settings::Precision>().get();
|
||||
bst.logger = &logger_;
|
||||
|
||||
TopoDS_Shape r;
|
||||
|
||||
|
||||
@@ -405,7 +405,7 @@ bool IfcGeom::util::is_extrusion(const gp_Vec & v, const TopoDS_Shape & s, TopoD
|
||||
return true;
|
||||
}
|
||||
|
||||
int IfcGeom::util::eliminate_narrow_operands(double prec, const NCollection_List<TopoDS_Shape>& bs, NCollection_List<TopoDS_Shape> & c) {
|
||||
int IfcGeom::util::eliminate_narrow_operands(double prec, const NCollection_List<TopoDS_Shape>& bs, NCollection_List<TopoDS_Shape> & c, Logger& logger) {
|
||||
int N = 0;
|
||||
NCollection_List<TopoDS_Shape>::Iterator it(bs);
|
||||
for (; it.More(); it.Next()) {
|
||||
@@ -418,7 +418,7 @@ int IfcGeom::util::eliminate_narrow_operands(double prec, const NCollection_List
|
||||
|
||||
bool is_narrow = min_dimension < prec;
|
||||
|
||||
Logger::Root().Notice("GEO", 122, "Min OBB dimension of operand = " + std::to_string(min_dimension));
|
||||
logger.Notice("GEO", 122, "Min OBB dimension of operand = " + std::to_string(min_dimension));
|
||||
|
||||
if (!is_narrow) {
|
||||
c.Append(it.Value());
|
||||
@@ -573,7 +573,7 @@ int IfcGeom::util::eliminate_touching_operands(double prec, const TopoDS_Shape &
|
||||
return N;
|
||||
}
|
||||
|
||||
bool IfcGeom::util::boolean_subtraction_2d_using_builder(const TopoDS_Shape & a_input, const NCollection_List<TopoDS_Shape> & b_input, TopoDS_Shape & result, double eps) {
|
||||
bool IfcGeom::util::boolean_subtraction_2d_using_builder(const TopoDS_Shape & a_input, const NCollection_List<TopoDS_Shape> & b_input, TopoDS_Shape & result, double eps, Logger& logger) {
|
||||
IfcGeom::impl::tree<int> edge_tree;
|
||||
|
||||
NCollection_List<TopoDS_Shape> ab_input = b_input;
|
||||
@@ -703,7 +703,7 @@ bool IfcGeom::util::boolean_subtraction_2d_using_builder(const TopoDS_Shape & a_
|
||||
if (u11 < U1 && U1 < u12 && u21 < U2 && U2 < u22) {
|
||||
// Edge curves belonging to different operands intersect, don't process
|
||||
// using builder.
|
||||
Logger::Root().Notice("GEO", 123, "Intersecting boundaries");
|
||||
logger.Notice("GEO", 123, "Intersecting boundaries");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -750,7 +750,7 @@ bool IfcGeom::util::boolean_subtraction_2d_using_builder(const TopoDS_Shape & a_
|
||||
// any effect and marked as redundant. Feeding it to the builder algo
|
||||
// will likely cause problems.
|
||||
redundant[std::distance(wires.begin(), it)] = true;
|
||||
Logger::Root().Notice("GEO", 124, "Subtraction operand outside of outer bound");
|
||||
logger.Notice("GEO", 124, "Subtraction operand outside of outer bound");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -790,7 +790,7 @@ bool IfcGeom::util::boolean_subtraction_2d_using_builder(const TopoDS_Shape & a_
|
||||
if (wire_clss[wire_index]->Perform(p2d) == TopAbs_IN) {
|
||||
// A wire is contained within another operand
|
||||
redundant[other_index] = true;
|
||||
Logger::Root().Notice("GEO", 125, "Subtraction operand contained in other");
|
||||
logger.Notice("GEO", 125, "Subtraction operand contained in other");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -848,7 +848,7 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
std::stringstream ss;
|
||||
ss << "bool-" << std::this_thread::get_id() << "-" << (operation_counter_++);
|
||||
debug_identifier = ss.str();
|
||||
Logger::Root().Notice("GEO", 126, "Boolean debug identifier: " + debug_identifier);
|
||||
settings.log().Notice("GEO", 126, "Boolean debug identifier: " + debug_identifier);
|
||||
}
|
||||
|
||||
if (fuzziness < 0.) {
|
||||
@@ -884,7 +884,7 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
|
||||
a = unify(a_input, fuzziness * 1000.);
|
||||
|
||||
Logger::Root().Message(
|
||||
settings.log().Message(
|
||||
Logger::LOG_DEBUG, "GEO", 127,
|
||||
"Simplified operand A from "s +
|
||||
std::to_string(count(a_input, TopAbs_FACE)) +
|
||||
@@ -896,7 +896,7 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
NCollection_List<TopoDS_Shape>::Iterator it(b_input);
|
||||
for (; it.More(); it.Next()) {
|
||||
b.Append(unify(it.Value(), fuzziness));
|
||||
Logger::Root().Message(
|
||||
settings.log().Message(
|
||||
Logger::LOG_DEBUG, "GEO", 128,
|
||||
"Simplified operand B from "s +
|
||||
std::to_string(count(it.Value(), TopAbs_FACE)) +
|
||||
@@ -924,7 +924,7 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
|
||||
auto N = bounding_box_overlap(fuzziness, a, b, b_tmp);
|
||||
if (N) {
|
||||
Logger::Root().Notice("GEO", 129, "Eliminated " + std::to_string(N) + " disjoint operands");
|
||||
settings.log().Notice("GEO", 129, "Eliminated " + std::to_string(N) + " disjoint operands");
|
||||
std::swap(b, b_tmp);
|
||||
}
|
||||
}
|
||||
@@ -935,7 +935,7 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
b_tmp.Clear();
|
||||
auto N = eliminate_touching_operands(fuzziness, a, b, b_tmp);
|
||||
if (N) {
|
||||
Logger::Root().Notice("GEO", 130, "Eliminated " + std::to_string(N) + " touching operands");
|
||||
settings.log().Notice("GEO", 130, "Eliminated " + std::to_string(N) + " touching operands");
|
||||
std::swap(b, b_tmp);
|
||||
}
|
||||
}
|
||||
@@ -944,9 +944,9 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
PERF("boolean subtraction: eliminate narrow");
|
||||
|
||||
b_tmp.Clear();
|
||||
auto N = eliminate_narrow_operands(fuzziness, b, b_tmp);
|
||||
auto N = eliminate_narrow_operands(fuzziness, b, b_tmp, settings.log());
|
||||
if (N) {
|
||||
Logger::Root().Notice("GEO", 131, "Eliminated " + std::to_string(N) + " narrow operands");
|
||||
settings.log().Notice("GEO", 131, "Eliminated " + std::to_string(N) + " narrow operands");
|
||||
std::swap(b, b_tmp);
|
||||
}
|
||||
}
|
||||
@@ -960,21 +960,21 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
}
|
||||
|
||||
if (b.Extent() == 0) {
|
||||
Logger::Root().Warning("GEO", 132, "No other operands remaining, using first operand");
|
||||
settings.log().Warning("GEO", 132, "No other operands remaining, using first operand");
|
||||
result = a;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!is_2d && Logger::LOG_NOTICE >= Logger::Root().Verbosity()) {
|
||||
if (!is_2d && Logger::LOG_NOTICE >= settings.log().Verbosity()) {
|
||||
PERF("preliminary manifoldness check");
|
||||
|
||||
if (!a.IsNull()) {
|
||||
Logger::Root().Notice("GEO", 133, "Operand A is " + (is_manifold(a) ? ""s : "non-"s) + "manifold");
|
||||
settings.log().Notice("GEO", 133, "Operand A is " + (is_manifold(a) ? ""s : "non-"s) + "manifold");
|
||||
}
|
||||
|
||||
NCollection_List<TopoDS_Shape>::Iterator it(b);
|
||||
for (int i = 0; it.More(); it.Next(), ++i) {
|
||||
Logger::Root().Notice("GEO", 134, "Operand B " + std::to_string(i) + " is " + (is_manifold(it.Value()) ? ""s : "non-"s) + "manifold");
|
||||
settings.log().Notice("GEO", 134, "Operand B " + std::to_string(i) + " is " + (is_manifold(it.Value()) ? ""s : "non-"s) + "manifold");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1014,7 +1014,7 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
|
||||
const double fuzz = (std::min)(min_length_orig / 3., fuzziness);
|
||||
|
||||
Logger::Root().Notice("GEO", 135, "Used fuzziness: " + std::to_string(fuzz));
|
||||
settings.log().Notice("GEO", 135, "Used fuzziness: " + std::to_string(fuzz));
|
||||
|
||||
const double new_fuzziness = fuzziness * 10.;
|
||||
const bool allow_retry = new_fuzziness - 1e-15 <= settings.precision * 10000. && new_fuzziness < min_length_orig;
|
||||
@@ -1048,7 +1048,7 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
}
|
||||
|
||||
if (is_extrusion_a) {
|
||||
Logger::Root().Notice("GEO", 136, "Operand A 1/1 is an extrusion");
|
||||
settings.log().Notice("GEO", 136, "Operand A 1/1 is an extrusion");
|
||||
|
||||
NCollection_List<TopoDS_Shape>::Iterator it(b);
|
||||
for (int nb = 1; it.More(); it.Next(), ++nb) {
|
||||
@@ -1064,10 +1064,10 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
}
|
||||
|
||||
if (is_extrusion_b) {
|
||||
Logger::Root().Notice("GEO", 137, "Operand B " + std::to_string(nb) + "/" + std::to_string(b.Extent()) + " is an extrusion");
|
||||
settings.log().Notice("GEO", 137, "Operand B " + std::to_string(nb) + "/" + std::to_string(b.Extent()) + " is an extrusion");
|
||||
|
||||
if (b_interval.first < a_interval.first + (fuzz * 100.) && b_interval.second > a_interval.second - (fuzz * 100.)) {
|
||||
Logger::Root().Notice("GEO", 138, "Operand B creates a through hole");
|
||||
settings.log().Notice("GEO", 138, "Operand B creates a through hole");
|
||||
|
||||
// Align b with a operand
|
||||
gp_Trsf trsf;
|
||||
@@ -1091,7 +1091,7 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
PERF("boolean operation: 2d builder");
|
||||
// First try using face builder
|
||||
|
||||
boolean_op_2d_success = boolean_subtraction_2d_using_builder(a_face, b_faces, face_result, fuzziness);
|
||||
boolean_op_2d_success = boolean_subtraction_2d_using_builder(a_face, b_faces, face_result, fuzziness, settings.log());
|
||||
}
|
||||
|
||||
if (!boolean_op_2d_success) {
|
||||
@@ -1107,23 +1107,23 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
BRepPrimAPI_MakePrism mp(face_result, gp_Vec(gp::DY()) * (a_interval.second - a_interval.first));
|
||||
if (mp.IsDone()) {
|
||||
if (b_remainder_3d.Extent()) {
|
||||
Logger::Root().Notice("GEO", 139, std::to_string(b_remainder_3d.Extent()) + " operands remaining to process in 3D");
|
||||
settings.log().Notice("GEO", 139, std::to_string(b_remainder_3d.Extent()) + " operands remaining to process in 3D");
|
||||
b = b_remainder_3d;
|
||||
s1s.Clear();
|
||||
s1s.Append(mp.Shape());
|
||||
} else {
|
||||
Logger::Root().Notice("GEO", 140, "Processed fully in 2D");
|
||||
settings.log().Notice("GEO", 140, "Processed fully in 2D");
|
||||
result = mp.Shape();
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
Logger::Root().Notice("GEO", 141, "Failed to extrude 2D boolean result. Retrying in 3D.");
|
||||
settings.log().Notice("GEO", 141, "Failed to extrude 2D boolean result. Retrying in 3D.");
|
||||
}
|
||||
} else {
|
||||
Logger::Root().Notice("GEO", 142, "Failed to perform 2D boolean operation. Retrying in 3D.");
|
||||
settings.log().Notice("GEO", 142, "Failed to perform 2D boolean operation. Retrying in 3D.");
|
||||
}
|
||||
} else {
|
||||
Logger::Root().Notice("GEO", 143, "No second operands can be processed as 2D inner bounds. Retrying in 3D.");
|
||||
settings.log().Notice("GEO", 143, "No second operands can be processed as 2D inner bounds. Retrying in 3D.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1145,7 +1145,7 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
}
|
||||
if (builder->IsDone()) {
|
||||
if (false && builder->DSFiller()->HasWarning(STANDARD_TYPE(BOPAlgo_AlertAcquiredSelfIntersection))) {
|
||||
Logger::Root().Notice("GEO", 144, "Builder reports self-intersection in output");
|
||||
settings.log().Notice("GEO", 144, "Builder reports self-intersection in output");
|
||||
success = false;
|
||||
|
||||
/*
|
||||
@@ -1159,7 +1159,7 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
}
|
||||
*/
|
||||
} else if(builder->DSFiller()->HasWarning(STANDARD_TYPE(BOPAlgo_AlertBadPositioning)) && !TopoDS_Iterator(*builder).More()) {
|
||||
Logger::Root().Notice("GEO", 145, "Builder reports bad positioning and result is empty");
|
||||
settings.log().Notice("GEO", 145, "Builder reports bad positioning and result is empty");
|
||||
success = false;
|
||||
} else {
|
||||
TopoDS_Shape r = *builder;
|
||||
@@ -1173,7 +1173,7 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
fix.Perform();
|
||||
r = fix.Shape();
|
||||
} catch (...) {
|
||||
Logger::Root().Error("GEO", 146, "Shape healing failed on boolean result");
|
||||
settings.log().Error("GEO", 146, "Shape healing failed on boolean result");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1184,7 +1184,7 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
success = ana.IsValid() != 0;
|
||||
|
||||
if (!success) {
|
||||
Logger::Root().Notice("GEO", 147, "Boolean operation yields invalid result");
|
||||
settings.log().Notice("GEO", 147, "Boolean operation yields invalid result");
|
||||
|
||||
std::stringstream str;
|
||||
bool any_emitted = false;
|
||||
@@ -1214,7 +1214,7 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
|
||||
dump(r);
|
||||
|
||||
Logger::Root().Notice("GEO", 148, str.str());
|
||||
settings.log().Notice("GEO", 148, str.str());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1334,7 +1334,7 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
|
||||
if (op == BOPAlgo_CUT && has_open_shells && all_faces_included_in_result && result_n_faces > first_op_n_faces) {
|
||||
success = false;
|
||||
Logger::Root().Notice("GEO", 149, "Boolean result discarded because subtractions results in only the addition of faces");
|
||||
settings.log().Notice("GEO", 149, "Boolean result discarded because subtractions results in only the addition of faces");
|
||||
} else {
|
||||
// when there are edges or vertex-edge distances close to the used fuzziness, the
|
||||
// output is not trusted and the operation is attempted with a higher fuzziness.
|
||||
@@ -1380,7 +1380,7 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
static const char* const reason_strings[] = { "edge length", "vertex-edge", "face-face" };
|
||||
std::stringstream str;
|
||||
str << "Boolean operation result failing " << reason_strings[reason] << " interference check, with fuzziness " << fuzziness << " with length " << v;
|
||||
Logger::Root().Notice("GEO", 150, str.str());
|
||||
settings.log().Notice("GEO", 150, str.str());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1389,7 +1389,7 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
}
|
||||
|
||||
} else {
|
||||
Logger::Root().Notice("GEO", 151, "Boolean operation yields non-manifold result");
|
||||
settings.log().Notice("GEO", 151, "Boolean operation yields non-manifold result");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1399,7 +1399,7 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
#if OCC_VERSION_HEX >= 0x70200
|
||||
|
||||
if (builder->HasError(STANDARD_TYPE(BOPAlgo_AlertBOPNotAllowed))) {
|
||||
Logger::Root().Error("GEO", 152, "Invalid operands. Using first operand");
|
||||
settings.log().Error("GEO", 152, "Invalid operands. Using first operand");
|
||||
result = a;
|
||||
success = true;
|
||||
}
|
||||
@@ -1412,14 +1412,14 @@ bool IfcGeom::util::boolean_operation(const boolean_settings& settings, const To
|
||||
#endif
|
||||
std::string str_str = str.str();
|
||||
if (str_str.size()) {
|
||||
Logger::Root().Notice("GEO", 153, str_str);
|
||||
settings.log().Notice("GEO", 153, str_str);
|
||||
}
|
||||
}
|
||||
if (!success) {
|
||||
if (allow_retry) {
|
||||
return boolean_operation(settings, a, b, op, result, new_fuzziness);
|
||||
} else {
|
||||
Logger::Root().Notice("GEO", 154, "No longer attempting boolean operation with higher fuzziness");
|
||||
settings.log().Notice("GEO", 154, "No longer attempting boolean operation with higher fuzziness");
|
||||
}
|
||||
}
|
||||
return success && !result.IsNull();
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
|
||||
#include <BOPAlgo_Operation.hxx>
|
||||
|
||||
#include "../../../ifcparse/IfcLogger.h"
|
||||
#include "../ifc_geomlibrary_api.h"
|
||||
|
||||
namespace IfcGeom {
|
||||
@@ -88,13 +89,19 @@ namespace IfcGeom {
|
||||
|
||||
int eliminate_touching_operands(double prec, const TopoDS_Shape& a, const NCollection_List<TopoDS_Shape>& bs, NCollection_List<TopoDS_Shape>& c);
|
||||
|
||||
int eliminate_narrow_operands(double prec, const NCollection_List<TopoDS_Shape>& bs, NCollection_List<TopoDS_Shape> & c);
|
||||
int eliminate_narrow_operands(double prec, const NCollection_List<TopoDS_Shape>& bs, NCollection_List<TopoDS_Shape> & c, Logger& logger = Logger::Root());
|
||||
|
||||
bool boolean_subtraction_2d_using_builder(const TopoDS_Shape& a_input, const NCollection_List<TopoDS_Shape>& b_input, TopoDS_Shape& result, double eps);
|
||||
bool boolean_subtraction_2d_using_builder(const TopoDS_Shape& a_input, const NCollection_List<TopoDS_Shape>& b_input, TopoDS_Shape& result, double eps, Logger& logger = Logger::Root());
|
||||
|
||||
struct boolean_settings {
|
||||
bool debug, attempt_2d;
|
||||
double precision;
|
||||
// Set by callers that carry a per-conversion Logger (e.g. kernels deriving
|
||||
// from AbstractKernel). Falls back to the global Logger::Root() singleton,
|
||||
// which IfcConvert never wires to its --log-file output, so messages logged
|
||||
// through that fallback are effectively silently dropped.
|
||||
Logger* logger = nullptr;
|
||||
Logger& log() const { return logger ? *logger : Logger::Root(); }
|
||||
};
|
||||
|
||||
bool boolean_operation(const boolean_settings& settings, const TopoDS_Shape&, const NCollection_List<TopoDS_Shape>&, BOPAlgo_Operation, TopoDS_Shape&, double fuzziness = -1.);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user