Compare commits

..
8 Commits
Author SHA1 Message Date
Clifford Yapp f21c45e755 Use bu_vls for VFONT paths
The VFONT loader used a 128-byte buffer when constructing the bundled
font path. Odd-pathname distcheck directories exceeded that limit in CI
environments, causing fblabel to reject the default font and all
dependent rtwizard tests to fail. Use a bu_vls path so the installed
font can be opened regardless of build prefix length, and release it on
all loader exits.
2026-09-18 19:54:20 +00:00
Clifford Yapp 52c83ac3a1 Implement some OpenVDB based repair functionality and flood filling 2026-09-18 19:32:32 +00:00
Clifford Yapp 14051845a3 facetize: add source-guided adaptive SPSR
Fixed-size point dumps make Poisson reconstruction unreliable as a
last-resort facetization method.  They can miss thin partitions while
oversampling surfaces that are already well resolved, and an arbitrary
point count does not show whether source characterization is complete.

Seed reconstruction with stabilized Crofton samples.  Retain paired
entry and exit normals, partition thickness, and ray identities so thin
geometry contributes explicit local information instead of unrelated
points.

Add a bounded adaptive libbg driver around the existing upstream
Poisson solver.  Each solve reports residual, density, normal, and
surface-variation hints to a caller callback.  Facetize responds with
exact source rays and validates partitions, endpoints, chord length,
area, volume, and closed-manifold topology before accepting a result.

Bound refinement by time, point, pass, and convergence limits.  Relax
only chord and thin-partition thresholds when the source BoT is already
known to be non-manifold.  Deprecate the fixed-array API, remove the
intermediate point-sampling path, adapt pnts callers, and add focused
coverage.  The vendored SPSR implementation remains unchanged.

Use configured method priority for perturbation variants so an MDC-only
run never invokes NMG.  Report finalization progress and retry counts
while the fallback hierarchy is evaluated.
2026-09-18 16:14:16 +00:00
Clifford Yapp d6fa937212 libanalyze: replace marching cubes with adaptive MDC
The legacy marching-cubes polygonizer sampled a uniform grid and could
miss thin or high-aspect features, merge undersampled tunnels, and emit
surfaces whose shared-edge winding was inconsistent.  Increasing the
global resolution made those failures prohibitively expensive rather
than addressing their local causes.

Add a ray-driven manifold dual contouring API built on an adaptive
octree.  Cache exact signs and Hermite edge crossings from librt
partitions, place feature-preserving vertices with bounded QEF solves,
and refine locally for thin walls, multiple crossings, interior
surfaces, and ambiguous topology.  Build faces from shared crossings
with deterministic winding and require closed manifold output.

Back analyze_polygonize with the new implementation, expose MDC as a
facetize method, and remove the obsolete polygonizer code, licensing,
continuation sampler, and CM default.  Keep NMG available when polygon
preservation is more important and it can successfully process the
input.

Document the Ju, Schaefer, and Warren algorithmic basis and the
bottom-up Euler-characteristic escalation path.  Add coverage for thin
walls, tunnels, overlapping CSG, toroidal cases, winding, resource
limits, and the compatibility polygonalize entry point.
2026-09-18 16:14:16 +00:00
Clifford Yapp 37aee260c1 facetize: retire the legacy pipeline and harden region results
The compatibility implementation duplicated command behavior and
retained unreliable paths that had been superseded by the planned
worker pipeline.  Keeping both implementations made option handling and
failure behavior needlessly difficult to reason about.

Remove the old facetize sources and MGED registration so all command
modes use the maintained orchestrator.  Preserve implicitly selected
region roots in the output database and keep region retries scoped to
validated perturbation inputs.

Tighten source and result validation, reject empty preparation results,
and suppress expected import or preparation diagnostics only inside a
scoped log hook.  Keep routine details out of the terminal summary and
write complete detail logs when concise reporting is not possible.

Extend regression and validation coverage for implicit roots, tolerated
failures, and malformed or unsupported inputs.
2026-09-18 16:14:16 +00:00
Clifford Yapp 56d64428ae facetize: separate orchestration and isolate NMG evaluation
The command implementation mixed option handling, mode selection,
database setup, scheduling, and result publication.  NMG Boolean work
also ran in the parent process, allowing known NMG failures to terminate
the overall conversion.

Introduce an explicit planning and orchestration layer so each command
mode follows one visible execution path.  Replace positional worker
arguments with typed request and result messages that are validated
before they can alter the working database.

Move NMG Boolean evaluation into the supervised subprocess framework.
Transfer trees and BoTs through the existing transaction protocol,
report failures without killing the parent, and reject primitives that
do not provide the required tessellation callback.

Update facetize regression and worker-protocol coverage for the new
boundaries and failure semantics.
2026-09-18 16:14:16 +00:00
Clifford Yapp 0f6db7016d facetize: add supervised parallel primitive workers
Primitive tessellation previously paid process and database setup
costs per object and left the parent with limited visibility into work
that timed out or died.  Large models consequently spent substantial
time outside the tessellation algorithms themselves.

Add long-lived supervised workers and a bounded scheduler for
independent objects.  Divide CPUs between worker processes and each
worker internal parallelism, reuse opened databases, and retain cache
state across requests.

Make result publication transactional.  A WRITE_STARTED acknowledgment
closes the READY and PROCEED race, while the parent detects timeouts and
abnormal exits, restarts workers, and records only completed object
results.  Reuse temporary result databases without leaking state between
requests.

Add process and database-transfer helpers together with worker,
recovery, and validation tests.  Document the parallel job control and
its resource behavior.
2026-09-18 16:14:15 +00:00
Clifford Yapp cbffc1171b libbu: support resource-aware worker processes
Large subprocess pools need to divide machine resources without allowing
each worker internal parallelism to consume every CPU.  Add a
process-local limit to bu_avail_cpus() and bu_parallel(), with atomic
updates and coverage for applying and removing the limit.

Make BU_MEM_AVAIL count FreeBSD reclaimable inactive and cache queues
in addition to immediately free pages.  This prevents idle systems from
appearing memory-starved to resource-aware algorithms and adds native
sysctl checks for the reported values.

Rename the private process.h to process_private.h.  This prevents the
source header from shadowing the MSVC CRT header used by std::thread,
which otherwise leaves _beginthreadex undeclared.
2026-09-18 16:14:15 +00:00
115 changed files with 13540 additions and 11401 deletions
-246
View File
@@ -1,246 +0,0 @@
Annotation and view-object rendering notes
==========================================
Scope
-----
BRL-CAD has two related, but deliberately distinct, ways to represent visual
markup:
* An annotation is an ID_ANNOT database primitive. It is persistent model
content with enough semantic and presentation information to be reproduced
outside the application that created it.
* A view object is application-owned scene state. It is useful for interactive
construction and manipulation, but is intentionally not backed by a database
object.
They share portions of the interactive display infrastructure, but they do not
currently have interchangeable ownership, lifetime, or rendering semantics.
Annotation capabilities
-----------------------
An rt_annot_internal stores a model-space anchor, a set of 2D vertices, and
either a model plane basis or screen-space placement. Its segment types cover
lines, circular arcs, NURBS, Beziers, text, and filled polygons. Segment style
records include a semantic role, line pattern and width, RGBA color, font or
symbol, text scaling, and decorative flags.
The libged annotate command can create styled text, leaders, linear/angular/
radius/diameter/ordinate dimensions, and bounding-box autodim groups. It can
regenerate derived annotations from saved attributes and associate them with
source model objects without making them part of those objects' CSG trees.
Annotations therefore have the properties needed for persistent markup:
* database naming, paths, transforms, and instances;
* survival across save/reopen and transfer to another application;
* semantic segment roles and per-segment presentation data;
* model-space and view-dependent screen-space placement; and
* high-level generation metadata and source-object associations.
An annotation is informational coverage, not a CSG solid. The raytracing
implementation preserves that distinction. It prepares annotation coverage
from active database paths and composites it on primary samples after ordinary
geometry has established color and depth. Model-space annotation coverage is
occluded by nearer solid geometry. Screen-space annotation coverage uses the
render view and image dimensions. Annotations do not acquire artificial
volume, alter model bounds, cast shadows, or participate in reflection and
refraction rays.
Visible coverage is returned in back-to-front layers. Model-space layers are
ordered by ray distance, followed by view-space layers ordered by projected
anchor depth; segment draw order breaks ties within an annotation. This lets
the image renderers apply source-over alpha consistently while retaining the
single-frontmost-hit query for compatibility. NIRT continues to report one
frontmost segment per model-space annotation rather than exposing these
presentation layers as solid partitions.
Color follows normal database tree state. An annotation segment with an
explicit RGBA style wins; otherwise it inherits the resolved combination-path
color; otherwise it is white. The legacy region-ID color table is not applied
to annotation display or coverage, since annotations are informational leaves
rather than regions.
Prepared coverage uses the existing libbg RTree implementation. A 3D RTree
culls model-space annotation instances and a 2D local RTree culls segments
inside every annotation. Screen-space instance extents cannot be placed in a
static world-space index because they change with the view, so those instances
remain in a compact list while still using their local segment RTree. This
avoids a new spatial data structure and keeps prepared scenes immutable and
safe for concurrent sample queries.
The rt, ART, and ADRT/ISST integrations follow this overlay model. ERT invokes
rt with the database, displayed database paths, and view, so database-backed
annotations can follow that route as well. ERT does not currently serialize
or pass application-owned view objects to its subprocess.
NIRT keeps annotation diagnostics opt-in. `useannot 1` enables model-space
annotation intersections, and the `fmt a` action reports them. Default NIRT
output is unchanged. Screen-space annotations are deliberately omitted
because a NIRT ray does not define an image size, pixel footprint, or complete
model-to-view mapping.
View-object capabilities
------------------------
The core representation is bv_scene_obj. A view set owns shared view objects,
and a particular bview can also own local objects. Independent views force
local ownership. bv_obj_put recycles objects when their application lifetime
ends; the objects are not written to the .g database.
The `view obj` command exposes the principal markup types:
* Lines are model-coordinate polylines represented by vlists. Generic scene
rendering can add arrowheads to segment ends.
* Labels have a model anchor and optional model-space target/leader. Their text
is projected and drawn as screen-facing HUD text. If the command omits Z,
screen X/Y coordinates are projected onto the current view plane at creation
time.
* Polygons include general polygons, circles, ellipses, rectangles, and
squares. Creation and editing operate on a saved view plane with a view-Z
offset. Selection, movement, open/close, area, overlap, and 2D boolean
operations are supported. A "fill" is currently a set of hatch lines, not
an opaque surface. Polygons can be explicitly imported from or exported to
persistent sketch primitives.
Scene objects also provide object color, transparency, pixel line width, dash
style, and arrow dimensions. Not all of these properties have a uniform
command interface for every object type.
There are other visual layers that should not be conflated with these objects.
Legacy gv_tcl data/sdata arrows, axes, lines, labels, and polygons have a
separate representation. Faceplate/HUD elements are screen UI. Database
objects temporarily cloned for editing are also transient, but retain database
primitive semantics and live in the database-object scene containers.
Comparison
----------
Both annotations and view objects eventually produce display-manager pixels,
often through bv_scene_obj and vlists. That common final path does not make
their source representations equivalent.
Annotations are the canonical choice when markup must be saved, named in a
database, instanced, shared, raytraced from a .g file, or understood by another
program. View objects are the right choice for application/session state that
must be created and manipulated without changing the database.
Some view objects have a direct annotation analogue, but conversion is not
lossless without type-aware logic:
* A view polyline maps naturally to line segments, including arrowhead style.
* A polygon outline and its hatch lines can map to annotation coverage, but the
existing view "fill" must not silently become an opaque filled polygon.
* A label is hybrid. Its target and leader are model-space geometry while its
glyphs remain screen-facing at a projected model anchor.
* Arbitrary vlist extraction is insufficient because display-matrix commands,
point and line sizes, child objects, glyph behavior, and semantic roles are
otherwise lost or ambiguous.
View-object line width and annotation line width also need an explicit unit
policy. View-object widths are display pixels. Screen-space annotation widths
are view-dependent coverage widths. A model-space annotation's line_width is
used as a scale on the automatically selected model-space stroke width. In
other words, removing a separate raytracer "stroke-width" setting does not
remove width control: the annotation's existing line_width/`--line-width`
style remains the single user-facing control. The renderer interprets it in
the appropriate coordinate system rather than exposing a second competing
knob.
Recommended transient rendering design
--------------------------------------
Do not make librt or the raytracers depend on bv_scene_obj, libbv application
containers, or libged. Do not manufacture tubes, TGCs, meshes, or geometry
just in front of the view plane. Artificial geometry would affect bounds,
depth, shadows, and secondary rays, and would make antialiasing and perspective
behavior depend on a fabricated distance from the eye.
If transient view objects need to appear in raytraced output, use an explicit
application-to-renderer snapshot boundary:
1. The GED/application layer snapshots selected live view objects when a render
is launched. This is the only layer that owns their lifetime and semantics.
2. A type-aware adapter in libged or libbv translates supported objects into a
renderer-neutral overlay/coverage description. It should reuse annotation
coverage preparation through an in-memory annotation-instance interface,
rather than duplicate line, glyph, and arrow intersection algorithms.
3. The snapshot travels with the exact view state: model-to-view transform,
perspective, image width and height, and sampling convention. In-process
renderers can receive it directly; subprocess rt/ERT needs an explicit
serialized side channel.
4. Raytracers composite this coverage only on primary image samples, after
geometry color and depth are known. It remains outside CSG, model bounds,
shadows, reflections, and refractions.
5. Initial support should be deliberately finite: polyline strokes and
arrowheads, label glyphs and leaders, polygon outlines, and polygon hatches.
Faceplate elements and legacy gv_tcl overlays should be separately specified
opt-in layers rather than being included accidentally.
6. Snapshot records should preserve object name and type, RGBA, visibility,
local/shared ownership, presentation units, and source identity. Unsupported
object types should produce a deliberate diagnostic or documented omission.
Application-side compositing of the interactive display-manager layer over an
ERT framebuffer is a viable smaller feature if only ERT screen captures need
view objects. It would closely reproduce the interactive view, but it would
not make the objects available to standalone rt, ART, or ISST output and should
not be presented as the general renderer solution.
Conversion between the two systems should remain explicit. Automatically
turning view objects into database annotations would violate their deliberately
transient contract. A user command to promote selected view markup to a
persistent annotation would be reasonable; polygon-to-sketch export is an
existing precedent. Conversely, a view-object editor may be used as a front
end for constructing an annotation, provided the persistence action is clear.
Maintenance findings before implementing the adapter
----------------------------------------------------
Several representation issues should be corrected before type-driven snapshot
conversion is relied upon:
* Container-selection flags (BV_DB_OBJS, BV_VIEW_OBJS, BV_LOCAL_OBJS, and
BV_CHILD_OBJS) reuse numeric bits also used for semantic s_type_flags
(BV_DBOBJ_BASED, BV_VIEWONLY, BV_LINES, and others). bv_obj_create currently
assigns its type argument to s_type_flags. A local view object consequently
acquires BV_LINES incidentally, while the line command does not explicitly
tag lines. The namespaces should be separated and every object explicitly
typed.
* Lines, labels, and polygons should have unambiguous type tags and per-type
lifecycle/extraction callbacks. Snapshot conversion must inspect typed data,
not infer semantics from a rendered vlist.
* Label construction should initialize every bv_label field deliberately,
including size, line_flag, anchor, arrow, and target. Current construction
does not establish all of those values on every path.
* The status of legacy gv_tcl overlay data should be decided explicitly:
migrate it, support it through a separate adapter, or document its exclusion.
* Screen-space annotation display and raytrace units need a parity test. The
legacy display-matrix vlist path and the ray coverage path currently express
screen offsets through different mechanisms; their apparent agreement must
be verified rather than assumed.
* Per-segment annotation colors exceed the legacy interactive vlist object's
single-color model. Uniform annotate-command colors work today, but true
multicolor interactive parity may require split scene objects or a richer
display representation.
Tests for a future adapter should cover shared and local ownership, cleanup,
label anchors and leaders, polygon holes/hatches/view-Z, perspective, pixel
width, model-space occlusion, screen-space overlay, and serialization across
the ERT subprocess boundary.
Conclusion
----------
Persistent annotations and transient view objects should continue to coexist.
The annotation coverage scene is the correct renderer-side abstraction for
both saved annotations and a future snapshot of transient markup. The
application should perform the semantic conversion and transfer a view-complete
snapshot; the renderer should treat it as primary-ray coverage, never as
invented scene geometry.
+1 -53
View File
@@ -132,10 +132,6 @@ Command to set the backout flag. With no option, prints the current value. When
Sets the _useair_ member of the __rt_i__ structure to the integer _n_. If _n_ is 0, then *nirt* ignores any air in the geometry. If this command is invoked with no arguments, *nirt* prints the current value of _useair_. Default is 0.
*useannot [* _n_*]*::
Enables (_n_=1) or disables (_n_=0) diagnostic annotation intersections. When enabled, *nirt* evaluates all model-space annotations below the active database paths and invokes the *a* output action for each crossing. Screen-space annotations are not evaluated because an individual NIRT ray does not supply a pixel size or model-to-view transform. If this command is invoked with no arguments, *nirt* prints the current value. Default is 0.
*overlap_claims [* _n_*]*::
Specifies how to handle multiple regions' claims to segments of a ray. If _n_ is 0 or "resolve", then all overlaps are resolved in favor of a single region and any other claimants are ignored. If _n_ is 2 or "rebuild_all", then all overlaps are rebuilt, so any overlapping regions along the ray create individual (geometrically intersecting) partitions. If _n_ is 3 or "retain", then all overlaps are retained. In this case, the resulting partitions are always geometrically disjoint, each one is owned by a single region according to the current overlap resolution strategy, but every claimant is recorded. If _n_ is 1 or "rebuild_fastgen", then *nirt* takes on _FASTGEN_ behavior, so overlaps of plate-mode primitives are rebuilt, but other overlaps are retained. This command is useful with the __claimant_count__, __claimant_list__, and __claimant_listn__ output items. Default is "resolve".
@@ -201,11 +197,7 @@ Quits *nirt*.
[[output_statements]]
== OUTPUT STATEMENTS
*nirt* allows the user a high degree of control, via the _fmt_ command, over what information gets printed out for each ray and in what format. There are eight types of output statements, each of which is executed under appropriate circumstances. The types and their use are:
*a*::
Annotation. Executed once for each model-space annotation crossing when *useannot* is enabled. Crossings are reported in ray-distance order after the ordinary solid shotline output. The default format is empty.
*nirt* allows the user a high degree of control, via the _fmt_ command, over what information gets printed out for each ray and in what format. There are six types of output statements, each of which is executed under appropriate circumstances. The types and their use are:
*r*::
@@ -286,41 +278,6 @@ azimuth of view (i.e., of ray direction).
elevation of view (i.e., of ray direction).
Annotation Information
*annot_path*::
full database path of the annotation primitive.
*annot_segment*::
zero-based annotation segment index.
*annot_role*::
semantic role of the annotation segment, such as `text`, `leader`, `dimension`, or `arrowhead`.
*annot_x*::
_x_ coordinate of the annotation hit point.
*annot_y*::
_y_ coordinate of the annotation hit point.
*annot_z*::
_z_ coordinate of the annotation hit point.
*annot_d*::
_d_ grid-plane coordinate of the annotation hit point.
*annot_visible*::
1 if no non-air solid surface is closer to the ray origin, otherwise 0. Occluded annotation crossings are still reported so they can be inspected during debugging.
Partition Information
@@ -564,15 +521,6 @@ nirt -A material_id -A los_density model.g all
Each region the ray passes through is reported together with its _material_id_ and _los_density_ attribute values via the *attributes* output item, which is useful for vulnerability and mass-properties analyses.
====
.Reporting annotation crossings for debugging
====
[source,bash]
----
nirt -s -e 'useannot 1;fmt a "%s %d (%g %g %g) visible=%d\n" annot_path annot_segment annot_x annot_y annot_z annot_visible;s' model.g component dimensions
----
This opt-in format reports every model-space annotation crossing and whether it is in front of the first solid surface. Ordinary NIRT output is unchanged unless *useannot* is enabled and an *a* format is supplied.
====
[[hints]]
== HINTS
+3 -2
View File
@@ -18,7 +18,8 @@ Link with *-lanalyze*.
The public interface is organized across the headers included by
_analyze.h_, including _analyze/diff.h_, _analyze/density.h_,
_analyze/grid.h_, _analyze/heal.h_, _analyze/info.h_, _analyze/pnts.h_,
_analyze/polygonize.h_, _analyze/nirt.h_, _analyze/voxelize.h_, and
_analyze/contour.h_, _analyze/polygonize.h_, _analyze/nirt.h_,
_analyze/voxelize.h_, and
_analyze/worker.h_.
== DESCRIPTION
@@ -32,7 +33,7 @@ to gather the information they need.
Facilities provided by the library include model differencing, material
density and mass property analysis, ray-based gridding and sampling,
geometry healing, model information queries, point-cloud generation and
processing, polygonization and voxelization of geometry, and the
processing, manifold dual contouring and voxelization of geometry, and the
interactive ray-tracing engine used by the *nirt*(1) command. A parallel
worker interface supports distributing analysis work across multiple
threads.
+2 -32
View File
@@ -25,7 +25,7 @@ where the "char" argument is replaced by a single character identifying the cate
[[nirt_format_categories]]
== Output Categories
NIRT offers eight categories of output reporting:
NIRT offers seven categories of output reporting:
[cols="3*"]
[%noheader]
@@ -33,9 +33,6 @@ NIRT offers eight categories of output reporting:
|*Category Name*
|*Char*
|*Description*
|*Annotation*
|*a*
|Output for each model-space annotation crossing when annotation reporting is enabled with *useannot 1*. The default annotation format is empty.
|*Ray*
|*r*
|Report of ray information. The formatting associated with r will print once per ray, regardless of whether a region is encountered.
@@ -65,7 +62,7 @@ NIRT offers eight categories of output reporting:
[[nirt_format_str]]
== Format Strings
NIRT's format specifications are a subset of those found in printf implementations. The d, i, f, e, E, g, G, and s types are supported, as well as width and precision specifiers.
NIRT's format specifications are a subset of those found in printf implementations. Specifically, the d, i, and f types are supported, as well as width and precision specifiers.
[[nirt_format_keys]]
@@ -103,33 +100,6 @@ Unlike the full C/C++ printf, NIRT accepts only pre-defined string keys that ide
Footnote and Miss categories have no particular keys unique to them, although they (like all categories) can use the Ray keys if desired. Partition, Overlap, and Gap, on the other hand, have keys that are unique to their contexts and valid only within those contexts:
.Annotation Variables
[cols="2*"]
[%noheader]
|===
|annot_path
|Full database path of the annotation primitive.
|annot_segment
|Zero-based annotation segment index.
|annot_role
|Semantic role of the annotation segment, such as `text`, `leader`, `dimension`, or `arrowhead`.
|annot_x
|x coordinate of the annotation hit point.
|annot_y
|y coordinate of the annotation hit point.
|annot_z
|z coordinate of the annotation hit point.
|annot_d
|d grid-plane coordinate of the annotation hit point.
|annot_visible
|1 if no non-air solid surface is closer to the ray origin, otherwise 0.
|===
Annotation reporting is diagnostic and opt-in. It returns all model-space
annotation crossings in ray-distance order, including occluded crossings.
Screen-space annotations are not reported because a NIRT shot does not define
the pixel dimensions and model-to-view transform needed to evaluate them.
.Partition Variables
[cols="2*"]
[%noheader]
+9 -8
View File
@@ -40,11 +40,12 @@ Coordinates and explicit sizes use the database's current modeling units.
Creation commands draw the new annotation immediately. Use *--no-draw* to
create it without changing the display. Names must not already exist.
Ray-traced annotations are zero-thickness informational coverage rather than
solid regions. Model-space annotations are depth-tested against ordinary
geometry. Screen-space annotations are generated for the current camera and
composited in the foreground; they do not participate in shadows, reflections,
line-of-sight thickness, or Boolean evaluation.
Model-space annotations also participate in raytracing. Librt expands their
strokes and filled areas into transient mesh geometry during preparation; the
generated geometry is not written to the database. It uses the normal region
material and color resolved from the containing combination tree. Screen-space
annotations remain display-only because primitive preparation has no render
view or image dimensions with which to place them.
The supported dimensions follow the general presentation conventions of ISO
129-1. Lettering defaults to OSIFont, an ISO 3098-style technical font shipped
@@ -208,9 +209,9 @@ Set the persistent annotation color using integer red, green, and blue values
from 0 through 255.
*--line-width width*::
Set the presentation line width. Display and screen-space ray rendering use
the value as a pixel width. Model-space ray rendering uses it to scale the
automatic stroke width derived from the annotation's text height or extent.
Set the display line width. For a model-space raytrace, this value scales the
physical stroke width inferred from the annotation's text height or overall
extent.
*--line-style style*::
Set semantic line-pattern metadata to *continuous*, *dashed*, *dotted*,
+24 -16
View File
@@ -10,7 +10,7 @@ facetize - Creates __new_object__ using __old_object__ as a guide, creating an e
[source]
----
facetize [-h] [-v] [-q] [-n] [-r] [-s suffix] [-p prefix] [--in-place] [--max-time #] [--max-pnts #] [--resume] [--methods m1,m2,...] [--method-opts METHOD opt1=val opt2=val...] [--no-empty] [--log-file filename] [--nmg-booleval] [--disable-fixup] [--perturb] [--no-perturb] [--perturb-sa-tol #] [--perturb-vol-tol #] [--tolerate-failures] [-B -t threshold] {old_object new_object}
facetize [-h] [-v] [-q] [-n] [-r] [-j jobs] [-s suffix] [-p prefix] [--in-place] [--max-time #] [--max-pnts #] [--resume] [--methods m1,m2,...] [--method-opts METHOD opt1=val opt2=val...] [--no-empty] [--log-file filename] [--nmg-booleval] [--disable-fixup] [--perturb] [--no-perturb] [--perturb-sa-tol #] [--perturb-vol-tol #] [--tolerate-failures] [-B -t threshold] {old_object new_object}
----
@@ -45,6 +45,8 @@ By default, the Manifold BoT path can make use of a coplanarity-avoidance pertur
When the perturbation step is active, per-region *facetize* validates the initial Boolean output against the original CSG geometry using a Crofton stochastic raytrace. The default tolerance thresholds that trigger a perturb retry are 10% for both surface area and volume; these can be adjusted with *--perturb-sa-tol* and *--perturb-vol-tol*. At the end of a per-region facetization run *facetize* prints a concise validation summary listing how many regions passed, triggered a perturb retry, or encountered one of the following noteworthy conditions:
_Unbounded halfspace (validation unavailable)_: Crofton surface-area and volume comparisons require a finite sampling domain. A standalone halfspace, or another CSG result without finite bounds, is therefore not sampled and is counted as having validation unavailable. A bounded object intersected with or subtracted by a halfspace can still be validated because its finite operand supplies the sampling bounds.
_Sub-mm / few-hit bypass (accepted with note)_: When the Crofton sampler finds only a very small number of ray-surface intersections (below an internal threshold of 50 crossings), the sampling noise alone would exceed 14% relative error, making any SA comparison meaningless. Geometry in this category is typically sub-millimetre in cross-section (e.g., a TGC with a radius under 0.2 mm) but the stochastic sampler has confirmed that some geometry is present. The BoT conversion is accepted and the region is counted separately in the summary. Users should verify that such extreme geometry reflects actual modeling intent rather than an accidental near-degenerate primitive.
_Zero-hit replacement_: When the Crofton sampler fires rays but records zero intersections with the CSG geometry while the corresponding BoT is non-empty, *facetize* concludes that the Boolean evaluation most likely produces empty geometry (for example, a subtractor that fully engulfs the base object). In this case the non-empty BoT is discarded and replaced with an empty BoT to match the expected raytrace behavior. If this replacement appears unexpected for a given region, the *lint* command can be used to inspect the result.
@@ -61,13 +63,21 @@ Different tolerance settings will create finer or coarser meshes. See the *tol*
Primitive tessellation is performed in a child process against a private working copy of the database in the BRL-CAD cache. The original database is not modified as individual primitive meshes are generated. Only after the conversion succeeds are the requested results transferred from the working database. This separation also permits an interrupted conversion to retain its intermediate state for use with *--resume*.
The parent command sends primitive names to a persistent tessellation process one at a time. The child reports a result for each name, so a timeout, conversion failure, or child-process crash that occurs before a database write can be associated directly with the affected primitive. The child is restarted when necessary and processing continues with the next name; the parent does not subdivide and retry the whole group to discover which object failed. Unless output is suppressed with *--quiet*, long tessellation batches also report their current object and completed-object count at approximately five-second intervals.
The parent command sends primitive names to a small pool of persistent tessellation processes. Each child reports a result for every name, so a timeout, conversion failure, or child-process crash can be associated directly with the affected primitive. A child is restarted when necessary and processing continues with the next name; the parent does not subdivide and retry the whole group to discover which object failed. Unless output is suppressed with *--quiet*, long tessellation batches also report their completed-object count and active-worker state at approximately five-second intervals.
Database updates use a separate write handshake. After preparing a mesh in memory, the child announces that it is ready to write and reports the approximate mesh size, then waits. The parent acknowledges that it is waiting for the write before the child may update the working database. The child explicitly reports when the update is complete. Consequently, the normal per-object tessellation limit, including *--max-time* and method-specific limits, applies to mesh preparation and does not interrupt an acknowledged database write.
By default, *facetize* uses at most two worker processes and only enables the second when both CPU and memory information indicate it is safe. It reserves the larger of one GiB or one quarter of total physical memory for the rest of the system. Starting another job also requires at least 512 MiB beyond that reserve, or the largest worker resident-memory measurement seen so far if that is greater. If the platform cannot report the required memory information, *facetize* falls back to one worker. The available CPU count is divided among worker processes and is also imposed as the thread limit inside each worker, preventing nested algorithms from independently using all CPUs. *--jobs* changes the maximum process count; it does not bypass the memory admission checks.
Per-region BoT conversion uses this worker policy for both independent CSG validation and initial Manifold Boolean evaluation. When more than one worker is available, persistent validation processes each open their own read-only handle to the original database and compute Crofton surface-area and volume references for different regions. Persistent Boolean processes then evaluate different region trees using independent read-only handles to one shared snapshot of the tessellated working database. That snapshot also serves as the rollback checkpoint, so increasing *--jobs* does not create additional full database copies. This process isolation avoids sharing mutable raytrace preparation or database state between concurrent evaluations. Each result remains associated with the requested region name. The parent commits completed BoTs through one writer and continues to perform hierarchy changes, validation decisions, and any perturb retries serially. A one-worker run retains the established in-process order and avoids the snapshot phase.
Validation and Boolean workers report their completed-region count and active-worker state approximately every five seconds. When *--max-time* is specified, it also bounds each parallel CSG reference or Boolean request; a timed-out process is terminated, and the failure is associated with that region. Failure or timeout of supplementary CSG validation does not cause unrelated regions to be retried.
Database updates use a separate write handshake. After preparing a mesh in memory, a child announces that it is ready to write and reports the approximate mesh size and its current resident memory, then waits. The parent grants write permission, the child acknowledges when it is starting the write, and the child explicitly reports when the update is complete. Consequently, the normal per-object tessellation limit, including *--max-time* and method-specific limits, applies to mesh preparation and does not interrupt an acknowledged write.
With multiple workers, primitive tessellation children write to small staging databases rather than modifying the shared working database. Region Boolean children read one immutable cache-local snapshot while completed results are committed to the working database. The snapshot doubles as the recovery checkpoint and is opened independently by each worker; it is not duplicated per worker. For very large files, snapshot preparation reports the amount copied and elapsed time at five-second intervals. A region result is first completed in memory and enters the write handshake only when it is ready to replace the prior staged result. After a child reports a completed staging write, the parent submits that result to a single persistent writer process. The writer announces that it is ready, waits for the parent's permission, acknowledges that it is starting the write, transfers the result through one persistent working-database handle, and reports completion. This permits tessellation and initial region Boolean evaluation to proceed in parallel without concurrent database allocation updates or repeated full directory scans, while allowing the parent to supervise the canonical database write itself. With one worker, the established direct path avoids the extra staging I/O and database snapshot.
Before the first primitive conversion, the parent measures write throughput on the same cache filesystem as the working database. It writes a temporary file in 1 MiB chunks until approximately one second has elapsed or 128 MiB has been written, then removes the file immediately. Successful mesh writes of at least 1 MiB subsequently refine this profile. For each database update, the parent allows ten times the projected write time, with a minimum of five seconds and a maximum of five minutes. This measured allowance protects legitimate long writes on slow storage while still detecting a genuinely stalled update.
If a child fails before write permission is granted, the working database is known to be unchanged and no rollback is needed. A failure, crash, or write-deadline expiration after permission is granted but before completion is ambiguous: the working database may contain a partial update. In that case *facetize* restores its cache-local checkpoint and replays only the primitive conversions already known to have succeeded. The original database remains untouched during this recovery.
If a child fails before acknowledging that its write has started, the working database is known to be unchanged and no rollback is needed. In parallel mode, a failure during a child write affects only that worker's disposable staging database, so the failed object is reported and the worker can be restarted without replaying unrelated objects. A serial child failure during a direct write, or a writer-process failure after acknowledging write start, is ambiguous because the working database may contain a partial update. In those cases *facetize* restores its cache-local checkpoint and replays only the conversions not already tied to a specific failure. The original database remains untouched during this recovery.
[[facetize_options]]
@@ -94,6 +104,10 @@ Instructs *facetize* to produce NMG solids rather than BoT solids.
Rather than converting all specified inputs to one top level object, walk specified trees and individually convert regions to facetized objects. This mode is useful when wanting to display models in shaded mode while preserving color and region ID properties. If no regions are present a normal conversion is performed instead.
*-j, --jobs #*::
Set the maximum number of facetize worker processes. A value of 1 forces serial processing. The default value of 0 selects a conservative automatic limit based on available CPUs and memory. Memory checks may delay or reduce parallel work even when a larger value is requested. In per-region BoT mode the same limit controls parallel CSG reference sampling and initial Manifold Boolean evaluation.
*-s, --suffix*::
User specified suffix to use avoiding naming conflicts (naming conflict avoidance is needed when creating objects in *-r* mode.)
@@ -119,7 +133,7 @@ Resume an incomplete facetization process (will utilize cached data from a previ
*--methods*::
Accepts a comma separated list of one or more facetization methods to use. The default is to try all algorithms available as needed, but if a user knows they want to try a specific methodology they can call it out using this option.
Accepts a comma separated list of one or more facetization methods to use. The default tries NMG tessellation first, Manifold Dual Contouring (MDC) second, and SPSR as a final fallback. Other listed methods may be selected explicitly if a user wants to try a specific methodology.
*--method-opts*::
@@ -231,21 +245,15 @@ mged>**facetize --tolerate-failures large_model large_model.partial.bot**
====
.Increase Decimation in CM Mode
.Refine a Manifold Dual Contouring conversion
[example]
====
mged>**facetize --methods CM --method-opts feature_size=0.06 d_feature_size=2.0 ellipse.r ell.bot**
This selects MDC directly and requests a finer cell size with a larger ray
budget than the default:
The default settings on this object in CM mode will produce a little over 8000 faces in the final bot, but the addition of the *d_feature_size* option with a >1.5 value has dramatically reduced the count to 104.
mged>**facetize --methods MDC --method-opts "MDC feature_size=0.1 max_rays=400000" ellipse.r ell.bot**
====
.Decrease Decimation in CM Mode
[example]
====
mged>**facetize --methods CM --method-opts feature_size=0.06 d_feature_size=0.01 ellipse.r ell.bot**
If the intent is preserve a more detailed mesh, reducing *decimation-feature-size* will keep more of the original triangles - in the above example, almost 250 thousand of the original 6.9 million faces were retained. NOTE: use lower values here cautiously, as extremely large meshes can be very difficult for many tools to deal with.
Smaller feature sizes increase mesh detail, ray count, memory use, and runtime.
====
+13 -16
View File
@@ -679,23 +679,21 @@ Convert CSG geometry to a 3D voxel grid by:
fill fraction
* Level-of-detail parameter controls sub-voxel sampling
==== 7.5 Implicit Surface Polygonizer (Marching Cubes / Tetrahedral)
==== 7.5 Manifold Dual Contouring
An implicit surface polygonizer (Bloomenthal tetrahedral marching) for
converting any inside/outside function to a triangle mesh.
`contour.cpp` evaluates CSG geometry directly with `librt` and constructs
closed, oriented triangle meshes:
`polygonizer.c` (based on Jules Bloomenthal’s "`An Implicit Surface
Polygonizer,`" Graphics Gems IV, 1994) converts any implicit function
(inside/outside test) to a triangle mesh:
* Maintains a hash table of evaluated lattice corners and edges
* Expanding front: starts at a seed point and spreads outward, testing
adjacent cube faces
* Each transitive cube is optionally decomposed into 6 tetrahedra for
sub-cube accuracy
* Edge-surface crossing is found by bisection (`converge`) then the
vertex normal is estimated from finite differences
* Used in `libanalyze` for converting CSG regions to faceted form
* Recursively refines an implicit octree using cached axis-aligned rays along
node box edges and interior quarter- and center-lines
* Reuses complete ray partitions at the conforming finest grid and retains
evaluated boundary points with analytic surface normals
* Resolves ambiguous faces consistently and permits multiple vertices in a
cell to preserve local topology
* Places vertices with bounded quadratic-error minimization
* Validates the resulting indexed mesh before returning it
* Backs the legacy `analyze_polygonize` interface without retaining the old
seed-driven marching-tetrahedra implementation
==== 7.6 Geometry Differencing (raydiff)
@@ -1712,7 +1710,6 @@ import
runtime
* *MT19937*: Mersenne Twister PRNG
* *pbrt-v3* (derived): HLBVH construction algorithm
* *Bloomenthal polygonizer*: implicit surface polygonization
* *Screened Poisson Reconstruction* (Michael Kazhdan): surface
reconstruction from point clouds
* *Ball Pivoting Algorithm*: surface reconstruction
-1
View File
@@ -55,7 +55,6 @@ brlcad_manage_files(pbrt.txt ${DOC_DIR}/legal/embedded TRIGGER
brlcad_manage_files(picohash.txt ${DOC_DIR}/legal/embedded TRIGGER gist)
brlcad_manage_files(pixcii.txt ${DOC_DIR}/legal/embedded TRIGGER libicv)
brlcad_manage_files(point_in_polygon.txt ${DOC_DIR}/legal/embedded TRIGGER libbg)
brlcad_manage_files(polygonizer.txt ${DOC_DIR}/legal/embedded TRIGGER libanalyze)
brlcad_manage_files(predicates.txt ${DOC_DIR}/legal/embedded TRIGGER libbg)
brlcad_manage_files(profont.txt ${DOC_DIR}/legal/embedded TRIGGER libbu)
brlcad_manage_files(pstdint.txt ${DOC_DIR}/legal/embedded TRIGGER libbu)
-9
View File
@@ -1,9 +0,0 @@
https://www.bloomenthal.com/JBloom/code/polygonizer.c
Authored by Jules Bloomenthal, Xerox PARC.
Copyright (c) Xerox Corporation, 1991. All rights reserved.
Permission is granted to reproduce, use and distribute this code for
any and all purposes, provided that this notice appears in all copies.
file:/src/libanalyze/polygonizer.c
+1
View File
@@ -31,6 +31,7 @@
#include "common.h"
#include "analyze/defines.h"
#include "analyze/contour.h"
#include "analyze/debug.h"
#include "analyze/diff.h"
#include "analyze/density.h"
+1
View File
@@ -1,5 +1,6 @@
set(
analyze_headers
contour.h
debug.h
defines.h
density.h
+118
View File
@@ -0,0 +1,118 @@
/* C O N T O U R . H
* BRL-CAD
*
* Copyright (c) 2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library 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 this file; see the file named COPYING for more
* information.
*/
/** @addtogroup libanalyze
* @{ */
/** @file analyze/contour.h
*
* Ray-driven manifold dual contouring of evaluated BRL-CAD geometry.
*/
#ifndef ANALYZE_CONTOUR_H
#define ANALYZE_CONTOUR_H
#include "common.h"
#include <stddef.h>
#include "vmath.h"
#include "analyze/defines.h"
__BEGIN_DECLS
#define ANALYZE_MDC_DEFAULT_MAX_RAYS 0
#define ANALYZE_MDC_DEFAULT_MINIMUM_FREE_MEM 150000000
#define ANALYZE_MDC_DEFAULT_MIN_DEPTH 2
#define ANALYZE_MDC_DEFAULT_MAX_DEPTH 10
#define ANALYZE_MDC_MAX_DEPTH 20
#define ANALYZE_MDC_DEFAULT_MAX_TIME 600
struct db_i;
/** Resource and accuracy controls for analyze_mdc(). */
struct analyze_mdc_params {
/** Requested maximum finest-cell edge length. Zero selects an
* implementation default based on the model bounds. */
fastf_t feature_size;
/** Optional user ceiling for the automatically derived ray budget.
* Zero applies only geometry, depth, time, and memory limits. */
size_t max_rays;
/** Abort before available memory drops below this many bytes. */
size_t minimum_free_mem;
/** Minimum and maximum power-of-two grid depths. */
int min_depth;
int max_depth;
/** Maximum wall-clock processing time in seconds. Zero is unlimited. */
int max_time;
/** Emit progress diagnostics when non-zero. */
int verbosity;
};
#define ANALYZE_MDC_PARAMS_DEFAULT { \
0.0, \
ANALYZE_MDC_DEFAULT_MAX_RAYS, \
ANALYZE_MDC_DEFAULT_MINIMUM_FREE_MEM, \
ANALYZE_MDC_DEFAULT_MIN_DEPTH, \
ANALYZE_MDC_DEFAULT_MAX_DEPTH, \
ANALYZE_MDC_DEFAULT_MAX_TIME, \
0 \
}
enum analyze_mdc_status {
ANALYZE_MDC_OK = 0,
ANALYZE_MDC_INVALID_INPUT = 1,
ANALYZE_MDC_PREP_FAILED = 2,
ANALYZE_MDC_NO_SURFACE = 3,
ANALYZE_MDC_RAY_LIMIT = 4,
ANALYZE_MDC_TIMEOUT = 5,
ANALYZE_MDC_MEMORY_LIMIT = 6,
ANALYZE_MDC_AMBIGUOUS = 7,
ANALYZE_MDC_NOT_MANIFOLD = 8
};
/**
* Evaluate @p object with librt and construct an indexed triangle mesh.
*
* On success, the caller owns @p faces and @p vertices and must release them
* with bu_free(). Failure leaves all outputs empty.
*/
ANALYZE_EXPORT extern enum analyze_mdc_status
analyze_mdc(int **faces, size_t *num_faces, point_t **vertices,
size_t *num_vertices, const char *object, struct db_i *dbip,
const struct analyze_mdc_params *params);
__END_DECLS
#endif /* ANALYZE_CONTOUR_H */
/** @} */
/*
* Local Variables:
* mode: C
* tab-width: 8
* indent-tabs-mode: t
* c-file-style: "stroustrup"
* End:
* ex: shiftwidth=4 tabstop=8
*/
+22 -2
View File
@@ -43,9 +43,29 @@ struct analyze_polygonize_params {
size_t minimum_free_mem;
int verbosity;
};
#define ANALYZE_POLYGONIZE_PARAMS_DEFAULT { 0, 0, 30, 150000000, 0 }
#define ANALYZE_POLYGONIZE_DEFAULT_MAX_CYCLE_TIME 30
#define ANALYZE_POLYGONIZE_DEFAULT_MINIMUM_FREE_MEM 150000000
#define ANALYZE_POLYGONIZE_PARAMS_DEFAULT { 0, 0, \
ANALYZE_POLYGONIZE_DEFAULT_MAX_CYCLE_TIME, \
ANALYZE_POLYGONIZE_DEFAULT_MINIMUM_FREE_MEM, 0 }
/**
* Legacy polygonization interface, implemented by analyze_mdc().
*
* @p size is the requested maximum cell edge length. @p p_s is retained for
* source and binary compatibility but is no longer used as a starting seed.
* The caller owns successful output arrays and must release them with
* bu_free(). Failure leaves all outputs empty.
*
* @return 0 on success
* @return -1 on invalid input or polygonization failure
* @return 2 when a time limit is reached
* @return 3 when the minimum-free-memory limit is reached
*/
ANALYZE_EXPORT extern int
analyze_polygonize(int **faces, int *num_faces, point_t **vertices, int *num_vertices, fastf_t size, point_t p_s, const char *obj, struct db_i *dbip, struct analyze_polygonize_params *p);
analyze_polygonize(int **faces, int *num_faces, point_t **vertices,
int *num_vertices, fastf_t size, point_t p_s, const char *obj,
struct db_i *dbip, struct analyze_polygonize_params *p);
__END_DECLS
+127 -5
View File
@@ -67,6 +67,7 @@
#define BG_SPSR_H
#include "common.h"
#include <stdint.h>
#include "vmath.h"
#include "bg/defines.h"
@@ -109,7 +110,7 @@ struct bg_3d_spsr_opts {
#define BG_3D_SPSR_BOUNDARY_DIRICHLET 3
#define BG_3D_SPSR_DEFAULT_DEGREE 1 /* DEFAULT_FEM_DEGREE */
#define BG_3D_SPSR_DEFAULT_DEPTH 11
#define BG_3D_SPSR_DEFAULT_DEPTH 8
#define BG_3D_SPSR_DEFAULT_KERNELDEPTH 0
#define BG_3D_SPSR_DEFAULT_ITERATIONS 0
#define BG_3D_SPSR_DEFAULT_FULL_DEPTH 0
@@ -117,13 +118,13 @@ struct bg_3d_spsr_opts {
#define BG_3D_SPSR_DEFAULT_BASEVCYCLES 0
#define BG_3D_SPSR_DEFAULT_MAX_MEM 0
#define BG_3D_SPSR_DEFAULT_THREADS 0
#define BG_3D_SPSR_DEFAULT_SAMPLES_PER_NODE 1.1
#define BG_3D_SPSR_DEFAULT_SCALE 1.0
#define BG_3D_SPSR_DEFAULT_SAMPLES_PER_NODE 1.5
#define BG_3D_SPSR_DEFAULT_SCALE 1.1
#define BG_3D_SPSR_DEFAULT_WIDTH 0.0
#define BG_3D_SPSR_DEFAULT_CONFIDENCE 0.0
#define BG_3D_SPSR_DEFAULT_CONFIDENCE_BIAS 0.0
#define BG_3D_SPSR_DEFAULT_CGSOLVER_ACCURACY 1.0e-3
#define BG_3D_SPSR_DEFAULT_POINT_WEIGHT 8.0 /* DefaultPointWeightMultiplier * Degree */
#define BG_3D_SPSR_DEFAULT_POINT_WEIGHT 2.0
#define BG_3D_SPSR_DEFAULT_NONMANIFOLD 0
#define BG_3D_SPSR_DEFAULT_LINEARFIT 0
#define BG_3D_SPSR_DEFAULT_EXACT 1
@@ -167,10 +168,131 @@ struct bg_3d_spsr_opts {
* @return 0 if successful, else error
*
*/
BG_EXPORT int bg_3d_spsr(int **faces, int *num_faces, point_t **vertices, int *num_vertices,
DEPRECATED BG_EXPORT int bg_3d_spsr(int **faces, int *num_faces, point_t **vertices, int *num_vertices,
const point_t *input_points_3d, const vect_t *input_normals_3d,
int num_input_pnts, struct bg_3d_spsr_opts *opts);
/** Reasons the SPSR solver may request additional source samples. */
#define BG_3D_SPSR_REFINE_RESIDUAL 0x01u
#define BG_3D_SPSR_REFINE_NORMAL 0x02u
#define BG_3D_SPSR_REFINE_DENSITY 0x04u
#define BG_3D_SPSR_REFINE_SURFACE_VARIATION 0x08u
/** Adaptive SPSR termination states. */
#define BG_3D_SPSR_COMPLETE 0
#define BG_3D_SPSR_CALLBACK_STOP 1
#define BG_3D_SPSR_POINT_LIMIT 2
#define BG_3D_SPSR_TIME_LIMIT 3
#define BG_3D_SPSR_NO_NEW_SAMPLES 4
#define BG_3D_SPSR_SOLVER_ERROR 5
/**
* One oriented source sample. A positive @p thickness records the length of
* the solid ray partition that supplied the sample. Non-zero equal pair IDs
* identify the entry and exit samples of the same partition.
*/
struct bg_3d_spsr_sample {
point_t point;
vect_t normal;
fastf_t thickness;
uint64_t pair_id;
};
/** A spatial location at which the solver would benefit from more samples. */
struct bg_3d_spsr_refinement_hint {
point_t point;
vect_t normal;
fastf_t error;
unsigned int reasons;
};
/** Source-to-candidate measurements supplied by an adaptive callback. */
struct bg_3d_spsr_validation {
size_t ray_count;
size_t source_hit_rays;
size_t partition_mismatch_rays;
size_t thin_partition_count;
size_t thin_partition_mismatches;
fastf_t endpoint_error_p95;
fastf_t endpoint_error_p99;
fastf_t chord_error_fraction;
fastf_t surface_area_error_fraction;
fastf_t volume_error_fraction;
int passed;
};
/** Information passed to an adaptive source-sampling callback. */
struct bg_3d_spsr_refinement_request {
size_t pass;
fastf_t target_feature_size;
double remaining_time;
const point_t *vertices;
size_t vertex_count;
const int *faces;
size_t face_count;
const struct bg_3d_spsr_refinement_hint *hints;
size_t hint_count;
};
/**
* Callback response. Sample storage remains owned by the callback and need
* only remain valid until the callback returns; libbg copies it immediately.
*/
struct bg_3d_spsr_refinement_response {
const struct bg_3d_spsr_sample *samples;
size_t sample_count;
struct bg_3d_spsr_validation validation;
/** Non-zero asks the adaptive driver to stop after this candidate. */
int stop_refinement;
};
typedef int (*bg_3d_spsr_refinement_func_t)(
struct bg_3d_spsr_refinement_response *response,
const struct bg_3d_spsr_refinement_request *request,
void *client_data);
/** Options controlling a bounded adaptive SPSR reconstruction. */
struct bg_3d_spsr_adaptive_opts {
struct bg_3d_spsr_opts solver;
size_t max_refinement_passes;
size_t max_points;
fastf_t target_feature_size;
double max_time;
};
/** Last-resort solve budget; callbacks may stop earlier when progress stalls. */
#define BG_3D_SPSR_DEFAULT_REFINEMENT_PASSES 8
#define BG_3D_SPSR_ADAPTIVE_OPTS_DEFAULT { \
BG_3D_SPSR_OPTS_DEFAULT, \
BG_3D_SPSR_DEFAULT_REFINEMENT_PASSES, \
0, \
0.0, \
0.0 }
/** Summary of an adaptive SPSR attempt. */
struct bg_3d_spsr_report {
size_t solve_count;
size_t initial_sample_count;
size_t final_sample_count;
size_t requested_sample_count;
size_t accepted_sample_count;
double elapsed_time;
int termination;
struct bg_3d_spsr_validation validation;
};
/**
* Reconstruct a surface and, when requested, obtain targeted additional
* samples from @p refine. A callback is required when refinement passes are
* enabled. The final candidate must be marked as passed by the callback.
*/
BG_EXPORT int bg_3d_spsr_adaptive(int **faces, int *num_faces,
point_t **vertices, int *num_vertices,
const struct bg_3d_spsr_sample *input_samples, size_t sample_count,
const struct bg_3d_spsr_adaptive_opts *opts,
bg_3d_spsr_refinement_func_t refine, void *client_data,
struct bg_3d_spsr_report *report);
__END_DECLS
#endif /* BG_SPSR_H */
+14 -1
View File
@@ -103,10 +103,23 @@ BU_EXPORT extern void bu_nice_set(int newnice);
/**
* Return the maximum number of physical CPUs that are considered to
* be available to this process now.
* be available to this process now, subject to any process-local limit set by
* bu_avail_cpus_set().
*/
BU_EXPORT extern size_t bu_avail_cpus(void);
/**
* Limit the CPU count reported by bu_avail_cpus() and honored by subsequent
* bu_parallel() calls in this process. A value of zero removes the limit.
* Call this before starting worker threads; changing the limit does not resize
* work that is already running.
*
* This is useful when several independent processes share one machine and
* each process contains code that selects its own parallelism with
* bu_avail_cpus().
*/
BU_EXPORT extern void bu_avail_cpus_set(size_t ncpu);
/**
* Create parallel threads of execution.
-85
View File
@@ -29,19 +29,10 @@
#include "bu/list.h"
#include "bu/vls.h"
#include "bn/tol.h"
#include "rt/geom.h"
#include "rt/defines.h"
__BEGIN_DECLS
struct db_i;
struct xray;
#define RT_ANNOT_SCREEN_DPI 96.0
#define RT_ANNOT_MILLIMETERS_PER_INCH 25.4
#define RT_ANNOT_SCREEN_PIXELS_PER_MM \
(RT_ANNOT_SCREEN_DPI / RT_ANNOT_MILLIMETERS_PER_INCH)
RT_EXPORT extern struct rt_annot_internal *rt_copy_annot(const struct rt_annot_internal *annot_ip);
/** Validate annotation topology, model-space placement, and optional segment
@@ -49,82 +40,6 @@ RT_EXPORT extern struct rt_annot_internal *rt_copy_annot(const struct rt_annot_i
RT_EXPORT extern int rt_annot_validate(const struct rt_annot_internal *annot_ip,
struct bu_vls *messages);
/** Opaque, immutable collection of prepared annotation instances. */
struct rt_annot_scene;
/** Camera state needed to evaluate view-space annotations. Pixel sample
* coordinates use a lower-left origin. */
struct rt_annot_view {
mat_t model2view;
size_t width;
size_t height;
fastf_t perspective;
};
/** A zero-thickness annotation coverage event. path is owned by the scene. */
struct rt_annot_hit {
const char *path;
size_t segment;
uint32_t role;
point_t point;
fastf_t distance;
unsigned char color[4];
int screen_space;
int visible;
};
/** Prepare annotations referenced by the supplied top-level database paths.
* Boolean operations are intentionally ignored: annotations are
* informational leaves, not solids. */
RT_EXPORT extern struct rt_annot_scene *rt_annot_scene_create(
struct db_i *dbip, int path_count, const char * const *paths,
const struct bg_tess_tol *ttol, const struct bn_tol *tol);
RT_EXPORT extern void rt_annot_scene_destroy(struct rt_annot_scene *scene);
RT_EXPORT extern size_t rt_annot_scene_count(const struct rt_annot_scene *scene);
/** Return model-space bounds for prepared annotations. Screen-space geometry
* contributes its model-space anchor because its extent is view-dependent. */
RT_EXPORT extern int rt_annot_scene_bounds(const struct rt_annot_scene *scene,
point_t minimum, point_t maximum);
/** Return the top visible coverage event for a primary sample. */
RT_EXPORT extern int rt_annot_scene_query(const struct rt_annot_scene *scene,
const struct rt_annot_view *view, const struct xray *ray,
fastf_t sample_x, fastf_t sample_y, fastf_t scene_distance,
struct rt_annot_hit *hit);
/** Return all visible primary-sample coverage events in back-to-front order.
* Model-space events precede screen-space events. When hits is NULL or
* capacity is zero, only the required result count is returned. */
RT_EXPORT extern size_t rt_annot_scene_query_layers(
const struct rt_annot_scene *scene, const struct rt_annot_view *view,
const struct xray *ray, fastf_t sample_x, fastf_t sample_y,
fastf_t scene_distance, struct rt_annot_hit *hits, size_t capacity);
/** Return all model-space coverage events, sorted by ray distance. When hits
* is NULL or capacity is zero, only the required result count is returned. */
RT_EXPORT extern size_t rt_annot_scene_query_model(const struct rt_annot_scene *scene,
const struct xray *ray, fastf_t scene_distance,
struct rt_annot_hit *hits, size_t capacity);
/** Alpha-composite a coverage result over a linear RGB sample. */
RT_EXPORT extern void rt_annot_hit_blend(fastf_t color[3],
const struct rt_annot_hit *hit);
/** Alpha-composite all visible primary-sample coverage over color. If
* front_hit is non-NULL, it receives the frontmost event. */
RT_EXPORT extern int rt_annot_scene_composite(const struct rt_annot_scene *scene,
const struct rt_annot_view *view, const struct xray *ray,
fastf_t sample_x, fastf_t sample_y, fastf_t scene_distance,
fastf_t color[3], struct rt_annot_hit *front_hit);
/** Generate one annotation segment in annotation-local XY coordinates. This
* is shared by plotting and the coverage preparer to keep curve and font
* expansion identical. */
RT_EXPORT extern int rt_annot_segment_vlist(struct bu_list *vlfree,
struct bu_list *vhead, const struct bg_tess_tol *ttol,
const struct rt_annot_internal *annot_ip, size_t segment);
__END_DECLS
/** @} */
+8 -1
View File
@@ -234,10 +234,17 @@ struct rt_bot_repair_info {
fastf_t max_hole_area_percent;
int strict;
/* OpenVDB repair controls. When force_openvdb is zero OpenVDB is used
* only as a fallback after the conventional repair path fails. */
int force_openvdb;
fastf_t openvdb_voxel_size;
// Info about generated output
int output_nonmanifold;
int output_lint_fail;
fastf_t output_volume;
int openvdb_available;
int used_openvdb;
unsigned int output_data_loss;
};
@@ -252,7 +259,7 @@ struct rt_bot_repair_info {
* tests. This isn't always desirable - sometimes manifold is enough even if
* the mesh is not otherwise well behaved - so it is an user settable param.
*/
#define RT_BOT_REPAIR_INFO_INIT {0.0, 5.0, 1, 0, 0, 0.0, 0};
#define RT_BOT_REPAIR_INFO_INIT {0.0, 5.0, 1, 0, 0.0, 0, 0, 0.0, 0, 0, 0};
/* Function to attempt repairing a non-manifold BoT. Returns 1 if ibot was
* already manifold (obot will contain NULL), 0 if a manifold BoT was created
-1
View File
@@ -1,6 +1,5 @@
# default.nrt
# Description: default - Standard NIRT Reporting Format
fmt a ""
fmt r "Origin (x y z) = (%.8f %.8f %.8f) (h v d) = (%.4f %.4f %.4f)\nDirection (x y z) = (%.8f %.8f %.8f) (az el) = (%.8f %.8f)\n" x_orig y_orig z_orig h v d_orig x_dir y_dir z_dir a e
fmt h " Region Name Entry (x y z) LOS Obliq_in Attrib\n"
fmt p "%-20s (%9.4f %9.4f %9.4f) %8.4f %8.4f%s\n" reg_name x_in y_in z_in los obliq_in attributes
+259 -16
View File
@@ -68,6 +68,13 @@
* ("/tc6_reg.c/sub6.s#sub"), so the lookup missed and no variant was
* applied, leaving the phantom face. After the fix the plan is built
* from region roots so keys match and the phantom face is eliminated.
*
* TC7 - NMG Boolean isolation and output modes: verifies that an interrupted
* worker cannot commit output, then exercises BoT, NMG, region, and
* in-place output paths.
*
* TC8 - implicit solid roots survive the working-database close and remain
* valid members of the imported output hierarchy.
*/
#include "common.h"
@@ -78,7 +85,9 @@
#include <string>
#include "bu/app.h"
#include "bu/env.h"
#include "bu/file.h"
#include "bu/log.h"
#include "bu/malloc.h"
#include "bu/str.h"
#include "bu/vls.h"
@@ -142,6 +151,36 @@ write_comb2(struct rt_wdb *wdbp,
0, 0, 0, 0, 0, 0, 0);
}
static int
write_comb1(struct rt_wdb *wdbp, const char *comb_name, const char *member, int is_region)
{
struct bu_list head;
BU_LIST_INIT(&head);
mk_addmember(member, &head, NULL, WMOP_UNION);
return mk_comb(wdbp, comb_name, &head, is_region, NULL, NULL, NULL,
0, 0, 0, 0, 0, 0, 0);
}
static int
run_facetize_command(const char *gfile, int argc, const char **argv, int verbose)
{
struct ged *gedp = ged_open("db", gfile, 1);
if (!gedp) {
bu_log("[regress_facetize] ged_open(%s) failed\n", gfile);
return BRLCAD_ERROR;
}
int ret = ged_exec(gedp, argc, argv);
if (verbose || ret != BRLCAD_OK) {
const char *log = bu_vls_cstr(gedp->ged_result_str);
if (log && log[0])
bu_log("[facetize] %s\n", log);
}
ged_close(gedp);
return ret;
}
/**
* Open @a gfile with ged_open and run "facetize @a input @a output".
* Returns BRLCAD_OK on success, BRLCAD_ERROR otherwise.
@@ -149,23 +188,8 @@ write_comb2(struct rt_wdb *wdbp,
static int
run_facetize(const char *gfile, const char *input, const char *output, int verbose)
{
struct ged *gedp = ged_open("db", gfile, 1);
if (!gedp) {
bu_log("[regress_facetize] ged_open(%s) failed\n", gfile);
return BRLCAD_ERROR;
}
const char *av[4] = {"facetize", input, output, NULL};
int ret = ged_exec(gedp, 3, av);
if (verbose || ret != BRLCAD_OK) {
const char *log = bu_vls_cstr(gedp->ged_result_str);
if (log && log[0])
bu_log("[facetize] %s\n", log);
}
ged_close(gedp);
return ret;
return run_facetize_command(gfile, 3, av, verbose);
}
/**
@@ -212,6 +236,46 @@ bu_log("[regress_facetize] check_bot: '%s' type %d is not a BoT\n",
return ok;
}
static int
check_object_type(const char *gfile, const char *object_name, int expected_type)
{
struct db_i *dbip = db_open(gfile, DB_OPEN_READONLY);
if (!dbip || db_dirbuild(dbip) < 0) {
if (dbip)
db_close(dbip);
return BRLCAD_ERROR;
}
struct directory *dp = db_lookup(dbip, object_name, LOOKUP_QUIET);
if (!dp) {
bu_log("[regress_facetize] '%s' does not exist\n", object_name);
db_close(dbip);
return BRLCAD_ERROR;
}
struct rt_db_internal intern;
RT_DB_INTERNAL_INIT(&intern);
if (rt_db_get_internal(&intern, dp, dbip, NULL) < 0) {
db_close(dbip);
return BRLCAD_ERROR;
}
int ret = (intern.idb_minor_type == expected_type) ? BRLCAD_OK : BRLCAD_ERROR;
if (ret != BRLCAD_OK)
bu_log("[regress_facetize] '%s' type %d, expected %d\n",
object_name, intern.idb_minor_type, expected_type);
rt_db_free_internal(&intern);
db_close(dbip);
return ret;
}
static int
count_log_hook(void *data, void *UNUSED(message))
{
int *count = (int *)data;
(*count)++;
return 0;
}
/**
* Run rt_crofton_shoot on @a obj_name in @a gfile.
* Stores SA (mm2) and VOL (mm3) in *sa / *vol.
@@ -1120,6 +1184,183 @@ tc6_havoc_wind9_pattern(const char *tmpdir, int verbose)
return BRLCAD_OK;
}
static int
tc7_nmg_modes(const char *tmpdir, int verbose)
{
bu_log("[regress_facetize] TC7: NMG Boolean and output modes...\n");
struct bu_vls gpath = BU_VLS_INIT_ZERO;
bu_vls_printf(&gpath, "%s/tc7_nmg.g", tmpdir);
const char *gfile = bu_vls_cstr(&gpath);
if (bu_file_exists(gfile, NULL))
bu_file_delete(gfile);
struct db_i *dbip = db_create(gfile, 5);
if (!dbip) {
bu_vls_free(&gpath);
return BRLCAD_ERROR;
}
struct rt_wdb *wdbp = wdb_dbopen(dbip, RT_WDB_TYPE_DB_DEFAULT);
point_t box_pts[8] = {
{0.0, 0.0, 0.0}, {10.0, 0.0, 0.0},
{10.0, 10.0, 0.0}, {0.0, 10.0, 0.0},
{0.0, 0.0, 10.0}, {10.0, 0.0, 10.0},
{10.0, 10.0, 10.0}, {0.0, 10.0, 10.0}
};
if (write_arb8(wdbp, "box.s", box_pts) < 0 ||
write_comb1(wdbp, "box.r", "box.s", 1) < 0 ||
write_comb1(wdbp, "box.c", "box.s", 0) < 0) {
wdb_close(wdbp);
bu_vls_free(&gpath);
return BRLCAD_ERROR;
}
wdb_close(wdbp);
const char *bot_av[] = {"facetize", "--nmg-booleval", "box.r", "box.bot", NULL};
const char *fault_av[] = {"facetize", "--nmg-booleval", "box.r", "fault.bot", NULL};
const char *nmg_av[] = {"facetize", "-n", "box.r", "box.nmg", NULL};
const char *regions_av[] = {"facetize", "-r", "--nmg-booleval", "box.r", "box.regions", NULL};
const char *fallback_av[] = {"facetize", "-r", "--nmg-booleval", "box.c", "box-fallback.bot", NULL};
const char *object_in_place_av[] = {"facetize", "--in-place", "--nmg-booleval", "box.c", NULL};
const char *in_place_av[] = {"facetize", "-r", "--in-place", "--nmg-booleval", "box.r", NULL};
int ret = BRLCAD_OK;
auto check_tc7 = [&ret](bool passed, const char *description) {
if (passed)
return;
bu_log("[regress_facetize] TC7: FAIL - %s\n", description);
ret = BRLCAD_ERROR;
};
struct bu_vls fault_path = BU_VLS_INIT_ZERO;
bu_vls_printf(&fault_path, "%s/tc7_nmg_worker.fault", tmpdir);
(void)bu_file_delete(bu_vls_cstr(&fault_path));
(void)bu_setenv("LIBGED_FACETIZE_TEST_FAULT",
"nmg-before-ready:fault.bot", 1);
(void)bu_setenv("LIBGED_FACETIZE_TEST_FAULT_FILE",
bu_vls_cstr(&fault_path), 1);
int fault_ret = run_facetize_command(gfile, 4, fault_av, verbose);
(void)bu_setenv("LIBGED_FACETIZE_TEST_FAULT", "", 1);
(void)bu_setenv("LIBGED_FACETIZE_TEST_FAULT_FILE", "", 1);
check_tc7(fault_ret == BRLCAD_ERROR,
"an interrupted NMG Boolean worker did not report failure");
check_tc7(bu_file_exists(bu_vls_cstr(&fault_path), NULL),
"NMG Boolean worker fault did not trigger");
check_tc7(check_object_type(gfile, "fault.bot", ID_BOT) != BRLCAD_OK,
"an interrupted NMG Boolean worker committed an output");
(void)bu_file_delete(bu_vls_cstr(&fault_path));
bu_vls_free(&fault_path);
int hook_calls = 0;
bu_log_add_hook(count_log_hook, &hook_calls);
int bot_ret = run_facetize_command(gfile, 4, bot_av, verbose);
int hook_calls_before_probe = hook_calls;
bu_log("facetize NMG hook restoration probe\n");
bu_log_delete_hook(count_log_hook, &hook_calls);
check_tc7(bot_ret == BRLCAD_OK, "NMG Boolean BoT command failed");
check_tc7(hook_calls == hook_calls_before_probe + 1,
"temporary log hook was not restored");
check_tc7(check_bot_exists(gfile, "box.bot") == BRLCAD_OK,
"NMG Boolean BoT output is missing");
int nmg_ret = run_facetize_command(gfile, 4, nmg_av, verbose);
check_tc7(nmg_ret == BRLCAD_OK, "NMG output command failed");
check_tc7(check_object_type(gfile, "box.nmg", ID_NMG) == BRLCAD_OK,
"NMG output has the wrong type");
int regions_ret = run_facetize_command(gfile, 5, regions_av, verbose);
check_tc7(regions_ret == BRLCAD_OK, "NMG Boolean region command failed");
check_tc7(check_object_type(gfile, "box.regions", ID_COMBINATION) == BRLCAD_OK,
"NMG Boolean region output is missing");
int fallback_ret = run_facetize_command(gfile, 5, fallback_av, verbose);
check_tc7(fallback_ret == BRLCAD_OK,
"region mode object fallback command failed");
check_tc7(check_bot_exists(gfile, "box-fallback.bot") == BRLCAD_OK,
"region mode object fallback output is missing");
int object_in_place_ret = run_facetize_command(gfile, 4,
object_in_place_av, verbose);
check_tc7(object_in_place_ret == BRLCAD_OK,
"in-place NMG Boolean object command failed");
check_tc7(check_object_type(gfile, "box.c", ID_BOT) == BRLCAD_OK,
"in-place NMG Boolean object has the wrong type");
int in_place_ret = run_facetize_command(gfile, 5, in_place_av, verbose);
check_tc7(in_place_ret == BRLCAD_OK,
"in-place NMG Boolean region command failed");
check_tc7(check_object_type(gfile, "box.r", ID_COMBINATION) == BRLCAD_OK,
"in-place region root has the wrong type");
check_tc7(check_bot_exists(gfile, "box.r.bot") == BRLCAD_OK,
"in-place region BoT output is missing");
bu_log("[regress_facetize] TC7: %s\n", ret == BRLCAD_OK ? "PASS" : "FAIL");
bu_vls_free(&gpath);
return ret;
}
/* ------------------------------------------------------------------ */
/* TC8: implicit root replacement persists across database reopen */
/* ------------------------------------------------------------------ */
static int
tc8_implicit_root_persistence(const char *tmpdir, int verbose)
{
bu_log("[regress_facetize] TC8: implicit root persistence...\n");
struct bu_vls gpath = BU_VLS_INIT_ZERO;
bu_vls_printf(&gpath, "%s/tc8_implicit_root.g", tmpdir);
const char *gfile = bu_vls_cstr(&gpath);
if (bu_file_exists(gfile, NULL))
bu_file_delete(gfile);
struct db_i *dbip = db_create(gfile, 5);
if (!dbip) {
bu_vls_free(&gpath);
return BRLCAD_ERROR;
}
struct rt_wdb *wdbp = wdb_dbopen(dbip, RT_WDB_TYPE_DB_DEFAULT);
point_t region_points[8] = {
{0.0, 0.0, 0.0}, {10.0, 0.0, 0.0},
{10.0, 10.0, 0.0}, {0.0, 10.0, 0.0},
{0.0, 0.0, 10.0}, {10.0, 0.0, 10.0},
{10.0, 10.0, 10.0}, {0.0, 10.0, 10.0}
};
point_t loose_points[8] = {
{20.0, 0.0, 0.0}, {30.0, 0.0, 0.0},
{30.0, 10.0, 0.0}, {20.0, 10.0, 0.0},
{20.0, 0.0, 10.0}, {30.0, 0.0, 10.0},
{30.0, 10.0, 10.0}, {20.0, 10.0, 10.0}
};
if (!wdbp || write_arb8(wdbp, "region.s", region_points) < 0 ||
write_arb8(wdbp, "loose.s", loose_points) < 0 ||
write_comb1(wdbp, "box.r", "region.s", 1) < 0 ||
write_comb2(wdbp, "assembly.c", "box.r", 'u',
"loose.s", 'u') < 0) {
if (wdbp)
wdb_close(wdbp);
bu_vls_free(&gpath);
return BRLCAD_ERROR;
}
wdb_close(wdbp);
const char *facetize_args[] = {
"facetize", "-r", "assembly.c", "assembly.regions", NULL
};
int ret = run_facetize_command(gfile, 4, facetize_args, verbose);
if (ret == BRLCAD_OK &&
(check_object_type(gfile, "assembly.regions", ID_COMBINATION) != BRLCAD_OK ||
check_object_type(gfile, "facetize_assembly.c", ID_COMBINATION) != BRLCAD_OK ||
check_bot_exists(gfile, "box.r.bot") != BRLCAD_OK ||
check_bot_exists(gfile, "facetize_loose.s") != BRLCAD_OK))
ret = BRLCAD_ERROR;
bu_log("[regress_facetize] TC8: %s\n",
ret == BRLCAD_OK ? "PASS" : "FAIL");
bu_vls_free(&gpath);
return ret;
}
/* ------------------------------------------------------------------ */
/* main */
/* ------------------------------------------------------------------ */
@@ -1151,6 +1392,8 @@ return 1;
if (tc4_havoc_reuse(tmpdir, verbose) != BRLCAD_OK) ret = 1;
if (tc5_near_coplanar_subTOL(tmpdir, verbose) != BRLCAD_OK) ret = 1;
if (tc6_havoc_wind9_pattern(tmpdir, verbose) != BRLCAD_OK) ret = 1;
if (tc7_nmg_modes(tmpdir, verbose) != BRLCAD_OK) ret = 1;
if (tc8_implicit_root_persistence(tmpdir, verbose) != BRLCAD_OK) ret = 1;
if (ret == 0)
bu_log("[regress_facetize] All tests PASSED\n");
+2 -3
View File
@@ -53,7 +53,7 @@ set(
)
brlcad_addlib(librender "${LIBRENDER_SRCS}" "" "${ADRT_LOCAL_INCLUDE_DIRS}"
PRIVATE_LIBS libgcv librt ZLIB::ZLIB ${M_LIBRARY}
PRIVATE_LIBS libgcv ZLIB::ZLIB ${M_LIBRARY}
)
set_target_properties(librender PROPERTIES VERSION 20.0.1 SOVERSION 20)
add_dependencies(librender gcv_plugins)
@@ -109,9 +109,8 @@ cmakefiles(isst.c)
add_subdirectory(master)
add_subdirectory(slave)
add_subdirectory(tests)
set(adrt_ignore_files load.h load_g.h tienet.h)
set(adrt_ignore_files load.h tienet.h)
cmakefiles(${adrt_ignore_files})
cmakefiles(CMakeLists.txt)
-8
View File
@@ -90,19 +90,11 @@ enum
#define ADRT_NAME_SIZE 256
/* TIE geometry is normalized from millimeters to meters while loading. */
#define ADRT_MODEL_UNITS_PER_TIE_UNIT 1000.0
#define ADRT_LOAD_FORMAT_G 42
#define ADRT_LOAD_FORMAT_REG 43
#define ADRT_LOAD_FORMAT_KDTREE 44
struct rt_annot_scene;
RENDER_EXPORT extern int load_g(struct tie_s *tie, const char *db, int argc, const char **argv, struct adrt_mesh_s **);
RENDER_EXPORT extern int load_g_annotations(struct tie_s *tie, const char *db,
int argc, const char **argv, struct adrt_mesh_s **,
struct rt_annot_scene **annotations);
#endif
+38 -23
View File
@@ -59,7 +59,6 @@ struct isst_s {
struct render_camera_s camera;
struct camera_tile_s tile;
struct adrt_mesh_s *meshes;
struct rt_annot_scene *annotations;
tienet_buffer_t buffer_image;
int ogl, sflags, w, h, gs, ui;
double dt, fps, uic;
@@ -68,7 +67,6 @@ struct isst_s {
void *texdata;
vect_t camera_pos_init;
vect_t camera_focus_init;
fastf_t scene_radius;
int64_t t1;
int64_t t2;
int dirty;
@@ -121,7 +119,13 @@ resize_isst(struct isst_s *isstp)
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
isstp->texdata = realloc(isstp->texdata, isstp->camera.w * isstp->camera.h * 3);
{
/* realloc through a temporary so a failure does not leak (and null out)
* the existing buffer. */
void *tmp = realloc(isstp->texdata, isstp->camera.w * isstp->camera.h * 3);
if (tmp)
isstp->texdata = tmp;
}
glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB, isstp->camera.w, isstp->camera.h, 0, GL_RGB, GL_UNSIGNED_BYTE, isstp->texdata);
glDisable(GL_LIGHTING);
@@ -154,14 +158,11 @@ isst_load_g(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc,
argv = (char **)malloc(sizeof(char *) * (strlen(Tcl_GetString(objv[3])) + 1)); /* allocate way too much. */
argc = (int)bu_argv_from_string(argv, strlen(Tcl_GetString(objv[3])), Tcl_GetString(objv[3]));
rt_annot_scene_destroy(isst->annotations);
isst->annotations = NULL;
load_g_annotations(isst->tie, Tcl_GetString(objv[2]), argc,
(const char **)argv, &(isst->meshes), &isst->annotations);
load_g(isst->tie, Tcl_GetString(objv[2]), argc, (const char **)argv, &(isst->meshes));
free(argv);
isst->scene_radius = render_camera_fit_scene(&isst->camera, isst->tie,
isst->annotations, ADRT_MODEL_UNITS_PER_TIE_UNIT);
VSETALL(isst->camera.pos, isst->tie->radius);
VMOVE(isst->camera.focus, isst->tie->mid);
VMOVE(isst->camera_pos_init, isst->camera.pos);
VMOVE(isst->camera_focus_init, isst->camera.focus);
@@ -238,9 +239,7 @@ paint_window(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Ob
isst->buffer_image.ind = 0;
render_camera_prep(&isst->camera);
render_camera_render_annotations(&isst->camera, isst->tie, &isst->tile,
&isst->buffer_image, isst->annotations,
ADRT_MODEL_UNITS_PER_TIE_UNIT);
render_camera_render(&isst->camera, isst->tie, &isst->tile, &isst->buffer_image);
isst->t1 = bu_gettime();
@@ -283,6 +282,7 @@ set_resolution(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_
}
CLAMP(resolution, 1, 20);
/* gs is the render grid size; 0 means render at full window resolution */
if (resolution == 20)
isst->gs = 0;
else
@@ -326,10 +326,13 @@ isst_zap(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *c
return TCL_ERROR;
}
/* Release the buffers owned directly by the workspace before the struct
* itself. (The tie and mesh list have a more involved lifecycle and are
* left for a dedicated teardown.) */
TIENET_BUFFER_FREE(isst->buffer_image);
if (isst->texdata)
free(isst->texdata);
rt_annot_scene_destroy(isst->annotations);
bu_free(isst, "isst free");
isst = NULL;
@@ -351,7 +354,7 @@ render_mode(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj
if (objc == 4)
buf = Tcl_GetString(objv[3]);
/* pack the 'rest' into buf - probably should use a vls for this*/
/* pack the 'rest' into buf - probably should use a vls for this */
if ( strlen(mode) == 3 && bu_strncmp("cut", mode, 3) == 0 ) {
struct adrt_mesh_s *mesh;
@@ -388,22 +391,26 @@ zero_view(ClientData UNUSED(clientData), Tcl_Interp *UNUSED(interp), int UNUSED(
static int
move_walk(ClientData UNUSED(clientData), Tcl_Interp *interp, int UNUSED(objc), Tcl_Obj *const *objv)
move_walk(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const *objv)
{
vect_t vec;
int flag;
if (objc < 3) {
Tcl_WrongNumArgs(interp, 1, objv, "pathName flag");
return TCL_ERROR;
}
if (Tcl_GetIntFromObj(interp, objv[2], &flag) != TCL_OK)
return TCL_ERROR;
if (flag >= 0) {
VSUB2(vec, isst->camera.focus, isst->camera.pos);
VSCALE(vec, vec, 0.1 * isst->scene_radius);
VSCALE(vec, vec, 0.1 * isst->tie->radius);
VADD2(isst->camera.pos, isst->camera.pos, vec);
VADD2(isst->camera.focus, isst->camera.focus, vec);
} else {
VSUB2(vec, isst->camera.pos, isst->camera.focus);
VSCALE(vec, vec, 0.1 * isst->scene_radius);
VSCALE(vec, vec, 0.1 * isst->tie->radius);
VADD2(isst->camera.pos, isst->camera.pos, vec);
VADD2(isst->camera.focus, isst->camera.focus, vec);
}
@@ -412,12 +419,16 @@ move_walk(ClientData UNUSED(clientData), Tcl_Interp *interp, int UNUSED(objc), T
}
static int
move_strafe(ClientData UNUSED(clientData), Tcl_Interp *interp, int UNUSED(objc), Tcl_Obj *const *objv)
move_strafe(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const *objv)
{
vect_t vec, dir, up;
int flag;
if (objc < 3) {
Tcl_WrongNumArgs(interp, 1, objv, "pathName flag");
return TCL_ERROR;
}
if (Tcl_GetIntFromObj(interp, objv[2], &flag) != TCL_OK)
return TCL_ERROR;
@@ -426,13 +437,13 @@ move_strafe(ClientData UNUSED(clientData), Tcl_Interp *interp, int UNUSED(objc),
if (flag >= 0) {
VSUB2(dir, isst->camera.focus, isst->camera.pos);
VCROSS(vec, dir, up);
VSCALE(vec, vec, 0.1 * isst->scene_radius);
VSCALE(vec, vec, 0.1 * isst->tie->radius);
VADD2(isst->camera.pos, isst->camera.pos, vec);
VADD2(isst->camera.focus, isst->camera.pos, dir);
} else {
VSUB2(dir, isst->camera.focus, isst->camera.pos);
VCROSS(vec, dir, up);
VSCALE(vec, vec, -0.1 * isst->scene_radius);
VSCALE(vec, vec, -0.1 * isst->tie->radius);
VADD2(isst->camera.pos, isst->camera.pos, vec);
VADD2(isst->camera.focus, isst->camera.pos, dir);
}
@@ -540,10 +551,14 @@ aerotate(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *c
VSCALE(vecdfoc, vecdfoc, mag_focus);
VADD2(isst->camera.focus, isst->camera_focus_init, vecdfoc);
}
/* Update the tcl copies of the az/el vars */
/* Update the tcl copies of the az/el vars. Store them in the same units
* as isst_load_g (radians via -DEG2RAD); previously aerotate wrote the raw
* degrees from bn_ae_vec, leaving the Tcl vars inconsistent after a drag. */
VSUB2(vec, isst->camera.focus, isst->camera.pos);
VUNITIZE(vec);
bn_ae_vec(&az, &el, vec);
az = az * -DEG2RAD;
el = el * -DEG2RAD;
bu_vls_sprintf(&tclstr, "%f", az);
Tcl_SetVar(interp, "az", bu_vls_addr(&tclstr), 0);
bu_vls_sprintf(&tclstr, "%f", el);
@@ -561,7 +576,7 @@ open_dm(ClientData UNUSED(cdata), Tcl_Interp *interp, int UNUSED(objc), Tcl_Obj
dmp = dm_open(NULL, (void *)interp, dm_default_type(), sizeof(av)/sizeof(void*)-1, (const char **)av);
if (dmp == DM_NULL) {
printf("dm failed?\n");
printf("Failed to open display manager\n");
return TCL_ERROR;
}
@@ -639,7 +654,7 @@ const char *fullname;
argv = __argv;
#endif
/* initialize progname for run-tim resource finding */
/* initialize progname for run-time resource finding */
bu_setprogname(argv[0]);
#ifdef HAVE_WINDOWS_H
+21 -225
View File
@@ -29,7 +29,6 @@
#include "bu/dylib.h"
#include "bu/log.h"
#include "bu/str.h"
#include "rt/primitives/annot.h"
#include "./camera.h"
@@ -44,27 +43,13 @@ struct render_shader_s {
static struct render_shader_s *shaders = NULL;
struct render_camera_annotation_data {
const struct rt_annot_scene *scene;
fastf_t model_units_per_tie_unit;
struct rt_annot_view view;
};
struct render_camera_parallel_data {
render_camera_thread_data_t thread;
struct render_camera_annotation_data annotation;
};
static const fastf_t render_camera_default_scene_radius = 1.0;
/* number of leading characters compared when matching a shader by name */
#define RENDER_SHADER_NAME_CMP_LEN 8
void render_camera_render_thread(int cpu, void *ptr); /* for bu_parallel */
static void render_camera_prep_ortho(render_camera_t *camera);
static void render_camera_prep_persp(render_camera_t *camera);
static void render_camera_prep_persp_dof(render_camera_t *camera);
static void render_camera_annotation_view(const render_camera_t *camera,
fastf_t model_units_per_tie_unit, struct rt_annot_view *view);
static struct render_shader_s *render_shader_register (const char *name, int (*init)(render_t *, const char *));
@@ -408,147 +393,20 @@ render_camera_prep(render_camera_t *camera)
}
fastf_t
render_camera_fit_scene(render_camera_t *camera, const struct tie_s *tie,
const struct rt_annot_scene *annotations,
fastf_t model_units_per_tie_unit)
{
point_t annotation_min, annotation_max;
point_t scene_min, scene_max;
vect_t offset;
fastf_t scene_radius;
if (!camera || !tie)
return 0.0;
if (!annotations || !rt_annot_scene_bounds(annotations,
annotation_min, annotation_max)) {
VSETALL(camera->pos, tie->radius);
VMOVE(camera->focus, tie->mid);
return tie->radius;
}
if (!isfinite(model_units_per_tie_unit) ||
model_units_per_tie_unit <= 0.0)
model_units_per_tie_unit = 1.0;
VSCALE(annotation_min, annotation_min,
1.0 / model_units_per_tie_unit);
VSCALE(annotation_max, annotation_max,
1.0 / model_units_per_tie_unit);
VMOVE(scene_min, annotation_min);
VMOVE(scene_max, annotation_max);
if (tie->tri_num) {
VMINMAX(scene_min, scene_max, tie->amin);
VMINMAX(scene_min, scene_max, tie->amax);
}
VADD2SCALE(camera->focus, scene_min, scene_max, 0.5);
VSUB2(offset, scene_max, scene_min);
scene_radius = 0.5 * MAGNITUDE(offset);
if (!isfinite(scene_radius) || scene_radius <= SMALL_FASTF)
scene_radius = render_camera_default_scene_radius;
/* Keep the established isometric initial direction while positioning it
* relative to the combined scene center. */
VSETALL(offset, scene_radius);
VADD2(camera->pos, camera->focus, offset);
return scene_radius;
}
static void
render_camera_annotation_view(const render_camera_t *camera,
fastf_t model_units_per_tie_unit, struct rt_annot_view *view)
{
vect_t look, up, side, temp, right;
point_t model_position;
fastf_t angle, sine, cosine, xy_scale = 1.0;
mat_t *matrix = &view->model2view;
VSUB2(look, camera->focus, camera->pos);
VUNITIZE(look);
VSET(up, 0.0, 0.0, 1.0);
VMOVE(temp, look);
angle = VDOT(up, temp);
VSCALE(temp, temp, angle);
VSUB2(up, up, temp);
VUNITIZE(up);
VCROSS(side, up, look);
sine = sin(-camera->tilt * DEG2RAD);
cosine = cos(-camera->tilt * DEG2RAD);
VSCALE(up, up, cosine);
VSCALE(side, side, sine);
VADD2(up, up, side);
VCROSS(side, up, look);
VREVERSE(right, side);
MAT_IDN(*matrix);
if (camera->type == RENDER_CAMERA_ORTHOGRAPHIC &&
camera->aspect > 0.0 && camera->gridsize > 0.0) {
xy_scale = 2.0 / (camera->aspect * camera->gridsize *
model_units_per_tie_unit);
} else if (camera->aspect > 0.0) {
xy_scale = 1.0 / camera->aspect;
}
for (size_t axis = 0; axis < 3; ++axis) {
(*matrix)[axis] = right[axis] * xy_scale;
(*matrix)[4 + axis] = up[axis] * xy_scale;
(*matrix)[8 + axis] = -look[axis];
}
VSCALE(model_position, camera->pos, model_units_per_tie_unit);
(*matrix)[3] = -VDOT(&(*matrix)[0], model_position);
(*matrix)[7] = -VDOT(&(*matrix)[4], model_position);
(*matrix)[11] = -VDOT(&(*matrix)[8], model_position);
view->width = camera->w;
view->height = camera->h;
view->perspective =
camera->type == RENDER_CAMERA_PERSPECTIVE ? 2.0 * camera->fov : 0.0;
}
static void
render_camera_composite_annotation(render_camera_thread_data_t *td,
const struct render_camera_annotation_data *annotation,
const struct tie_ray_s *tie_ray, fastf_t sample_x, fastf_t sample_y,
vect_t *pixel)
{
struct rt_annot_hit back_layer = {0};
struct xray ray;
fastf_t scene_distance = INFINITY;
if (!annotation || !annotation->scene)
return;
VSCALE(ray.r_pt, tie_ray->pos, annotation->model_units_per_tie_unit);
VMOVE(ray.r_dir, tie_ray->dir);
if (!rt_annot_scene_query_layers(annotation->scene, &annotation->view,
&ray, sample_x, sample_y, INFINITY, &back_layer, 1))
return;
if (!back_layer.screen_space) {
struct tie_id_s id;
struct tie_ray_s depth_ray = *tie_ray;
if (TIE_WORK(td->tie, &depth_ray, &id, render_hit, NULL))
scene_distance = id.dist * annotation->model_units_per_tie_unit;
}
(void)rt_annot_scene_composite(annotation->scene, &annotation->view,
&ray, sample_x, sample_y, scene_distance, *pixel, NULL);
}
static void
render_camera_render_thread_impl(int UNUSED(cpu), render_camera_thread_data_t *td,
const struct render_camera_annotation_data *annotation)
void
render_camera_render_thread(int UNUSED(cpu), void *ptr)
{
render_camera_thread_data_t *td;
int d, n, res_ind, scanline, v_scanline;
vect_t pixel, accum;
vect_t v1 = VINIT_ZERO;
vect_t v2 = VINIT_ZERO;
struct tie_ray_s ray;
struct tie_ray_s annotation_ray;
fastf_t view_inv;
VSETALL(v1, 0);
td = (render_camera_thread_data_t *)ptr;
view_inv = 1.0 / td->camera->view_num;
td->camera->render.tie = td->tie;
@@ -599,15 +457,9 @@ render_camera_render_thread_impl(int UNUSED(cpu), render_camera_thread_data_t *t
VMOVE(ray.pos, td->camera->view_list[d].pos);
ray.depth = 0;
VUNITIZE(ray.dir);
annotation_ray = ray;
/* Compute pixel value using this ray */
td->camera->render.work(&td->camera->render, td->tie, &ray, &pixel);
render_camera_composite_annotation(td, annotation,
&annotation_ray,
(fastf_t)n + 0.5,
(fastf_t)td->camera->h - (fastf_t)v_scanline - 0.5,
&pixel);
VADD2(accum, accum, pixel);
}
@@ -624,7 +476,6 @@ render_camera_render_thread_impl(int UNUSED(cpu), render_camera_thread_data_t *t
VMOVE(ray.pos, td->camera->view_list[0].pos);
ray.depth = 0;
VUNITIZE(ray.dir);
annotation_ray = ray;
/* Compute pixel value using this ray */
td->camera->render.work(&td->camera->render, td->tie, &ray, &pixel);
@@ -639,19 +490,12 @@ render_camera_render_thread_impl(int UNUSED(cpu), render_camera_thread_data_t *t
VSET(pixel, (TFLOAT)RENDER_CAMERA_BGR, (TFLOAT)RENDER_CAMERA_BGG, (TFLOAT)RENDER_CAMERA_BGB);
ray.depth = 0;
annotation_ray = ray;
/* Compute pixel value using this ray */
td->camera->render.work(&td->camera->render, td->tie, &ray, &pixel);
}
}
if (td->camera->view_num == 1)
render_camera_composite_annotation(td, annotation,
&annotation_ray, (fastf_t)n + 0.5,
(fastf_t)td->camera->h - (fastf_t)v_scanline - 0.5,
&pixel);
if (td->tile->format == RENDER_CAMERA_BIT_DEPTH_24) {
V_MIN(pixel[0], 1);
@@ -679,30 +523,9 @@ render_camera_render_thread_impl(int UNUSED(cpu), render_camera_thread_data_t *t
void
render_camera_render_thread(int cpu, void *ptr)
render_camera_render(render_camera_t *camera, struct tie_s *tie, camera_tile_t *tile, tienet_buffer_t *result)
{
render_camera_render_thread_impl(cpu, (render_camera_thread_data_t *)ptr,
NULL);
}
static void
render_camera_render_annotations_thread(int cpu, void *ptr)
{
struct render_camera_parallel_data *data =
(struct render_camera_parallel_data *)ptr;
render_camera_render_thread_impl(cpu, &data->thread, &data->annotation);
}
static void
render_camera_render_internal(render_camera_t *camera, struct tie_s *tie,
camera_tile_t *tile, tienet_buffer_t *result,
const struct rt_annot_scene *annotations,
fastf_t model_units_per_tie_unit)
{
struct render_camera_parallel_data data = {0};
render_camera_thread_data_t td;
unsigned int scanline;
uint32_t ind;
@@ -720,47 +543,19 @@ render_camera_render_internal(render_camera_t *camera, struct tie_s *tie,
TCOPY(camera_tile_t, tile, 0, result->data, result->ind);
result->ind += sizeof(camera_tile_t);
data.thread.tie = tie;
data.thread.camera = camera;
data.thread.tile = tile;
data.thread.res_buf = &((char *)result->data)[result->ind];
td.tie = tie;
td.camera = camera;
td.tile = tile;
td.res_buf = &((char *)result->data)[result->ind];
scanline = 0;
data.thread.scanline = &scanline;
data.thread.sem_tie_worker = bu_semaphore_register("sem_tie_worker");
data.annotation.scene = annotations;
data.annotation.model_units_per_tie_unit =
model_units_per_tie_unit > 0.0 ? model_units_per_tie_unit : 1.0;
if (annotations)
render_camera_annotation_view(camera,
data.annotation.model_units_per_tie_unit, &data.annotation.view);
td.scanline = &scanline;
td.sem_tie_worker = bu_semaphore_register("sem_tie_worker");
if (annotations)
bu_parallel(render_camera_render_annotations_thread,
camera->thread_num, &data);
else
bu_parallel(render_camera_render_thread, camera->thread_num,
&data.thread);
bu_parallel(render_camera_render_thread, camera->thread_num, &td);
result->ind = ind;
}
void
render_camera_render(render_camera_t *camera, struct tie_s *tie,
camera_tile_t *tile, tienet_buffer_t *result)
{
render_camera_render_internal(camera, tie, tile, result, NULL, 1.0);
}
void
render_camera_render_annotations(render_camera_t *camera, struct tie_s *tie,
camera_tile_t *tile, tienet_buffer_t *result,
const struct rt_annot_scene *annotations,
fastf_t model_units_per_tie_unit)
{
render_camera_render_internal(camera, tie, tile, result, annotations,
model_units_per_tie_unit);
return;
}
@@ -825,9 +620,9 @@ render_shader_unload_plugin(render_t *r, const char *name)
{
#ifdef HAVE_DLFCN_H
struct render_shader_s *t, *s = shaders, *meh;
if (!bu_strncmp(s->name, name, 8)) {
if (!bu_strncmp(s->name, name, RENDER_SHADER_NAME_CMP_LEN)) {
t = s->next;
if (r && r->shader && !bu_strncmp(r->shader, name, 8)) {
if (r && r->shader && !bu_strncmp(r->shader, name, RENDER_SHADER_NAME_CMP_LEN)) {
meh = s->next;
while (meh) {
if (render_shader_init(r, meh->name, NULL) != -1)
@@ -846,7 +641,7 @@ LOADED:
}
while (s->next) {
if (!bu_strncmp(s->next->name, name, 8)) {
if (!bu_strncmp(s->next->name, name, RENDER_SHADER_NAME_CMP_LEN)) {
if (r)
render_shader_init(r, s->name, NULL);
if (s->next->dlh)
@@ -856,6 +651,7 @@ LOADED:
bu_free(t, "unload shader");
return 0;
}
s = s->next;
}
bu_log("Could not find shader \"%s\"\n", name);
@@ -871,7 +667,7 @@ render_shader_init(render_t *r, const char *name, const char *buf)
{
struct render_shader_s *s = shaders;
while (s) {
if (!bu_strncmp(s->name, name, 8)) {
if (!bu_strncmp(s->name, name, RENDER_SHADER_NAME_CMP_LEN)) {
s->init(r, buf);
r->shader = s->name;
return 0;
-11
View File
@@ -99,18 +99,7 @@ __BEGIN_DECLS
RENDER_EXPORT extern void render_camera_init(render_camera_t *camera, size_t threads);
RENDER_EXPORT extern void render_camera_free(render_camera_t *camera);
RENDER_EXPORT extern void render_camera_prep(render_camera_t *camera);
/** Center a camera on TIE geometry and any prepared annotations. Returns the
* effective scene radius in TIE coordinates. */
RENDER_EXPORT extern fastf_t render_camera_fit_scene(render_camera_t *camera,
const struct tie_s *tie, const struct rt_annot_scene *annotations,
fastf_t model_units_per_tie_unit);
RENDER_EXPORT extern void render_camera_render(render_camera_t *camera, struct tie_s *tie, camera_tile_t *tile, tienet_buffer_t *result);
/** Render with an externally owned annotation scene. The coordinate scale
* converts TIE coordinates to database model coordinates. */
RENDER_EXPORT extern void render_camera_render_annotations(render_camera_t *camera,
struct tie_s *tie, camera_tile_t *tile, tienet_buffer_t *result,
const struct rt_annot_scene *annotations,
fastf_t model_units_per_tie_unit);
RENDER_EXPORT extern int render_shader_init(render_t *, const char *name, const char *buf);
RENDER_EXPORT extern const char *render_shader_load_plugin(const char *filename);
+10 -86
View File
@@ -40,13 +40,11 @@
#include "vmath.h"
#include "nmg.h"
#include "rt/geom.h"
#include "rt/search.h"
#include "raytrace.h"
#include "rt/tie.h"
#include "adrt.h"
#include "adrt_struct.h"
#include "load_g.h"
static struct bn_tol tol; /* calculation tolerance */
@@ -106,42 +104,6 @@ struct gcv_data {
static struct gcv_data gcvwriter = {{load_nmg_to_adrt_gcvwrite, NULL, NULL}, NULL};
int
adrt_path_has_geometry(struct db_i *database, const char *path)
{
static const char *geometry_search = "! -type comb ! -type annot";
struct directory *root;
if (!database || !path)
return 0;
root = db_lookup(database, path, LOOKUP_QUIET);
/* Let db_walk_tree report a missing path rather than hiding the error. */
if (!root)
return 1;
return db_search(NULL, DB_SEARCH_QUIET, geometry_search, 1, &root,
database, NULL, NULL, NULL) != 0;
}
union tree *
adrt_leaf_tess(struct db_tree_state *tsp, const struct db_full_path *pathp,
struct rt_db_internal *ip, void *client_data)
{
union tree *result;
if (!ip || ip->idb_type != ID_ANNOT)
return rt_booltree_leaf_tess(tsp, pathp, ip, client_data);
/* Annotations are rendered directly and have no NMG representation. */
BU_GET(result, union tree);
RT_TREE_INIT(result);
result->tr_op = OP_NOP;
return result;
}
/* load the region into the tie image */
static void
load_nmg_to_adrt_internal(struct adrt_mesh_s *mesh, struct nmgregion *r)
@@ -191,8 +153,7 @@ load_nmg_to_adrt_internal(struct adrt_mesh_s *mesh, struct nmgregion *r)
NMG_CK_VERTEX(v);
/* convert mm to m */
VSCALE((*tribuf[vert_count]).v, v->vg_p->coord,
1.0 / ADRT_MODEL_UNITS_PER_TIE_UNIT);
VSCALE((*tribuf[vert_count]).v, v->vg_p->coord, 1.0/1000.0);
vert_count++;
}
if (vert_count > 3)
@@ -287,12 +248,9 @@ load_nmg_to_adrt_regstart(struct db_tree_state *ts, const struct db_full_path *p
for (i=0;i<bot->num_faces;i++)
{
VSCALE((*tribuf[0]).v, (bot->vertices+3*bot->faces[3*i+0]),
1.0 / ADRT_MODEL_UNITS_PER_TIE_UNIT);
VSCALE((*tribuf[1]).v, (bot->vertices+3*bot->faces[3*i+1]),
1.0 / ADRT_MODEL_UNITS_PER_TIE_UNIT);
VSCALE((*tribuf[2]).v, (bot->vertices+3*bot->faces[3*i+2]),
1.0 / ADRT_MODEL_UNITS_PER_TIE_UNIT);
VSCALE((*tribuf[0]).v, (bot->vertices+3*bot->faces[3*i+0]), 1.0/1000.0);
VSCALE((*tribuf[1]).v, (bot->vertices+3*bot->faces[3*i+1]), 1.0/1000.0);
VSCALE((*tribuf[2]).v, (bot->vertices+3*bot->faces[3*i+2]), 1.0/1000.0);
TIE_VAL(tie_push)(cur_tie, tribuf, 1, mesh, 0);
}
@@ -340,16 +298,11 @@ load_nmg_to_adrt_gcvwrite(struct nmgregion *r, const struct db_full_path *pathp,
int
load_g_annotations(struct tie_s *tie, const char *db, int argc,
const char **argv, struct adrt_mesh_s **meshes,
struct rt_annot_scene **annotations)
load_g(struct tie_s *tie, const char *db, int argc, const char **argv, struct adrt_mesh_s **meshes)
{
struct model *the_model;
struct bg_tess_tol ttol; /* tessellation tolerance in mm */
struct db_tree_state tree_state; /* includes tol & model */
const char **geometry_paths = NULL;
int geometry_count = 0;
int walk_result = 0;
cur_tie = tie; /* NOTE: cur_tie is a file-scope global; this is not
* reentrant and would need locking to be thread-safe. */
@@ -385,21 +338,13 @@ load_g_annotations(struct tie_s *tie, const char *db, int argc,
if ((dbip = db_open(db, DB_OPEN_READONLY)) == DBI_NULL) {
perror(db);
bu_log("Unable to open geometry database file (%s)\n", db);
nmg_km(the_model);
return -1;
}
if (db_dirbuild(dbip)) {
bu_log("ERROR: db_dirbuild failed\n");
db_close(dbip);
dbip = DBI_NULL;
nmg_km(the_model);
return -1;
}
if (annotations) {
*annotations = rt_annot_scene_create(dbip, argc, argv, &ttol, &tol);
}
BN_CK_TOL(tree_state.ts_tol);
BG_CK_TESS_TOL(tree_state.ts_ttol);
@@ -417,26 +362,15 @@ load_g_annotations(struct tie_s *tie, const char *db, int argc,
tribuf[1] = (TIE_3 *)bu_malloc(sizeof(TIE_3) * 3, "triangle tribuffer");
tribuf[2] = (TIE_3 *)bu_malloc(sizeof(TIE_3) * 3, "triangle tribuffer");
if (argc > 0) {
geometry_paths = (const char **)bu_calloc((size_t)argc,
sizeof(const char *), "ADRT geometry paths");
for (int i = 0; i < argc; ++i) {
if (adrt_path_has_geometry(dbip, argv[i]))
geometry_paths[geometry_count++] = argv[i];
}
}
if (geometry_count) {
walk_result = db_walk_tree(dbip,
geometry_count, /* number of toplevel regions */
geometry_paths, /* region names */
(void) db_walk_tree(dbip,
argc, /* number of toplevel regions */
argv, /* region names */
1, /* ncpu */
&tree_state, /* initial tree state */
load_nmg_to_adrt_regstart, /* region start function */
gcv_region_end, /* region end function */
adrt_leaf_tess, /* leaf func */
rt_booltree_leaf_tess, /* leaf func */
(void *)&gcvwriter); /* client data */
}
/* Release dynamic storage */
nmg_km(the_model);
@@ -446,20 +380,10 @@ load_g_annotations(struct tie_s *tie, const char *db, int argc,
bu_free(tribuf[1], "vert");
bu_free(tribuf[2], "vert");
bu_free(tribuf, "tri");
if (geometry_paths)
bu_free(geometry_paths, "ADRT geometry paths");
TIE_VAL(tie_prep)(cur_tie);
return walk_result;
}
int
load_g(struct tie_s *tie, const char *db, int argc, const char **argv,
struct adrt_mesh_s **meshes)
{
return load_g_annotations(tie, db, argc, argv, meshes, NULL);
return 0;
}
/*
-43
View File
@@ -1,43 +0,0 @@
/* L O A D _ G . H
* BRL-CAD / ADRT
*
* Copyright (c) 2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
#ifndef ADRT_LOAD_G_H
#define ADRT_LOAD_G_H
#include "common.h"
#include "adrt.h"
struct db_i;
struct db_tree_state;
struct db_full_path;
struct rt_db_internal;
union tree;
__BEGIN_DECLS
RENDER_EXPORT extern int adrt_path_has_geometry(struct db_i *dbip,
const char *path);
RENDER_EXPORT extern union tree *adrt_leaf_tess(struct db_tree_state *tsp,
const struct db_full_path *pathp, struct rt_db_internal *ip,
void *client_data);
__END_DECLS
#endif /* ADRT_LOAD_G_H */
/*
* Local Variables:
* tab-width: 8
* mode: C
* indent-tabs-mode: t
* c-file-style: "stroustrup"
* End:
* ex: shiftwidth=4 tabstop=8
*/
-16
View File
@@ -1,16 +0,0 @@
brlcad_addexec(adrt_annotation_test annotation.c
"librender;libwdb;librt;libbu;${M_LIBRARY}" TEST)
target_include_directories(adrt_annotation_test PRIVATE
${BRLCAD_SOURCE_DIR}/src/adrt
${BRLCAD_SOURCE_DIR}/src/adrt/librender
)
brlcad_add_test(NAME adrt_annotation_test COMMAND adrt_annotation_test)
cmakefiles(annotation.c CMakeLists.txt)
# Local Variables:
# tab-width: 8
# mode: cmake
# indent-tabs-mode: t
# End:
# ex: shiftwidth=2 tabstop=8
-179
View File
@@ -1,179 +0,0 @@
/* A N N O T A T I O N . C
* BRL-CAD
*
* Copyright (c) 2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
#include "common.h"
#include <math.h>
#include <stdio.h>
#include "bu/app.h"
#include "bu/file.h"
#include "raytrace.h"
#include "rt/primitives/annot.h"
#include "wdb.h"
#include "load_g.h"
#include "librender/camera.h"
static void
write_test_database(struct db_i *dbip)
{
struct rt_wdb *wdbp = wdb_dbopen(dbip, RT_WDB_TYPE_DB_DISK);
struct rt_annot_internal annot = {0};
point2d_t vertices[2];
struct line_seg line = {0};
void *segments[1];
int reverse[1] = {0};
point_t center = VINIT_ZERO;
struct wmember members;
if (wdbp == RT_WDB_NULL)
bu_exit(1, "unable to open ADRT annotation test database\n");
annot.magic = RT_ANNOT_INTERNAL_MAGIC;
VSET(annot.V, 10.0, 0.0, 0.0);
annot.flags = RT_ANNOT_MODEL_SPACE;
VSET(annot.u_vec, 0.0, 1.0, 0.0);
VSET(annot.v_vec, 0.0, 0.0, 1.0);
annot.vert_count = 2;
annot.verts = vertices;
V2SET(vertices[0], -1.0, 0.0);
V2SET(vertices[1], 1.0, 0.0);
annot.ant.count = 1;
annot.ant.reverse = reverse;
annot.ant.segments = segments;
line.magic = CURVE_LSEG_MAGIC;
line.start = 0;
line.end = 1;
segments[0] = &line;
if (rt_annot_validate(&annot, NULL) ||
mk_annot(wdbp, "test.annot", &annot) < 0 ||
mk_sph(wdbp, "test.sph", center, 1.0) < 0)
bu_exit(1, "unable to write ADRT annotation test objects\n");
BU_LIST_INIT(&members.l);
if (!mk_addmember("test.annot", &members.l, NULL, WMOP_UNION) ||
mk_lcomb(wdbp, "annotation-only.c", &members, 0, NULL, NULL,
NULL, 0))
bu_exit(1, "unable to write annotation-only test combination\n");
BU_LIST_INIT(&members.l);
if (!mk_addmember("test.annot", &members.l, NULL, WMOP_UNION) ||
!mk_addmember("test.sph", &members.l, NULL, WMOP_UNION) ||
mk_lcomb(wdbp, "mixed.c", &members, 0, NULL, NULL, NULL, 0))
bu_exit(1, "unable to write mixed test combination\n");
}
static void
check_geometry_filter(struct db_i *dbip)
{
struct rt_db_internal intern;
union tree *leaf;
if (adrt_path_has_geometry(dbip, "test.annot") ||
adrt_path_has_geometry(dbip, "annotation-only.c") ||
!adrt_path_has_geometry(dbip, "test.sph") ||
!adrt_path_has_geometry(dbip, "mixed.c"))
bu_exit(1, "ADRT annotation geometry filtering failed\n");
RT_DB_INTERNAL_INIT(&intern);
intern.idb_type = ID_ANNOT;
leaf = adrt_leaf_tess(NULL, NULL, &intern, NULL);
if (!leaf || leaf->tr_op != OP_NOP)
bu_exit(1, "ADRT annotation leaf did not become a no-op\n");
db_free_tree(leaf);
}
static void
check_camera_fit(struct db_i *dbip)
{
const char *paths[] = {"test.annot"};
struct bg_tess_tol ttol = BG_TESS_TOL_INIT_TOL;
struct bn_tol tol = BN_TOL_INIT_TOL;
struct rt_annot_scene *scene = rt_annot_scene_create(dbip, 1, paths,
&ttol, &tol);
render_camera_t camera = {0};
struct tie_s tie = {0};
fastf_t radius;
const fastf_t combined_radius = 0.5 * sqrt(41.0);
if (!scene || rt_annot_scene_count(scene) != 1)
bu_exit(1, "unable to prepare ADRT annotation test scene\n");
tie.radius = 2.0;
VSET(tie.mid, 1.0, 2.0, 3.0);
radius = render_camera_fit_scene(&camera, &tie, NULL, 1.0);
if (!NEAR_EQUAL(radius, 2.0, BN_TOL_DIST) ||
!VNEAR_EQUAL(camera.focus, tie.mid, BN_TOL_DIST) ||
!NEAR_EQUAL(camera.pos[X], 2.0, BN_TOL_DIST) ||
!NEAR_EQUAL(camera.pos[Y], 2.0, BN_TOL_DIST) ||
!NEAR_EQUAL(camera.pos[Z], 2.0, BN_TOL_DIST))
bu_exit(1, "ADRT geometry-only camera framing changed\n");
radius = render_camera_fit_scene(&camera, &tie, scene, 10.0);
if (radius <= SMALL_FASTF ||
!NEAR_EQUAL(camera.focus[X], 1.0, BN_TOL_DIST) ||
!NEAR_ZERO(camera.focus[Y], BN_TOL_DIST) ||
!NEAR_ZERO(camera.focus[Z], BN_TOL_DIST) ||
!NEAR_EQUAL(camera.pos[X] - camera.focus[X], radius, BN_TOL_DIST) ||
!NEAR_EQUAL(camera.pos[Y] - camera.focus[Y], radius, BN_TOL_DIST) ||
!NEAR_EQUAL(camera.pos[Z] - camera.focus[Z], radius, BN_TOL_DIST))
bu_exit(1, "ADRT annotation-only camera framing failed: radius=%g "
"focus=(%g %g %g) pos=(%g %g %g)\n", radius,
V3ARGS(camera.focus), V3ARGS(camera.pos));
tie.tri_num = 1;
VSET(tie.amin, -2.0, -2.0, -2.0);
VSET(tie.amax, 0.0, 2.0, 2.0);
radius = render_camera_fit_scene(&camera, &tie, scene, 10.0);
if (!NEAR_EQUAL(radius, combined_radius, BN_TOL_DIST) ||
!NEAR_EQUAL(camera.focus[X], -0.5, BN_TOL_DIST) ||
!NEAR_ZERO(camera.focus[Y], BN_TOL_DIST) ||
!NEAR_ZERO(camera.focus[Z], BN_TOL_DIST))
bu_exit(1, "ADRT combined geometry and annotation framing failed\n");
rt_annot_scene_destroy(scene);
}
int
main(int argc, char **argv)
{
char path[MAXPATHLEN];
struct db_i *dbip;
bu_setprogname(argv[0]);
if (argc != 1)
return 1;
{
FILE *fp = bu_temp_file(path, MAXPATHLEN);
if (!fp)
bu_exit(1, "unable to create ADRT annotation test path\n");
fclose(fp);
}
dbip = db_create(path, 5);
if (dbip == DBI_NULL)
bu_exit(1, "unable to create ADRT annotation test database\n");
write_test_database(dbip);
check_geometry_filter(dbip);
check_camera_fit(dbip);
db_close(dbip);
bu_file_delete(path);
return 0;
}
/*
* Local Variables:
* tab-width: 8
* mode: C
* indent-tabs-mode: t
* c-file-style: "stroustrup"
* End:
* ex: shiftwidth=4 tabstop=8
*/
+480 -399
View File
File diff suppressed because it is too large Load Diff
+4 -5
View File
@@ -64,17 +64,16 @@ ArtTileCallback::on_tile_end(const renderer::Frame* frame, const size_t tile_x,
{
foundation::Tile& t = frame->image().tile(tile_x, tile_y);
const foundation::Tile rgb(t, PixelFormatUInt8);
const foundation::CanvasProperties& properties = frame->image().properties();
// fb_write(fbp, tile_x, tile_y, rgb.get_storage(), rgb.get_size());
// printf("yay!\n");
// printf("%lu %lu \n", tile_x, tile_y);
// printf("%lu %lu \n", rgb.get_width(), rgb.get_height());
for (size_t y = 0; y < rgb.get_height(); y++) {
for (size_t x = 0; x < rgb.get_width(); x++) {
size_t x_coord = tile_x * properties.m_tile_width + x;
size_t y_coord = tile_y * properties.m_tile_height + y;
size_t img_h = properties.m_canvas_height;
fb_write(fbp, (int)x_coord, (int)(img_h - y_coord - 1), rgb.get_storage()+((y * rgb.get_width() * 4) + (x * 4)), 1);
size_t x_coord = tile_x * rgb.get_width() + x;
size_t y_coord = tile_y * rgb.get_height() + y;
size_t img_h = frame->image().properties().m_canvas_height;
fb_write(fbp, (int)x_coord, (int)(img_h - y_coord), rgb.get_storage()+((y * rgb.get_width() * 4) + (x * 4)), 1);
}
}
}
+1
View File
@@ -42,6 +42,7 @@ if(BRLCAD_ENABLE_QT AND OPENGL_TARGETS)
Qt6::Widgets
Qt6::OpenGL
Qt6::OpenGLWidgets
${OPENGL_TARGETS}
)
else(Qt6Widgets_FOUND)
qt5_wrap_cpp(moc_srcs ${isst_headers})
+15 -52
View File
@@ -26,7 +26,6 @@
#include <QFile>
#include <QPlainTextEdit>
#include <QTextStream>
#include <vector>
#include "gfile.h"
#include "bu/malloc.h"
@@ -34,7 +33,6 @@
#include "gcv.h"
#include "nmg.h"
#include "rt/geom.h"
#include "load_g.h"
/* Replace the load_g globals from adrt with a struct that is
* passed through the callers. */
@@ -104,8 +102,7 @@ nmg_to_adrt_internal(TIE_3 **tribuf, struct tie_s *cur_tie, struct adrt_mesh_s *
NMG_CK_VERTEX(v);
/* convert mm to m */
VSCALE((*tribuf[vert_count]).v, v->vg_p->coord,
1.0 / ADRT_MODEL_UNITS_PER_TIE_UNIT);
VSCALE((*tribuf[vert_count]).v, v->vg_p->coord, 1.0/1000.0);
vert_count++;
}
if (vert_count > 3)
@@ -188,12 +185,9 @@ nmg_to_adrt_regstart(struct db_tree_state *ts, const struct db_full_path *path,
for (i=0;i<bot->num_faces;i++)
{
VSCALE((*d->tribuf[0]).v, (bot->vertices+3*bot->faces[3*i+0]),
1.0 / ADRT_MODEL_UNITS_PER_TIE_UNIT);
VSCALE((*d->tribuf[1]).v, (bot->vertices+3*bot->faces[3*i+1]),
1.0 / ADRT_MODEL_UNITS_PER_TIE_UNIT);
VSCALE((*d->tribuf[2]).v, (bot->vertices+3*bot->faces[3*i+2]),
1.0 / ADRT_MODEL_UNITS_PER_TIE_UNIT);
VSCALE((*d->tribuf[0]).v, (bot->vertices+3*bot->faces[3*i+0]), 1.0/1000.0);
VSCALE((*d->tribuf[1]).v, (bot->vertices+3*bot->faces[3*i+1]), 1.0/1000.0);
VSCALE((*d->tribuf[2]).v, (bot->vertices+3*bot->faces[3*i+2]), 1.0/1000.0);
TIE_VAL(tie_push)(d->cur_tie, d->tribuf, 1, mesh, 0);
}
@@ -239,13 +233,6 @@ nmg_to_adrt_gcvwrite(struct nmgregion *r, const struct db_full_path *pathp, stru
nmg_to_adrt_internal(d->tribuf, d->cur_tie, mesh, r);
}
GFile::~GFile()
{
closedb();
}
int
GFile::load_g(const char *filename, int argc, const char *argv[])
{
@@ -254,9 +241,6 @@ GFile::load_g(const char *filename, int argc, const char *argv[])
struct bg_tess_tol ttol; /* tessellation tolerance in mm */
struct db_tree_state tree_state; /* includes tol & model */
struct isst_nmg_data d;
std::vector<const char *> geometry_paths;
closedb();
RT_DBTS_INIT(&tree_state);
tree_state.ts_tol = &tol;
@@ -294,8 +278,6 @@ GFile::load_g(const char *filename, int argc, const char *argv[])
}
if (db_dirbuild(dbip)) {
bu_log("ERROR: db_dirbuild failed\n");
db_close(dbip);
dbip = NULL;
return -1;
}
d.dbip = dbip;
@@ -322,30 +304,20 @@ GFile::load_g(const char *filename, int argc, const char *argv[])
tribuf[2] = (TIE_3 *)bu_malloc(sizeof(TIE_3) * 3, "triangle tribuffer");
d.tribuf = this->tribuf;
annotations = rt_annot_scene_create(dbip, argc, argv, &ttol, &tol);
for (int i = 0; i < argc; ++i) {
if (adrt_path_has_geometry(dbip, argv[i]))
geometry_paths.push_back(argv[i]);
}
if (!geometry_paths.empty()) {
(void) db_walk_tree(dbip,
(int)geometry_paths.size(), /* number of toplevel regions */
geometry_paths.data(), /* region names */
1, /* ncpu */
&tree_state, /* initial tree state */
nmg_to_adrt_regstart, /* region start function */
gcv_region_end, /* region end function */
adrt_leaf_tess, /* leaf func */
(void *)&gcvwriter); /* client data */
}
(void) db_walk_tree(dbip,
argc, /* number of toplevel regions */
argv, /* region names */
1, /* ncpu */
&tree_state, /* initial tree state */
nmg_to_adrt_regstart, /* region start function */
gcv_region_end, /* region end function */
rt_booltree_leaf_tess, /* leaf func */
(void *)&gcvwriter); /* client data */
/* Release dynamic storage */
nmg_km(the_model);
rt_vlist_cleanup();
db_close(dbip);
dbip = NULL;
bu_free(tribuf[0], "vert");
bu_free(tribuf[1], "vert");
bu_free(tribuf[2], "vert");
@@ -359,17 +331,7 @@ GFile::load_g(const char *filename, int argc, const char *argv[])
void
GFile::closedb()
{
rt_annot_scene_destroy(annotations);
annotations = NULL;
if (tie) {
TIE_FREE(tie);
bu_free(tie, "free tie");
tie = NULL;
}
if (dbip) {
db_close(dbip);
dbip = NULL;
}
bu_free(tie, "free tie");
current_file.clear();
}
@@ -383,3 +345,4 @@ GFile::closedb()
* End:
* ex: shiftwidth=4 tabstop=8
*/
+5 -8
View File
@@ -32,7 +32,6 @@
extern "C" {
#include "bn/tol.h"
#include "raytrace.h"
#include "rt/primitives/annot.h"
#include "rt/tie.h"
#include "adrt.h"
@@ -44,16 +43,13 @@ class GFile : public QObject
Q_OBJECT
public:
~GFile() override;
int load_g(const char *filename, int argc, const char **argv);
void closedb();
struct tie_s *tie = NULL;
struct adrt_mesh_s *meshes = NULL;
struct db_i *dbip = NULL;
struct rt_annot_scene *annotations = NULL;
TIE_3 **tribuf = NULL;
struct tie_s *tie;
struct adrt_mesh_s *meshes;
struct db_i *dbip;
TIE_3 **tribuf;
QString current_file;
};
@@ -70,3 +66,4 @@ class GFile : public QObject
* End:
* ex: shiftwidth=4 tabstop=8
*/
+2 -4
View File
@@ -28,9 +28,6 @@
int
ISSTApp::load_g(const char *filename, int argc, const char *argv[])
{
/* Synchronize with the render thread before GFile releases the old
* annotation scene and TIE data. */
w.canvas->clear_tie();
if (g.load_g(filename, argc, argv)) {
w.statusBar()->showMessage("open failed");
return -1;
@@ -38,7 +35,7 @@ ISSTApp::load_g(const char *filename, int argc, const char *argv[])
// The OpenGL widget manages the rendering, so let it know about the
// TIE data structure associated with the current model
w.canvas->set_tie(g.tie, g.annotations);
w.canvas->set_tie(g.tie);
return 0;
}
@@ -54,3 +51,4 @@ ISSTApp::load_g(const char *filename, int argc, const char *argv[])
* End:
* ex: shiftwidth=4 tabstop=8
*/
+4 -1
View File
@@ -36,14 +36,16 @@
class ISSTApp : public QApplication
{
Q_OBJECT
public:
ISSTApp(int &argc, char *argv[]) :QApplication(argc, argv) {};
~ISSTApp() {};
int load_g(const char *filename, int argc, const char **argv);
GFile g;
ISST_MainWindow w;
GFile g;
};
#endif // ISSTAPP_H
@@ -58,3 +60,4 @@ class ISSTApp : public QApplication
* End:
* ex: shiftwidth=4 tabstop=8
*/
+9 -28
View File
@@ -159,13 +159,8 @@ void TIERenderer::render()
m_grabCond.wait(&m_grabMutex);
QMutexLocker lock(&m_renderMutex);
m_grabMutex.unlock();
/* The GUI may clear a scene while a queued render is waiting for the
* context. Return the context before leaving that stale request. */
if (m_exiting || !tie) {
ctx->moveToThread(qGuiApp->thread());
if (m_exiting)
return;
}
Q_ASSERT(ctx->thread() == QThread::currentThread());
@@ -188,8 +183,7 @@ void TIERenderer::render()
// Core TIE render
render_camera_prep(&camera);
render_camera_render_annotations(&camera, tie, &tile, &buffer_image,
annotations, ADRT_MODEL_UNITS_PER_TIE_UNIT);
render_camera_render(&camera, tie, &tile, &buffer_image);
glDisable(GL_LIGHTING);
@@ -303,31 +297,17 @@ void isstGL::grabContext()
}
void
isstGL::clear_tie()
isstGL::set_tie(struct tie_s *in_tie)
{
m_renderer->lockRenderer();
m_renderer->tie = NULL;
m_renderer->annotations = NULL;
m_renderer->changed = false;
m_renderer->unlockRenderer();
}
void
isstGL::set_tie(struct tie_s *in_tie, struct rt_annot_scene *annotations)
{
m_renderer->lockRenderer();
m_renderer->tie = in_tie;
m_renderer->annotations = annotations;
render_camera_fit_scene(&m_renderer->camera, m_renderer->tie, annotations,
ADRT_MODEL_UNITS_PER_TIE_UNIT);
// Initialize the camera position
VSETALL(m_renderer->camera.pos, m_renderer->tie->radius);
VMOVE(m_renderer->camera.focus, m_renderer->tie->mid);
// Record the initial settings for use in subsequent calculations
VMOVE(m_renderer->camera_pos_init, m_renderer->camera.pos);
VMOVE(m_renderer->camera_focus_init, m_renderer->camera.focus);
m_renderer->changed = true;
m_renderer->unlockRenderer();
VSETALL(m_renderer->camera_pos_init, m_renderer->tie->radius);
VMOVE(m_renderer->camera_focus_init, m_renderer->tie->mid);
// Having just loaded a new TIE scene,
// we need a new image
@@ -389,3 +369,4 @@ void isstGL::save_image() {
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
+2 -3
View File
@@ -77,7 +77,6 @@ class TIERenderer : public QObject, protected QOpenGLFunctions
public:
struct tie_s *tie = NULL; // From parent app
struct rt_annot_scene *annotations = NULL; // Owned by the parent app
struct render_camera_s camera;
vect_t camera_pos_init;
vect_t camera_focus_init;
@@ -114,8 +113,7 @@ class isstGL : public QOpenGLWidget
explicit isstGL(QWidget *parent = nullptr);
~isstGL();
void clear_tie();
void set_tie(struct tie_s *in_tie, struct rt_annot_scene *annotations);
void set_tie(struct tie_s *in_tie);
void save_image();
@@ -155,3 +153,4 @@ class isstGL : public QOpenGLWidget
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
+2 -1
View File
@@ -29,6 +29,7 @@ set(
api.c
centroid.c
check_options.c
contour.cpp
density.cpp
globals.c
inside.c
@@ -68,7 +69,7 @@ set(
cmakefiles(${libanalyze_ignored_files})
# Note - libanalyze_deps is defined by ${BRLCAD_SOURCE_DIR}/src/source_dirs.cmake
brlcad_addlib(libanalyze "${LIBANALYZE_SOURCES}" "" "${CMAKE_CURRENT_BINARY_DIR}"
brlcad_addlib(libanalyze "${LIBANALYZE_SOURCES}" "" "${CMAKE_CURRENT_BINARY_DIR};${EIGEN3_INCLUDE_DIR}"
PUBLIC_LIBS ${libanalyze_deps}
)
set_target_properties(libanalyze PROPERTIES VERSION 20.0.1 SOVERSION 20)
File diff suppressed because it is too large Load Diff
+3 -196
View File
@@ -480,22 +480,6 @@ _nirt_get_resource(struct nirt_state *nss)
}
static void
_nirt_annotation_result_clear(struct nirt_state *nss)
{
delete nss->i->vals->annotation;
nss->i->vals->annotation = NULL;
}
static void
_nirt_annotation_scene_clear(struct nirt_state *nss)
{
rt_annot_scene_destroy(nss->i->annotation_scene);
nss->i->annotation_scene = NULL;
}
int
_nirt_raytrace_prep(struct nirt_state *nss)
{
@@ -533,17 +517,11 @@ _nirt_raytrace_prep(struct nirt_state *nss)
bu_free(attrs, "objs");
return -1;
}
bu_free(objs, "objs");
bu_free(attrs, "objs");
nmsg(nss, "Prepping the geometry...\n");
rt_prep(nss->i->ap->a_rt_i);
_nirt_annotation_scene_clear(nss);
if (nss->i->use_annotations) {
nss->i->annotation_scene = rt_annot_scene_create(nss->i->dbip,
ocnt, objs, &nss->i->ap->a_rt_i->rti_ttol,
&nss->i->ap->a_rt_i->rti_tol);
}
bu_free(objs, "objs");
nmsg(nss, "%s ", (nss->i->active_paths.size() == 1) ? "Object" : "Objects");
for (size_t i = 0; i < nss->i->active_paths.size(); i++) {
if (i == 0) {
@@ -982,17 +960,6 @@ _nirt_print_fmt_substr(struct nirt_state *nss, struct bu_vls *ostr, const char *
nirt_print_key("a", r->a);
nirt_print_key("e", r->e);
if (r->annotation) {
nirt_print_key("annot_path", r->annotation->path.c_str());
nirt_print_key("annot_segment", r->annotation->segment);
nirt_print_key("annot_role", r->annotation->role.c_str());
nirt_print_key("annot_x", r->annotation->point[X] * base2local);
nirt_print_key("annot_y", r->annotation->point[Y] * base2local);
nirt_print_key("annot_z", r->annotation->point[Z] * base2local);
nirt_print_key("annot_d", r->annotation->d * base2local);
nirt_print_key("annot_visible", r->annotation->visible);
}
if (!r->seg || r->seg->type == 0) return;
if (r->seg->type == NIRT_PARTITION_SEG || r->seg->type == NIRT_ALL_SEG) {
@@ -1089,9 +1056,6 @@ _nirt_report(struct nirt_state *nss, char type, struct nirt_output_record *r)
std::vector<std::pair<std::string,std::string> >::iterator f_it;
switch (type) {
case 'a':
fmt_vect = &nss->i->fmt.annotation;
break;
case 'r':
fmt_vect = &nss->i->fmt.ray;
break;
@@ -1127,75 +1091,6 @@ _nirt_report(struct nirt_state *nss, char type, struct nirt_output_record *r)
}
static const char *
_nirt_annotation_role(uint32_t role)
{
switch (role) {
case RT_ANNOT_ROLE_UNSPECIFIED:
return "unspecified";
case RT_ANNOT_ROLE_GEOMETRY:
return "geometry";
case RT_ANNOT_ROLE_TEXT:
return "text";
case RT_ANNOT_ROLE_LEADER:
return "leader";
case RT_ANNOT_ROLE_EXTENSION:
return "extension";
case RT_ANNOT_ROLE_DIMENSION:
return "dimension";
case RT_ANNOT_ROLE_ARROWHEAD:
return "arrowhead";
case RT_ANNOT_ROLE_SYMBOL:
return "symbol";
case RT_ANNOT_ROLE_MASK:
return "mask";
case RT_ANNOT_ROLE_CENTERMARK:
return "centermark";
case RT_ANNOT_ROLE_PLACEHOLDER:
return "placeholder";
case RT_ANNOT_ROLE_TEXT_DECORATION:
return "text-decoration";
default:
return "unknown";
}
}
static void
_nirt_report_annotations(struct nirt_state *nss)
{
const size_t count = rt_annot_scene_query_model(nss->i->annotation_scene,
&nss->i->ap->a_ray, nss->i->first_solid_distance, NULL, 0);
if (!count)
return;
std::vector<struct rt_annot_hit> hits(count);
const size_t found = rt_annot_scene_query_model(nss->i->annotation_scene,
&nss->i->ap->a_ray, nss->i->first_solid_distance, hits.data(),
hits.size());
nirt_seg *saved_segment = nss->i->vals->seg;
nss->i->vals->seg = NULL;
for (size_t i = 0; i < std::min(found, hits.size()); ++i) {
const struct rt_annot_hit &hit = hits[i];
if (hit.segment > (size_t)std::numeric_limits<int>::max()) {
nerr(nss, "Annotation segment index is too large for NIRT reporting\n");
continue;
}
if (!nss->i->vals->annotation)
nss->i->vals->annotation = new nirt_annotation_record;
nirt_annotation_record *record = nss->i->vals->annotation;
record->path = hit.path ? hit.path : "";
record->segment = (int)hit.segment;
record->role = _nirt_annotation_role(hit.role);
VMOVE(record->point, hit.point);
record->d = d_calc(nss, record->point);
record->visible = hit.visible;
_nirt_report(nss, 'a', nss->i->vals);
}
nss->i->vals->seg = saved_segment;
}
/************************
* Raytracing Callbacks *
************************/
@@ -1318,21 +1213,6 @@ _nirt_if_hit(struct application *ap, struct partition *part_head, struct seg *UN
int ev_odd = 1; /* first partition is colored as "odd" */
point_t out_old = VINIT_ZERO;
double d_out_old = 0.0;
nss->i->first_solid_distance = INFINITY;
for (part = part_head->pt_forw; part != part_head; part = part->pt_forw) {
if (part->pt_regionp->reg_aircode)
continue;
if (part->pt_inhit->hit_dist >= 0.0) {
nss->i->first_solid_distance = part->pt_inhit->hit_dist;
break;
}
if (part->pt_outhit->hit_dist >= 0.0) {
nss->i->first_solid_distance = part->pt_outhit->hit_dist;
break;
}
}
nirt_seg *s = new nirt_seg;
if (vals->seg) {
delete vals->seg;
@@ -1669,10 +1549,9 @@ static const struct nirt_cmd_desc nirt_descs[] = {
{ "s", "shoot a ray at the target", NULL },
{ "backout", "back out of model", NULL },
{ "useair", "set/query use of air", "<0|1|2|...>" },
{ "useannot", "set/query annotation reporting", "<0|1>" },
{ "units", "set/query local units", "<mm|cm|m|in|ft>" },
{ "overlap_claims", "set/query overlap rebuilding/retention", "<0|1|2|3>" },
{ "fmt", "set/query output formats", "{arhpfmog} format item item ..." },
{ "fmt", "set/query output formats", "{rhpfmog} format item item ..." },
{ "plotfile", "designate an output file to hold plot data", "file" },
{ "print", "query an output item", "item" },
{ "debug", "set/query nirt debug flags", "[-h] [-l [lib]] [-C [lib]] [-V [lib] [val]] [lib [flag]]" },
@@ -1949,9 +1828,6 @@ _nirt_cmd_shoot(void *ns, int argc, const char **UNUSED(argv))
return -1;
}
_nirt_annotation_result_clear(nss);
nss->i->first_solid_distance = INFINITY;
/* If we have no active rtip, we don't need to prep or shoot */
if (!_nirt_get_rtip(nss)) {
return 0;
@@ -1984,10 +1860,9 @@ _nirt_cmd_shoot(void *ns, int argc, const char **UNUSED(argv))
nss->i->ap->a_ray.r_pt[2] * nss->i->base2local,
V3ARGS(nss->i->ap->a_ray.r_dir));
// TODO - any necessary initialization for data collection by callbacks
_nirt_init_ovlp(nss);
(void)rt_shootray(nss->i->ap);
if (nss->i->use_annotations)
_nirt_report_annotations(nss);
// Undo backout
for (i = 0; i < 3; ++i) {
@@ -2090,45 +1965,6 @@ _nirt_cmd_use_air(void *ns, int argc, const char *argv[])
}
extern "C" int
_nirt_cmd_use_annotations(void *ns, int argc, const char *argv[])
{
struct nirt_state *nss = (struct nirt_state *)ns;
struct bu_vls optparse_msg = BU_VLS_INIT_ZERO;
int enabled = 0;
if (!ns) return -1;
if (argc == 1) {
nout(nss, "use_annotations = %d\n", nss->i->use_annotations);
return 0;
}
if (argc > 2) {
nerr(nss, "Usage: useannot %s\n", _nirt_get_desc_args("useannot"));
return -1;
}
if (bu_opt_int(&optparse_msg, 1, (const char **)&argv[1],
(void *)&enabled) == -1) {
nerr(nss, "Error: bu_opt value read failure: %s\n\nUsage: useannot %s\n",
bu_vls_cstr(&optparse_msg), _nirt_get_desc_args("useannot"));
bu_vls_free(&optparse_msg);
return -1;
}
bu_vls_free(&optparse_msg);
if (enabled != 0 && enabled != 1) {
nerr(nss, "useannot must be set to 0 (off) or 1 (on)\n");
return -1;
}
if (enabled != nss->i->use_annotations) {
nss->i->use_annotations = enabled;
_nirt_annotation_scene_clear(nss);
_nirt_annotation_result_clear(nss);
if (enabled)
nss->i->need_reprep = 1;
}
return 0;
}
extern "C" int
_nirt_cmd_units(void *ns, int argc, const char *argv[])
{
@@ -2249,9 +2085,6 @@ _nirt_cmd_format_output(void *ns, int argc, const char **argv)
// print out current fmt str for the specified type
struct bu_vls ostr = BU_VLS_INIT_ZERO;
switch (type) {
case 'a':
_nirt_print_fmt_str(&ostr, nss->i->fmt.annotation);
break;
case 'r':
_nirt_print_fmt_str(&ostr, nss->i->fmt.ray);
break;
@@ -2358,10 +2191,6 @@ _nirt_cmd_format_output(void *ns, int argc, const char **argv)
* formatting instructions with the new. */
set_fmt:
switch (type) {
case 'a':
nss->i->fmt.annotation.clear();
nss->i->fmt.annotation = fmt_tmp;
break;
case 'r':
nss->i->fmt.ray.clear();
nss->i->fmt.ray = fmt_tmp;
@@ -2714,7 +2543,6 @@ _nirt_cmd_state(void *ns, int argc, const char *argv[])
bu_vls_printf(&dumpstr, "xyz %g %g %g\n", V3ARGS(nss->i->vals->orig));
bu_vls_printf(&dumpstr, "dir %g %g %g\n", V3ARGS(nss->i->vals->dir));
bu_vls_printf(&dumpstr, "useair %d\n", nss->i->use_air);
bu_vls_printf(&dumpstr, "useannot %d\n", nss->i->use_annotations);
bu_vls_printf(&dumpstr, "units %s\n", bu_units_string(nss->i->local2base));
bu_vls_printf(&dumpstr, "overlap_claims ");
switch (nss->i->overlap_claims) {
@@ -2735,8 +2563,6 @@ _nirt_cmd_state(void *ns, int argc, const char *argv[])
break;
}
struct bu_vls ostr = BU_VLS_INIT_ZERO;
_nirt_print_fmt_cmd(&ostr, 'a', nss->i->fmt.annotation);
bu_vls_printf(&dumpstr, "%s", bu_vls_cstr(&ostr));
_nirt_print_fmt_cmd(&ostr, 'r', nss->i->fmt.ray);
bu_vls_printf(&dumpstr, "%s", bu_vls_cstr(&ostr));
_nirt_print_fmt_cmd(&ostr, 'h', nss->i->fmt.head);
@@ -2791,7 +2617,6 @@ const struct bu_cmdtab _libanalyze_nirt_cmds[] = {
{ "state", _nirt_cmd_state},
{ "units", _nirt_cmd_units},
{ "useair", _nirt_cmd_use_air},
{ "useannot", _nirt_cmd_use_annotations},
{ "xyz", _nirt_cmd_target_coor},
{ (char *)NULL, NULL}
};
@@ -2958,14 +2783,6 @@ static const char *nirt_cmd_tbl_defs =
"z_dir, FNOUNIT, Ray direction unit vector z component,"
"a, FNOUNIT, Azimuth,"
"e, FNOUNIT, Elevation,"
"annot_path, STRING, Annotation database path,"
"annot_segment, INT, Annotation segment index,"
"annot_role, STRING, Annotation segment role,"
"annot_x, FLOAT, Annotation hit X coordinate,"
"annot_y, FLOAT, Annotation hit Y coordinate,"
"annot_z, FLOAT, Annotation hit Z coordinate,"
"annot_d, FLOAT, Annotation hit gridplane distance,"
"annot_visible, INT, Annotation hit visibility,"
"x_in, FLOAT, ,"
"y_in, FLOAT, ,"
"z_in, FLOAT, ,"
@@ -3078,7 +2895,6 @@ nirt_init(struct nirt_state *ns)
n->base2local = 0.0;
n->local2base = 0.0;
n->use_air = 0;
n->use_annotations = 0;
n->backout = 1;
n->b_state = false;
@@ -3093,8 +2909,6 @@ nirt_init(struct nirt_state *ns)
BU_GET(n->res_air, struct resource);
n->rtip = RTI_NULL;
n->rtip_air = RTI_NULL;
n->annotation_scene = NULL;
n->first_solid_distance = INFINITY;
n->need_reprep = 1;
BU_GET(n->val_types, struct bu_attribute_value_set);
@@ -3108,7 +2922,6 @@ nirt_init(struct nirt_state *ns)
n->vals->h = 0.0;
n->vals->v = 0.0;
n->vals->d_orig = 0.0;
n->vals->annotation = NULL;
n->vals->seg = NULL;
_nirt_diff_create(ns);
@@ -3212,8 +3025,6 @@ nirt_clear_dbip(struct nirt_state *ns)
{
if (!ns) return -1;
_nirt_annotation_scene_clear(ns);
_nirt_annotation_result_clear(ns);
db_close(ns->i->dbip);
ns->i->dbip = NULL;
@@ -3234,9 +3045,6 @@ void
nirt_destroy(struct nirt_state *ns)
{
if (!ns) return;
_nirt_annotation_scene_clear(ns);
_nirt_annotation_result_clear(ns);
bu_vls_free(&ns->nirt_cmd);
bu_vls_free(ns->i->err);
bu_vls_free(ns->i->msg);
@@ -3249,7 +3057,6 @@ nirt_destroy(struct nirt_state *ns)
db_close(ns->i->dbip);
delete ns->i->vals->seg;
BU_PUT(ns->i->vals, struct nirt_output_record);
BU_PUT(ns->i->res, struct resource);
+1 -17
View File
@@ -83,7 +83,7 @@ extern "C" b_off_t ftello(FILE *);
#define NIRT_OVLP_RETAIN 3
#define NIRT_PRINTF_SPECIFIERS "difeEgGs"
#define NIRT_OUTPUT_TYPE_SPECIFIERS "arhpfmog"
#define NIRT_OUTPUT_TYPE_SPECIFIERS "rhpfmog"
#define HELPFLAG "--print-help"
#define PURPOSEFLAG "--print-purpose"
@@ -274,16 +274,6 @@ class nirt_seg {
}
};
class nirt_annotation_record {
public:
std::string path;
int segment;
std::string role;
point_t point;
fastf_t d;
int visible;
};
/* This record structure doesn't have to correspond exactly to the above list
* of available values, but it needs to retain sufficient information to
* support the ability to generate all of them upon request. */
@@ -296,7 +286,6 @@ struct nirt_output_record {
fastf_t a;
fastf_t e;
struct nirt_overlap ovlp_list;
nirt_annotation_record *annotation;
nirt_seg *seg;
};
@@ -305,7 +294,6 @@ struct nirt_diff_state;
class nirt_fmt_state {
public:
std::vector<std::pair<std::string,std::string> > annotation;
std::vector<std::pair<std::string,std::string> > ray;
std::vector<std::pair<std::string,std::string> > head;
std::vector<std::pair<std::string,std::string> > part;
@@ -315,7 +303,6 @@ class nirt_fmt_state {
std::vector<std::pair<std::string,std::string> > gap;
void clear() {
annotation.clear();
ray.clear();
head.clear();
part.clear();
@@ -360,7 +347,6 @@ struct nirt_state_impl {
int backout;
int overlap_claims;
int use_air;
int use_annotations;
std::set<std::string> attrs; // active attributes
std::vector<std::string> active_paths; // active paths for raytracer
struct nirt_output_record *vals;
@@ -382,8 +368,6 @@ struct nirt_state_impl {
struct resource *res;
struct rt_i *rtip_air;
struct resource *res_air;
struct rt_annot_scene *annotation_scene;
fastf_t first_solid_distance;
int need_reprep;
/* internal format specifier arrays */
File diff suppressed because it is too large Load Diff
+4 -3
View File
@@ -1,9 +1,9 @@
brlcad_addexec(analyze_contour contour.cpp "libanalyze;libwdb;librt;libbg;libbu" TEST)
brlcad_add_test(NAME analyze_contour COMMAND analyze_contour)
brlcad_addexec(analyze_raydiff raydiff.c "libanalyze;librt;libbu" TEST)
brlcad_addexec(analyze_sp solid_partitions.c "libanalyze;librt;libbu" TEST)
brlcad_addexec(analyze_nhit nhit.cpp "libanalyze;librt;libbu" TEST_USESDATA)
brlcad_addexec(analyze_nirt_annotations nirt_annotations.cpp
"libanalyze;libwdb;librt;libbu" TEST_USESDATA)
brlcad_add_test(NAME analyze_nirt_annotations COMMAND analyze_nirt_annotations)
#####################################
# analyze_densities testing #
@@ -16,6 +16,7 @@ brlcad_add_test(NAME analyze_densities_std COMMAND analyze_densities std)
cmakefiles(
CMakeLists.txt
arbs.g
contour.cpp
raydiff.g
)
+425
View File
@@ -0,0 +1,425 @@
/* A N A L Y Z E _ C O N T O U R . C P P
* BRL-CAD
*
* Copyright (c) 2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES ARE DISCLAIMED.
*/
/** @file contour.cpp
*
* Basic topology and resource-limit tests for analyze_mdc().
*/
#include "common.h"
#include <algorithm>
#include <climits>
#include <cmath>
#include <cstdio>
#include <set>
#include <utility>
#include "bu/app.h"
#include "bu/malloc.h"
#include "bg/trimesh.h"
#include "analyze/contour.h"
#include "analyze/polygonize.h"
#include "raytrace.h"
#include "wdb.h"
static constexpr double METRIC_RELATIVE_TOLERANCE = 0.10;
static int failures = 0;
static void
expect(bool condition, const char *message)
{
if (condition)
return;
std::fprintf(stderr, "FAIL: %s\n", message);
failures++;
}
static void
expect_metric(double actual, double expected, const char *object,
const char *metric)
{
double relative_error = std::fabs(actual - expected) / expected;
if (actual >= 0.0 && relative_error <= METRIC_RELATIVE_TOLERANCE)
return;
std::fprintf(stderr,
"FAIL: %s %s is %.17g, expected %.17g (relative error %.2f%%)\n",
object, metric, actual, expected, 100.0 * relative_error);
failures++;
}
static void
check_mesh(struct db_i *dbip, const char *object, int expected_components = 1,
double expected_area = 0.0, double expected_volume = 0.0,
size_t minimum_faces = 4, int expected_euler = INT_MAX)
{
int *faces = NULL;
point_t *vertices = NULL;
size_t face_count = 0;
size_t vertex_count = 0;
struct analyze_mdc_params params = ANALYZE_MDC_PARAMS_DEFAULT;
params.min_depth = 4;
params.max_depth = 8;
params.max_rays = 0;
params.minimum_free_mem = 0;
params.max_time = 0;
params.verbosity = 0;
enum analyze_mdc_status status = analyze_mdc(&faces, &face_count,
&vertices, &vertex_count, object, dbip, &params);
expect(status == ANALYZE_MDC_OK, object);
if (status == ANALYZE_MDC_OK) {
expect(vertex_count >= 4, "contour has vertices");
expect(face_count >= minimum_faces, "contour has expected resolution");
expect(bg_trimesh_solid2(static_cast<int>(vertex_count),
static_cast<int>(face_count),
reinterpret_cast<fastf_t *>(vertices), faces, NULL) == 0,
"contour is a closed oriented manifold");
if (expected_euler != INT_MAX) {
std::set<std::pair<int, int>> edges;
for (size_t face = 0; face < face_count; face++) {
for (size_t corner = 0; corner < 3; corner++) {
int a = faces[3 * face + corner];
int b = faces[3 * face + (corner + 1) % 3];
edges.insert(std::minmax(a, b));
}
}
long long euler = static_cast<long long>(vertex_count) -
static_cast<long long>(edges.size()) +
static_cast<long long>(face_count);
expect(euler == expected_euler,
"contour has the expected Euler characteristic");
}
if (expected_area > 0.0)
expect_metric(bg_trimesh_area(faces, face_count, vertices,
vertex_count), expected_area, object, "surface area");
if (expected_volume > 0.0)
expect_metric(bg_trimesh_volume(faces, face_count, vertices,
vertex_count), expected_volume, object, "volume");
int *face_indices = NULL;
int *component_offsets = NULL;
int components = bg_trimesh_separate(&face_indices,
&component_offsets, faces, static_cast<int>(face_count));
expect(components == expected_components,
"contour has the expected connected components");
if (face_indices)
bu_free(face_indices, "MDC test component faces");
if (component_offsets)
bu_free(component_offsets, "MDC test component offsets");
}
if (faces)
bu_free(faces, "MDC test faces");
if (vertices)
bu_free(vertices, "MDC test vertices");
}
static bool
make_region(struct rt_wdb *wdbp, const char *region, const char *solid)
{
struct wmember member;
BU_LIST_INIT(&member.l);
if (!mk_addmember(solid, &member.l, NULL, WMOP_UNION))
return false;
return mk_lcomb(wdbp, region, &member, 1, NULL, NULL, NULL, 0) == 0;
}
int
main(int UNUSED(argc), const char **argv)
{
bu_setprogname(argv[0]);
struct db_i *dbip = db_create_inmem();
expect(dbip != NULL, "create in-memory database");
if (!dbip)
return 1;
struct rt_wdb *wdbp = wdb_dbopen(dbip, RT_WDB_TYPE_DB_INMEM);
expect(wdbp != NULL, "open in-memory database");
if (!wdbp) {
db_close(dbip);
return 1;
}
constexpr double sphere_radius = 10.0;
constexpr double torus_major_radius = 10.0;
constexpr double torus_minor_radius = 2.5;
constexpr double slender_torus_major_radius = 100.0;
constexpr double slender_torus_minor_radius = 2.0;
constexpr double lower_radius = 1.5;
constexpr double upper_radius = 1.0;
point_t center = VINIT_ZERO;
point_t minimum = {-8.0, -6.0, -4.0};
point_t maximum = {8.0, 6.0, 4.0};
expect(mk_sph(wdbp, "sphere.s", center, sphere_radius) == 0,
"create test sphere");
expect(mk_rpp(wdbp, "box.s", minimum, maximum) == 0,
"create test box");
point_t thin_minimum = {-5.0, -2.5, -0.05};
point_t thin_maximum = {5.0, 2.5, 0.05};
expect(mk_rpp(wdbp, "thin.s", thin_minimum, thin_maximum) == 0,
"create thin-wall test box");
point_t tunnel_minimum = {-10.0, -10.0, -10.0};
point_t tunnel_maximum = {10.0, 10.0, 10.0};
point_t tunnel_base = {0.0, 0.0, -11.0};
vect_t tunnel_height = {0.0, 0.0, 22.0};
expect(mk_rpp(wdbp, "tunnel_outer.s", tunnel_minimum,
tunnel_maximum) == 0, "create tunnel test outer box");
expect(mk_rcc(wdbp, "tunnel_void.s", tunnel_base, tunnel_height,
1.0) == 0, "create tunnel test void");
struct wmember tunnel_members;
BU_LIST_INIT(&tunnel_members.l);
expect(mk_addmember("tunnel_outer.s", &tunnel_members.l, NULL,
WMOP_UNION) != NULL, "add tunnel outer box");
expect(mk_addmember("tunnel_void.s", &tunnel_members.l, NULL,
WMOP_SUBTRACT) != NULL, "subtract tunnel void");
expect(mk_lcomb(wdbp, "tunnel.r", &tunnel_members, 1, NULL, NULL,
NULL, 0) == 0, "create tunnel test region");
vect_t normal = {0.0, 0.0, 1.0};
expect(mk_tor(wdbp, "torus.s", center, normal, torus_major_radius,
torus_minor_radius) == 0,
"create test torus");
expect(mk_tor(wdbp, "slender_torus.s", center, normal,
slender_torus_major_radius, slender_torus_minor_radius) == 0,
"create high-aspect torus");
point_t tgc_base = {-4.0, -3.0, -6.0};
vect_t tgc_height = {2.0, 1.0, 12.0};
vect_t tgc_a = {5.0, 0.0, 0.0};
vect_t tgc_b = {0.0, 3.0, 0.0};
vect_t tgc_c = {2.5, 0.0, 0.0};
vect_t tgc_d = {0.0, 1.5, 0.0};
expect(mk_tgc(wdbp, "tgc.s", tgc_base, tgc_height, tgc_a, tgc_b,
tgc_c, tgc_d) == 0, "create test TGC");
point_t concave_arb[8] = {
{500.0, -500.0, -500.0},
{500.0, 500.0, -500.0},
{500.0, -169.922, -304.688},
{500.0, -500.0, 500.0},
{400.0, -500.0, -500.0},
{400.0, 500.0, -500.0},
{400.0, -169.922, -304.688},
{400.0, -500.0, 500.0}
};
expect(mk_arb8(wdbp, "concave.s",
reinterpret_cast<const fastf_t *>(concave_arb)) == 0,
"create sharp concave ARB");
point_t lower_center = {-8.0, -5.0, -3.0};
point_t upper_center = {9.0, 4.0, 6.0};
expect(mk_sph(wdbp, "lower.s", lower_center, lower_radius) == 0,
"create lower disconnected sphere");
expect(mk_sph(wdbp, "upper.s", upper_center, upper_radius) == 0,
"create upper disconnected sphere");
struct wmember members;
BU_LIST_INIT(&members.l);
expect(mk_addmember("lower.s", &members.l, NULL, WMOP_UNION) != NULL,
"add lower disconnected sphere");
expect(mk_addmember("upper.s", &members.l, NULL, WMOP_UNION) != NULL,
"add upper disconnected sphere");
expect(mk_lcomb(wdbp, "disconnected.r", &members, 1, NULL, NULL, NULL,
0) == 0, "create disconnected region");
constexpr double overlap_radius = 5.0;
constexpr double overlap_offset = 3.0;
point_t overlap_left_center = {-overlap_offset, 0.0, 0.0};
point_t overlap_right_center = {overlap_offset, 0.0, 0.0};
expect(mk_sph(wdbp, "overlap_left.s", overlap_left_center,
overlap_radius) == 0, "create left overlapping sphere");
expect(mk_sph(wdbp, "overlap_right.s", overlap_right_center,
overlap_radius) == 0, "create right overlapping sphere");
expect(make_region(wdbp, "overlap_left.r", "overlap_left.s"),
"create left overlapping region");
expect(make_region(wdbp, "overlap_right.r", "overlap_right.s"),
"create right overlapping region");
struct wmember overlap_members;
BU_LIST_INIT(&overlap_members.l);
expect(mk_addmember("overlap_left.r", &overlap_members.l, NULL,
WMOP_UNION) != NULL, "add left overlapping region");
expect(mk_addmember("overlap_right.r", &overlap_members.l, NULL,
WMOP_UNION) != NULL, "add right overlapping region");
expect(mk_lcomb(wdbp, "overlap.c", &overlap_members, 0, NULL, NULL,
NULL, 0) == 0, "create overlapping-region combination");
vect_t box_size;
VSUB2(box_size, maximum, minimum);
const double sphere_area = 4.0 * M_PI * sphere_radius * sphere_radius;
const double sphere_volume = 4.0 * M_PI * sphere_radius * sphere_radius *
sphere_radius / 3.0;
const double box_area = 2.0 * (box_size[X] * box_size[Y] +
box_size[X] * box_size[Z] + box_size[Y] * box_size[Z]);
const double box_volume = box_size[X] * box_size[Y] * box_size[Z];
vect_t thin_size;
VSUB2(thin_size, thin_maximum, thin_minimum);
const double thin_area = 2.0 * (thin_size[X] * thin_size[Y] +
thin_size[X] * thin_size[Z] + thin_size[Y] * thin_size[Z]);
const double thin_volume =
thin_size[X] * thin_size[Y] * thin_size[Z];
const double torus_area = 4.0 * M_PI * M_PI * torus_major_radius *
torus_minor_radius;
const double torus_volume = 2.0 * M_PI * M_PI * torus_major_radius *
torus_minor_radius * torus_minor_radius;
const double slender_torus_area = 4.0 * M_PI * M_PI *
slender_torus_major_radius * slender_torus_minor_radius;
const double disconnected_area = 4.0 * M_PI *
(lower_radius * lower_radius + upper_radius * upper_radius);
const double disconnected_volume = 4.0 * M_PI *
(lower_radius * lower_radius * lower_radius +
upper_radius * upper_radius * upper_radius) / 3.0;
const double overlap_distance = 2.0 * overlap_offset;
const double overlap_cap_height = overlap_radius -
0.5 * overlap_distance;
const double overlap_intersection_volume = M_PI *
(4.0 * overlap_radius + overlap_distance) *
std::pow(2.0 * overlap_radius - overlap_distance, 2.0) / 12.0;
const double overlap_area = 8.0 * M_PI * overlap_radius *
overlap_radius - 4.0 * M_PI * overlap_radius * overlap_cap_height;
const double overlap_volume = 8.0 * M_PI * overlap_radius *
overlap_radius * overlap_radius / 3.0 -
overlap_intersection_volume;
check_mesh(dbip, "sphere.s", 1, sphere_area, sphere_volume);
check_mesh(dbip, "box.s", 1, box_area, box_volume);
check_mesh(dbip, "thin.s", 1, thin_area, thin_volume, 10000);
check_mesh(dbip, "torus.s", 1, torus_area, torus_volume, 4, 0);
check_mesh(dbip, "slender_torus.s", 1, slender_torus_area,
0.0, 4, 0);
check_mesh(dbip, "tunnel.r", 1, 0.0, 0.0, 4, 0);
check_mesh(dbip, "tgc.s");
check_mesh(dbip, "concave.s");
check_mesh(dbip, "disconnected.r", 2, disconnected_area,
disconnected_volume);
check_mesh(dbip, "overlap.c", 1, overlap_area, overlap_volume);
{
int *coarse_faces = NULL;
point_t *coarse_vertices = NULL;
size_t coarse_face_count = 0;
size_t coarse_vertex_count = 0;
struct analyze_mdc_params coarse = ANALYZE_MDC_PARAMS_DEFAULT;
coarse.min_depth = 3;
coarse.max_depth = 3;
coarse.max_rays = 50000;
coarse.minimum_free_mem = 0;
coarse.max_time = 0;
enum analyze_mdc_status coarse_status = analyze_mdc(&coarse_faces,
&coarse_face_count, &coarse_vertices, &coarse_vertex_count,
"tunnel.r", dbip, &coarse);
expect(coarse_status == ANALYZE_MDC_AMBIGUOUS,
"under-resolved tunnel requests refinement");
expect(!coarse_faces && !coarse_vertices && !coarse_face_count &&
coarse_vertex_count == 0,
"under-resolved tunnel leaves outputs empty");
if (coarse_faces)
bu_free(coarse_faces, "coarse MDC test faces");
if (coarse_vertices)
bu_free(coarse_vertices, "coarse MDC test vertices");
}
{
int *compatibility_faces = NULL;
point_t *compatibility_vertices = NULL;
int compatibility_face_count = 0;
int compatibility_vertex_count = 0;
point_t unused_seed = VINIT_ZERO;
struct analyze_polygonize_params compatibility =
ANALYZE_POLYGONIZE_PARAMS_DEFAULT;
compatibility.max_time = 0;
compatibility.max_cycle_time = 0;
compatibility.minimum_free_mem = 0;
int status = analyze_polygonize(&compatibility_faces,
&compatibility_face_count, &compatibility_vertices,
&compatibility_vertex_count, 1.0, unused_seed, "sphere.s",
dbip, &compatibility);
expect(status == 0, "polygonize compatibility interface");
if (status == 0) {
expect(compatibility_face_count >= 4,
"compatibility contour has faces");
expect(compatibility_vertex_count >= 4,
"compatibility contour has vertices");
expect(bg_trimesh_solid2(compatibility_vertex_count,
compatibility_face_count,
reinterpret_cast<fastf_t *>(compatibility_vertices),
compatibility_faces, NULL) == 0,
"compatibility contour is a closed oriented manifold");
}
if (compatibility_faces)
bu_free(compatibility_faces, "compatibility test faces");
if (compatibility_vertices)
bu_free(compatibility_vertices, "compatibility test vertices");
compatibility.max_time = 1;
compatibility.time_offset = 1;
expect(analyze_polygonize(&compatibility_faces,
&compatibility_face_count, &compatibility_vertices,
&compatibility_vertex_count, 1.0, unused_seed, "sphere.s",
dbip, &compatibility) == 2,
"compatibility interface preserves timeout status");
expect(!compatibility_faces && !compatibility_vertices &&
!compatibility_face_count && !compatibility_vertex_count,
"compatibility timeout leaves outputs empty");
}
int *faces = NULL;
point_t *vertices = NULL;
size_t face_count = 0;
size_t vertex_count = 0;
struct analyze_mdc_params limited = ANALYZE_MDC_PARAMS_DEFAULT;
limited.min_depth = 4;
limited.max_depth = 4;
limited.max_rays = 1;
limited.minimum_free_mem = 0;
expect(analyze_mdc(&faces, &face_count, &vertices, &vertex_count,
"sphere.s", dbip, &limited) == ANALYZE_MDC_RAY_LIMIT,
"ray limit is enforced during sampling");
expect(!faces && !vertices && !face_count && !vertex_count,
"failure leaves outputs empty");
expect(analyze_mdc(NULL, &face_count, &vertices, &vertex_count,
"sphere.s", dbip, NULL) == ANALYZE_MDC_INVALID_INPUT,
"invalid output pointer is rejected");
db_close(dbip);
return failures ? 1 : 0;
}
/*
* Local Variables:
* mode: C++
* tab-width: 8
* c-basic-offset: 4
* indent-tabs-mode: t
* c-file-style: "stroustrup"
* End:
* ex: shiftwidth=4 tabstop=8
*/
-191
View File
@@ -1,191 +0,0 @@
/* N I R T _ A N N O T A T I O N S . C P P
* BRL-CAD
*
* Copyright (c) 2026 United States Government as represented by the
* U.S. Army Research Laboratory.
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
#include "common.h"
#include <cstdio>
#include <cstdlib>
#include "analyze.h"
#include "bu/app.h"
#include "bu/file.h"
#include "bu/malloc.h"
#include "raytrace.h"
#include "wdb.h"
static constexpr fastf_t FRONT_ANNOTATION_X = 18.0;
static constexpr fastf_t REAR_ANNOTATION_X = 10.0;
static constexpr fastf_t SCREEN_ANNOTATION_X = 19.0;
static constexpr fastf_t OCCLUDER_MINIMUM_X = 15.0;
static constexpr fastf_t OCCLUDER_MAXIMUM_X = 16.0;
static constexpr fastf_t RAY_ORIGIN_X = 20.0;
static constexpr fastf_t TEST_HALF_EXTENT = 1.0;
static int
capture_output(struct nirt_state *state, void *data)
{
struct bu_vls current = BU_VLS_INIT_ZERO;
struct bu_vls *captured = (struct bu_vls *)data;
nirt_log(&current, state, NIRT_OUT);
bu_vls_vlscat(captured, &current);
bu_vls_free(&current);
return 0;
}
static void
write_annotation(struct rt_wdb *wdbp, const char *name, fastf_t x,
bool screen_space)
{
struct rt_annot_internal annotation = {};
struct line_seg line = {};
struct rt_annot_seg_style style = {};
int reverse = 0;
void *segment = &line;
point2d_t vertices[2] = {{0.0, 0.0}, {TEST_HALF_EXTENT, 0.0}};
annotation.magic = RT_ANNOT_INTERNAL_MAGIC;
VSET(annotation.V, x, 0.0, 0.0);
annotation.flags = screen_space ? RT_ANNOT_SCREEN_SPACE :
RT_ANNOT_MODEL_SPACE;
VSET(annotation.u_vec, 0.0, 1.0, 0.0);
VSET(annotation.v_vec, 0.0, 0.0, 1.0);
annotation.vert_count = 2;
annotation.verts = vertices;
annotation.ant.count = 1;
annotation.ant.reverse = &reverse;
annotation.ant.segments = &segment;
annotation.styles = &style;
line.magic = CURVE_LSEG_MAGIC;
line.start = 0;
line.end = 1;
style.role = RT_ANNOT_ROLE_LEADER;
style.line_pattern = RT_ANNOT_LINE_CONTINUOUS;
if (rt_annot_validate(&annotation, NULL) ||
mk_annot(wdbp, name, &annotation) < 0)
bu_exit(EXIT_FAILURE, "unable to write %s\n", name);
}
static void
clear_standard_formats(struct nirt_state *state)
{
const char *commands[] = {
"fmt r \"\"", "fmt h \"\"", "fmt p \"\"", "fmt f \"\"",
"fmt m \"\"", "fmt o \"\"", "fmt g \"\""
};
for (size_t i = 0; i < sizeof(commands) / sizeof(commands[0]); ++i)
if (nirt_exec(state, commands[i]))
bu_exit(EXIT_FAILURE, "NIRT rejected command: %s\n", commands[i]);
}
static void
get_output(struct bu_vls *output, struct bu_vls *captured)
{
bu_vls_sprintf(output, "%s", bu_vls_cstr(captured));
bu_vls_trunc(captured, 0);
}
int
main(int argc, char **argv)
{
char path[MAXPATHLEN];
struct db_i *dbip;
struct rt_wdb *wdbp;
struct nirt_state *state;
struct bu_vls captured = BU_VLS_INIT_ZERO;
struct bu_vls output = BU_VLS_INIT_ZERO;
struct wmember members;
point_t minimum, maximum;
bu_setprogname(argv[0]);
if (argc != 1)
return EXIT_FAILURE;
{
FILE *fp = bu_temp_file(path, sizeof(path));
if (!fp)
bu_exit(EXIT_FAILURE, "unable to create temporary database path\n");
fclose(fp);
}
dbip = db_create(path, 5);
if (!dbip)
bu_exit(EXIT_FAILURE, "unable to create temporary database\n");
wdbp = wdb_dbopen(dbip, RT_WDB_TYPE_DB_DISK);
if (!wdbp)
bu_exit(EXIT_FAILURE, "unable to open temporary database for writing\n");
write_annotation(wdbp, "front.annot", FRONT_ANNOTATION_X, false);
write_annotation(wdbp, "rear.annot", REAR_ANNOTATION_X, false);
write_annotation(wdbp, "screen.annot", SCREEN_ANNOTATION_X, true);
VSET(minimum, OCCLUDER_MINIMUM_X, -TEST_HALF_EXTENT,
-TEST_HALF_EXTENT);
VSET(maximum, OCCLUDER_MAXIMUM_X, TEST_HALF_EXTENT,
TEST_HALF_EXTENT);
if (mk_rpp(wdbp, "occluder.s", minimum, maximum) < 0)
bu_exit(EXIT_FAILURE, "unable to write occluder\n");
BU_LIST_INIT(&members.l);
if (!mk_addmember("occluder.s", &members.l, NULL, WMOP_UNION) ||
mk_lcomb(wdbp, "occluder.r", &members, 1, NULL, NULL, NULL, 0))
bu_exit(EXIT_FAILURE, "unable to write occluding region\n");
BU_GET(state, struct nirt_state);
if (nirt_init(state))
bu_exit(EXIT_FAILURE, "unable to initialize NIRT\n");
nirt_udata(state, &captured);
nirt_hook(state, capture_output, NIRT_OUT);
if (nirt_exec(state,
"draw front.annot rear.annot screen.annot occluder.r") ||
nirt_init_dbip(state, dbip))
bu_exit(EXIT_FAILURE, "unable to prepare NIRT test database\n");
clear_standard_formats(state);
if (nirt_exec(state,
"fmt a \"%s|%d|%s|%.1f|%.1f|%d\\n\" annot_path annot_segment annot_role annot_x annot_d annot_visible"))
bu_exit(EXIT_FAILURE, "unable to set annotation report format\n");
struct bu_vls shot = BU_VLS_INIT_ZERO;
bu_vls_sprintf(&shot, "backout 0;xyz %g 0 0;dir -1 0 0;s",
RAY_ORIGIN_X);
if (nirt_exec(state, bu_vls_cstr(&shot)))
bu_exit(EXIT_FAILURE, "unable to shoot default NIRT ray\n");
bu_vls_free(&shot);
get_output(&output, &captured);
if (bu_vls_strlen(&output))
bu_exit(EXIT_FAILURE,
"annotations were reported without useannot: %s\n",
bu_vls_cstr(&output));
if (nirt_exec(state, "useannot 1;s"))
bu_exit(EXIT_FAILURE, "unable to shoot annotation NIRT ray\n");
get_output(&output, &captured);
struct bu_vls expected = BU_VLS_INIT_ZERO;
bu_vls_sprintf(&expected,
"/front.annot|0|leader|%.1f|%.1f|1\n"
"/rear.annot|0|leader|%.1f|%.1f|0\n",
FRONT_ANNOTATION_X, FRONT_ANNOTATION_X,
REAR_ANNOTATION_X, REAR_ANNOTATION_X);
if (!BU_STR_EQUAL(bu_vls_cstr(&output), bu_vls_cstr(&expected)))
bu_exit(EXIT_FAILURE, "unexpected annotation report:\n%s",
bu_vls_cstr(&output));
bu_vls_free(&expected);
nirt_destroy(state);
BU_PUT(state, struct nirt_state);
bu_vls_free(&captured);
bu_vls_free(&output);
db_close(dbip);
bu_file_delete(path);
return EXIT_SUCCESS;
}
+6 -12
View File
@@ -419,7 +419,7 @@ protected:
ListNode* AllocListNode();
void FreeListNode(ListNode* a_listNode);
bool Overlap(Rect* a_rectA, Rect* a_rectB) const;
bool Intersect(const Rect* a_rect, const Ray* a_ray) const;
bool Intersect(Rect* a_rect, Ray* a_ray) const;
void ReInsert(Node* a_node, ListNode** a_listNode);
bool Search(Node* a_node, Rect* a_rect, int& a_foundCount, std::function<bool(const DataType&, void *)> callback, void *a_context) const;
void RemoveAllRec(Node* a_node);
@@ -433,15 +433,14 @@ protected:
size_t CheckNodes(Node *a_nodeA, Node *a_nodeB, std::set<DataType> *a_result, std::set<DataType> *b_result);
size_t CheckNodes(Node *a_nodeA, Node *a_nodeB, std::set<std::pair<DataType, DataType>> *result);
size_t IsectNode(const Node *a_node, const Ray *a_ray,
std::set<DataType> *result) const;
size_t IsectNode(Node *a_node, Ray *a_ray, std::set<DataType> *result);
Node* m_root = nullptr; ///< Root of tree
ElementTypeReal m_unitSphereVolume = kElementTypeRealZero; ///< Unit sphere constant for required number of dimensions
public:
// Find the leaves intersected by a ray, returning the data from the leaves in a set.
size_t Intersects(const Ray *a_ray, std::set<DataType> *result) const;
size_t Intersects(Ray *a_ray, std::set<DataType> *result);
void plot(const char *fname);
void plot2d(const char *fname);
@@ -1552,7 +1551,7 @@ bool RTREE_QUAL::Overlap(Rect* a_rectA, Rect* a_rectB) const
// Decide whether a ray intersect a Rect.
RTREE_TEMPLATE
bool RTREE_QUAL::Intersect(const Rect* a_rect, const Ray* a_ray) const
bool RTREE_QUAL::Intersect(Rect* a_rect, Ray* a_ray) const
{
RTreeAssert(a_rect);
if (kNumDimensions != 3) return false;
@@ -1686,8 +1685,7 @@ size_t RTREE_QUAL::Overlaps(RTree &other, std::set<std::pair<DataType, DataType>
RTREE_TEMPLATE
size_t RTREE_QUAL::IsectNode(const Node *a_node, const Ray *a_ray,
std::set<DataType> *result) const
size_t RTREE_QUAL::IsectNode(Node *a_node, Ray *a_ray, std::set<DataType> *result)
{
size_t ocnt = 0;
for (int index = 0; index < a_node->m_count; ++index) {
@@ -1705,8 +1703,7 @@ size_t RTREE_QUAL::IsectNode(const Node *a_node, const Ray *a_ray,
// Loosely based on the idea from the openNURBS code to search two R-trees for all pairs elements whose bounding boxes overlap.
RTREE_TEMPLATE
size_t RTREE_QUAL::Intersects(const Ray *a_ray,
std::set<DataType> *result) const
size_t RTREE_QUAL::Intersects(Ray *a_ray, std::set<DataType> *result)
{
if (!m_root) return 0;
size_t ovlp_cnt = IsectNode(m_root, a_ray, result);
@@ -1803,9 +1800,6 @@ void RTREE_QUAL::plot2d(const char *fname)
}
#undef BB_PLOT2D
#undef BB_PLOT
#undef TREE_LEAF_FACE_3D
#undef RTREE_TEMPLATE
#undef RTREE_QUAL
+796 -134
View File
@@ -8,8 +8,8 @@
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* This library 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.
*
@@ -19,170 +19,832 @@
*/
/** @file spsr.cpp
*
* Interface to Adaptive Multigrid Solvers for Screened Poisson Surface Reconstruction
* Compatible with mkazhdan/PoissonRecon API (v18.x+).
*
* Screened Poisson surface reconstruction for fixed and adaptive oriented
* point sets.
*/
#include "common.h"
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstring>
#include <exception>
#include <limits>
#include <memory>
#include <mutex>
#include <unordered_map>
#include <utility>
#include <vector>
#include "vmath.h"
#include "bu/log.h"
#include "bu/malloc.h"
#include "bg/spsr.h"
#include "RTree.h"
#if defined(__GNUC__) && !defined(__clang__)
# pragma GCC diagnostic push /* start new diagnostic pragma */
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wall"
#elif defined(__clang__)
# pragma clang diagnostic push /* start new diagnostic pragma */
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Weverything"
#endif
#include "SPSR/Reconstructors.h"
#if defined(__GNUC__) && !defined(__clang__)
# pragma GCC diagnostic pop /* end ignoring warnings */
# pragma GCC diagnostic pop
#elif defined(__clang__)
# pragma clang diagnostic pop /* end ignoring warnings */
# pragma clang diagnostic pop
#endif
using namespace PoissonRecon;
// Input stream for oriented samples: implements `read` for coordinates and normals
template<typename Real, unsigned int Dim>
struct PtStream : public Reconstructor::InputOrientedSampleStream<Real, Dim>
{
PtStream(const point_t *ipnts, const vect_t *inorms, int cnt)
: _size(cnt), _current(0), _input_pnts(ipnts), _input_nrmls(inorms) {}
void reset(void) { _current = 0; }
bool read(Point<Real, Dim> &p, Point<Real, Dim> &n)
{
if (_current < _size) {
for (size_t d = 0; d < Dim; d++)
p[d] = _input_pnts[_current][d];
for (size_t d = 0; d < Dim; d++)
n[d] = _input_nrmls[_current][d];
_current++;
return true;
}
return false;
}
protected:
unsigned int _size, _current;
const point_t *_input_pnts;
const vect_t *_input_nrmls;
namespace {
using clock_type = std::chrono::steady_clock;
using real_type = fastf_t;
constexpr size_t SPSR_MAX_HINTS = 4096;
constexpr size_t SPSR_MIN_NEIGHBORS = 4;
constexpr double SPSR_NORMAL_ANGLE_DEGREES = 15.0;
constexpr double SPSR_DEDUP_FRACTION = 0.25;
constexpr int SPSR_MAX_DEPTH = 30;
struct spsr_mesh {
std::vector<int> faces;
std::vector<real_type> vertices;
};
// Output face stream: must implement write() and size()
template <typename Index>
struct PolygonStream : public Reconstructor::OutputFaceStream<2>
template<typename Real, unsigned int Dim>
struct point_stream : public Reconstructor::InputOrientedSampleStream<Real, Dim>
{
PolygonStream(std::vector<std::vector<Index>> &polygonStream) : _polygons(polygonStream) {}
size_t size(void) const { return _polygons.size(); }
point_stream(const std::vector<struct bg_3d_spsr_sample> &samples)
: current(0), input(samples)
{
}
void reset(void)
{
current = 0;
}
bool read(Point<Real, Dim> &point, Point<Real, Dim> &normal)
{
if (current >= input.size())
return false;
for (size_t dimension = 0; dimension < Dim; dimension++) {
point[dimension] = input[current].point[dimension];
normal[dimension] = input[current].normal[dimension];
}
current++;
return true;
}
private:
size_t current;
const std::vector<struct bg_3d_spsr_sample> &input;
};
template<typename Index>
struct polygon_stream : public Reconstructor::OutputFaceStream<2>
{
polygon_stream(std::vector<std::vector<Index>> &output) : polygons(output)
{
}
size_t size(void) const
{
return polygons.size();
}
size_t write(const std::vector<node_index_type> &polygon)
{
std::vector<Index> poly(polygon.size());
for (size_t i = 0; i < polygon.size(); i++) poly[i] = (Index)polygon[i];
_polygons.push_back(poly);
return _polygons.size() - 1;
std::vector<Index> converted(polygon.size());
for (size_t i = 0; i < polygon.size(); i++)
converted[i] = static_cast<Index>(polygon[i]);
polygons.push_back(std::move(converted));
return polygons.size() - 1;
}
protected:
std::vector<std::vector<Index>> &_polygons;
private:
std::vector<std::vector<Index>> &polygons;
};
// Output vertex stream: must implement write() and size()
template <typename Real, unsigned int Dim>
struct VertexStream : public Reconstructor::OutputLevelSetVertexStream<Real, Dim>
template<typename Real, unsigned int Dim>
struct vertex_stream : public Reconstructor::OutputLevelSetVertexStream<Real, Dim>
{
VertexStream(std::vector<Real> &vCoordinates) : _vCoordinates(vCoordinates) {}
size_t size(void) const { return _vCoordinates.size() / Dim; }
size_t write(const Point<Real, Dim> &p, const Point<Real, Dim> &, const Real &)
vertex_stream(std::vector<Real> &output) : coordinates(output)
{
for (unsigned int d = 0; d < Dim; d++) _vCoordinates.push_back(p[d]);
return _vCoordinates.size() / Dim - 1;
}
protected:
std::vector<Real> &_vCoordinates;
size_t size(void) const
{
return coordinates.size() / Dim;
}
size_t write(const Point<Real, Dim> &point, const Point<Real, Dim> &,
const Real &)
{
for (unsigned int dimension = 0; dimension < Dim; dimension++)
coordinates.push_back(point[dimension]);
return coordinates.size() / Dim - 1;
}
private:
std::vector<Real> &coordinates;
};
extern "C" int
bg_3d_spsr(int **faces, int *num_faces, point_t **points, int *num_pnts,
const point_t *input_points_3d, const vect_t *input_normals_3d,
int num_input_pnts, struct bg_3d_spsr_opts *spsr_opts)
static double
elapsed_seconds(const clock_type::time_point &start)
{
using Real = fastf_t;
static const unsigned int FEMSig = FEMDegreeAndBType<Reconstructor::Poisson::DefaultFEMDegree, Reconstructor::Poisson::DefaultFEMBoundary>::Signature;
using FEMSigs = IsotropicUIntPack<3, FEMSig>;
// Set up multithreading
PoissonRecon::ThreadPool::ParallelizationType = PoissonRecon::ThreadPool::ASYNC;
// Solver and extraction parameters
Reconstructor::Poisson::SolutionParameters<Real> solverParams;
solverParams.verbose = false;
solverParams.depth = (spsr_opts) ? spsr_opts->depth : 8;
solverParams.fullDepth = (spsr_opts) ? spsr_opts->full_depth : 11;
solverParams.samplesPerNode = (spsr_opts) ? spsr_opts->samples_per_node : 1.5;
solverParams.exactInterpolation = true;
Reconstructor::LevelSetExtractionParameters extractionParams;
extractionParams.forceManifold = true;
extractionParams.linearFit = false;
extractionParams.polygonMesh = false;
extractionParams.verbose = false;
PtStream<Real, 3> vstream(input_points_3d, input_normals_3d, num_input_pnts);
using Implicit = Reconstructor::Implicit<Real, 3, FEMSigs>;
using Solver = Reconstructor::Poisson::Solver<Real, 3, FEMSigs>;
Implicit *implicit = Solver::Solve(vstream, solverParams);
if (!implicit) {
bu_log("PoissonRecon: Solver::Solve failed\n");
return -1;
}
std::vector<std::vector<int>> polygons;
std::vector<Real> vCoordinates;
PolygonStream<int> pStream(polygons);
VertexStream<Real, 3> vStream(vCoordinates);
implicit->extractLevelSet(vStream, pStream, extractionParams);
*num_faces = (int)(polygons.size());
*num_pnts = (int)(vCoordinates.size() / 3);
bu_log("Point cnt: %d\n", *num_pnts);
bu_log("Face cnt: %d\n", *num_faces);
// Allocate output arrays
(*faces) = (int *)bu_calloc(*num_faces * 3, sizeof(int), "faces array");
(*points) = (point_t *)bu_calloc(*num_pnts, sizeof(point_t), "points array");
// Copy faces (triangulated output expected)
for (int i = 0; i < *num_faces; i++) {
if (polygons[i].size() != 3) {
bu_log("Warning: polygon %d is not a triangle (has %zu vertices)\n", i, polygons[i].size());
// TODO - triangulate if we don't have a triangle.
continue;
}
(*faces)[3*i+0] = polygons[i][0];
(*faces)[3*i+1] = polygons[i][1];
(*faces)[3*i+2] = polygons[i][2];
}
// Copy points
for (int i = 0; i < *num_pnts; i++) {
(*points)[i][X] = vCoordinates[3*i+0];
(*points)[i][Y] = vCoordinates[3*i+1];
(*points)[i][Z] = vCoordinates[3*i+2];
}
delete implicit;
return 0;
return std::chrono::duration<double>(clock_type::now() - start).count();
}
static bool
finite_vector(const fastf_t *vector)
{
return std::isfinite(vector[X]) && std::isfinite(vector[Y]) &&
std::isfinite(vector[Z]);
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8 cino=N-s
static bool
valid_options(const struct bg_3d_spsr_opts &options)
{
if (options.degree != BG_3D_SPSR_DEFAULT_DEGREE ||
options.btype != BG_3D_SPSR_BOUNDARY_NEUMANN ||
options.max_memory_GB != BG_3D_SPSR_DEFAULT_MAX_MEM ||
options.threads != BG_3D_SPSR_DEFAULT_THREADS ||
!NEAR_ZERO(options.confidence, SMALL_FASTF) ||
!NEAR_ZERO(options.confidence_bias, SMALL_FASTF))
return false;
if (options.depth < 1 || options.depth > SPSR_MAX_DEPTH ||
options.kerneldepth < 0 || options.iterations < 0 ||
options.full_depth < 0 || options.base_depth < 0 ||
options.baseVcycles < 0 || options.samples_per_node <= 0.0 ||
options.scale < 1.0 || options.width < 0.0 ||
options.cgsolver_accuracy <= 0.0 || options.point_weight < 0.0)
return false;
return options.nonManifold >= 0 && options.nonManifold <= 1 &&
options.linearFit >= 0 && options.linearFit <= 1 &&
options.exact >= 0 && options.exact <= 1;
}
static void
set_solver_options(
Reconstructor::Poisson::SolutionParameters<real_type> &solver,
Reconstructor::LevelSetExtractionParameters &extraction,
const struct bg_3d_spsr_opts &options)
{
solver.depth = static_cast<unsigned int>(options.depth);
solver.kernelDepth = options.kerneldepth ?
static_cast<unsigned int>(options.kerneldepth) :
static_cast<unsigned int>(-1);
solver.iters = options.iterations ?
static_cast<unsigned int>(options.iterations) : 8u;
solver.fullDepth = options.full_depth ?
static_cast<unsigned int>(options.full_depth) :
std::min(5u, solver.depth);
solver.baseDepth = options.base_depth ?
static_cast<unsigned int>(options.base_depth) :
static_cast<unsigned int>(-1);
solver.baseVCycles = options.baseVcycles ?
static_cast<unsigned int>(options.baseVcycles) : 1u;
solver.samplesPerNode = options.samples_per_node;
solver.scale = options.scale;
solver.width = options.width;
solver.cgSolverAccuracy = options.cgsolver_accuracy;
solver.pointWeight = options.point_weight;
solver.exactInterpolation = options.exact != 0;
solver.confidence = false;
solver.verbose = false;
solver.showResidual = false;
extraction.forceManifold = options.nonManifold == 0;
extraction.linearFit = options.linearFit != 0;
extraction.polygonMesh = false;
extraction.verbose = false;
}
static fastf_t
sample_extent(const std::vector<struct bg_3d_spsr_sample> &samples)
{
point_t minimum;
point_t maximum;
VSETALL(minimum, INFINITY);
VSETALL(maximum, -INFINITY);
for (const auto &sample : samples)
VMINMAX(minimum, maximum, sample.point);
return DIST_PNT_PNT(minimum, maximum);
}
class sample_set
{
public:
sample_set(fastf_t tolerance, size_t limit) :
distance_tolerance(tolerance), distance_tolerance_sq(tolerance * tolerance),
point_limit(limit)
{
}
bool append(const struct bg_3d_spsr_sample &input)
{
if (!finite_vector(input.point) || !finite_vector(input.normal))
return false;
struct bg_3d_spsr_sample sample = input;
fastf_t normal_length = MAGNITUDE(sample.normal);
if (!std::isfinite(normal_length) || normal_length <= VUNITIZE_TOL)
return false;
VSCALE(sample.normal, sample.normal, 1.0 / normal_length);
double minimum[3];
double maximum[3];
for (size_t dimension = 0; dimension < 3; dimension++) {
minimum[dimension] = sample.point[dimension] - distance_tolerance;
maximum[dimension] = sample.point[dimension] + distance_tolerance;
}
bool duplicate = false;
index.Search(minimum, maximum,
[&sample, this, &duplicate](const size_t &candidate, void *) {
if (DIST_PNT_PNT_SQ(sample.point, values[candidate].point) <=
distance_tolerance_sq) {
duplicate = true;
return false;
}
return true;
}, NULL);
if (duplicate || (point_limit && values.size() >= point_limit))
return false;
size_t sample_index = values.size();
values.push_back(sample);
double point[3] = {
sample.point[X], sample.point[Y], sample.point[Z]
};
index.Insert(point, point, sample_index);
return true;
}
const std::vector<struct bg_3d_spsr_sample> &samples(void) const
{
return values;
}
bool full(void) const
{
return point_limit && values.size() >= point_limit;
}
private:
fastf_t distance_tolerance;
fastf_t distance_tolerance_sq;
size_t point_limit;
std::vector<struct bg_3d_spsr_sample> values;
RTree<size_t, double, 3> index;
};
static void
append_hint(std::vector<struct bg_3d_spsr_refinement_hint> &hints,
const point_t point, const vect_t normal, fastf_t error,
unsigned int reasons)
{
struct bg_3d_spsr_refinement_hint hint = {};
VMOVE(hint.point, point);
VMOVE(hint.normal, normal);
hint.error = error;
hint.reasons = reasons;
hints.push_back(hint);
}
template<typename Implicit>
static void
sample_hints(std::vector<struct bg_3d_spsr_refinement_hint> &hints,
const std::vector<struct bg_3d_spsr_sample> &samples,
const Implicit &implicit, fastf_t feature_size)
{
const fastf_t normal_dot_limit =
std::cos(SPSR_NORMAL_ANGLE_DEGREES * DEG2RAD);
typename Implicit::Evaluator evaluator = implicit.evaluator();
for (const auto &sample : samples) {
Point<real_type, 3> point;
for (size_t dimension = 0; dimension < 3; dimension++)
point[dimension] = sample.point[dimension];
try {
Point<real_type, 3> gradient = evaluator.grad(point);
real_type gradient_length = std::sqrt(
gradient[0] * gradient[0] + gradient[1] * gradient[1] +
gradient[2] * gradient[2]);
unsigned int reasons = 0;
fastf_t error = feature_size;
vect_t normal;
VSET(normal, gradient[0], gradient[1], gradient[2]);
if (gradient_length <= VUNITIZE_TOL) {
reasons = BG_3D_SPSR_REFINE_RESIDUAL |
BG_3D_SPSR_REFINE_NORMAL;
VSETALL(normal, 0.0);
} else {
fastf_t residual = std::fabs(
evaluator(point) - implicit.isoValue) / gradient_length;
fastf_t normal_dot = std::fabs(
VDOT(sample.normal, normal) / gradient_length);
if (residual > feature_size) {
reasons |= BG_3D_SPSR_REFINE_RESIDUAL;
error = residual;
}
if (normal_dot < normal_dot_limit) {
reasons |= BG_3D_SPSR_REFINE_NORMAL;
error = std::max(error,
feature_size * (1.0 + normal_dot_limit - normal_dot));
}
VSCALE(normal, normal, 1.0 / gradient_length);
}
if (reasons)
append_hint(hints, sample.point, normal, error, reasons);
} catch (const std::exception &) {
append_hint(hints, sample.point, sample.normal,
2.0 * feature_size, BG_3D_SPSR_REFINE_RESIDUAL);
}
}
}
static void
density_hints(std::vector<struct bg_3d_spsr_refinement_hint> &hints,
const std::vector<struct bg_3d_spsr_sample> &samples,
fastf_t feature_size)
{
RTree<size_t, double, 3> index;
for (size_t i = 0; i < samples.size(); i++) {
double point[3] = {
samples[i].point[X], samples[i].point[Y], samples[i].point[Z]
};
index.Insert(point, point, i);
}
fastf_t search_distance_sq = feature_size * feature_size;
for (size_t i = 0; i < samples.size(); i++) {
double minimum[3];
double maximum[3];
for (size_t dimension = 0; dimension < 3; dimension++) {
minimum[dimension] =
samples[i].point[dimension] - feature_size;
maximum[dimension] =
samples[i].point[dimension] + feature_size;
}
size_t neighbor_count = 0;
index.Search(minimum, maximum,
[&samples, i, search_distance_sq, &neighbor_count](
const size_t &candidate, void *) {
if (DIST_PNT_PNT_SQ(samples[i].point,
samples[candidate].point) <= search_distance_sq)
neighbor_count++;
return neighbor_count < SPSR_MIN_NEIGHBORS;
}, NULL);
if (neighbor_count < SPSR_MIN_NEIGHBORS)
append_hint(hints, samples[i].point, samples[i].normal,
feature_size, BG_3D_SPSR_REFINE_DENSITY);
}
}
static void
surface_variation_hints(
std::vector<struct bg_3d_spsr_refinement_hint> &hints,
const spsr_mesh &mesh, fastf_t feature_size)
{
size_t vertex_count = mesh.vertices.size() / 3;
std::vector<std::array<fastf_t, 3>> first_normal(vertex_count);
std::vector<fastf_t> variation(vertex_count, 0.0);
std::vector<unsigned char> have_normal(vertex_count, 0);
const fastf_t variation_limit =
1.0 - std::cos(SPSR_NORMAL_ANGLE_DEGREES * DEG2RAD);
for (size_t face = 0; face < mesh.faces.size() / 3; face++) {
int ia = mesh.faces[3 * face];
int ib = mesh.faces[3 * face + 1];
int ic = mesh.faces[3 * face + 2];
const fastf_t *a = &mesh.vertices[3 * static_cast<size_t>(ia)];
const fastf_t *b = &mesh.vertices[3 * static_cast<size_t>(ib)];
const fastf_t *c = &mesh.vertices[3 * static_cast<size_t>(ic)];
vect_t ab;
vect_t ac;
vect_t normal;
VSUB2(ab, b, a);
VSUB2(ac, c, a);
VCROSS(normal, ab, ac);
fastf_t length = MAGNITUDE(normal);
if (length <= VUNITIZE_TOL)
continue;
VSCALE(normal, normal, 1.0 / length);
const int vertices[3] = {ia, ib, ic};
for (size_t corner = 0; corner < 3; corner++) {
size_t vertex = static_cast<size_t>(vertices[corner]);
if (!have_normal[vertex]) {
VMOVE(first_normal[vertex].data(), normal);
have_normal[vertex] = 1;
} else {
variation[vertex] = std::max(variation[vertex],
1.0 - std::fabs(VDOT(first_normal[vertex].data(), normal)));
}
}
}
for (size_t vertex = 0; vertex < vertex_count; vertex++) {
if (variation[vertex] <= variation_limit)
continue;
const fastf_t *point = &mesh.vertices[3 * vertex];
append_hint(hints, point, first_normal[vertex].data(),
feature_size * (1.0 + variation[vertex]),
BG_3D_SPSR_REFINE_SURFACE_VARIATION);
}
}
static void
limit_hints(std::vector<struct bg_3d_spsr_refinement_hint> &hints,
fastf_t feature_size)
{
std::sort(hints.begin(), hints.end(),
[](const struct bg_3d_spsr_refinement_hint &left,
const struct bg_3d_spsr_refinement_hint &right) {
return left.error > right.error;
});
RTree<size_t, double, 3> locations;
std::vector<struct bg_3d_spsr_refinement_hint> selected;
selected.reserve(std::min(hints.size(), SPSR_MAX_HINTS));
fastf_t separation = feature_size * SPSR_DEDUP_FRACTION;
fastf_t separation_sq = separation * separation;
for (const auto &hint : hints) {
double minimum[3];
double maximum[3];
for (size_t dimension = 0; dimension < 3; dimension++) {
minimum[dimension] = hint.point[dimension] - separation;
maximum[dimension] = hint.point[dimension] + separation;
}
bool nearby = false;
locations.Search(minimum, maximum,
[&hint, &selected, separation_sq, &nearby](
const size_t &candidate, void *) {
if (DIST_PNT_PNT_SQ(hint.point,
selected[candidate].point) <= separation_sq) {
nearby = true;
return false;
}
return true;
}, NULL);
if (nearby)
continue;
size_t hint_index = selected.size();
selected.push_back(hint);
double point[3] = {hint.point[X], hint.point[Y], hint.point[Z]};
locations.Insert(point, point, hint_index);
if (selected.size() == SPSR_MAX_HINTS)
break;
}
hints.swap(selected);
}
template<typename Implicit>
static bool
extract_mesh(spsr_mesh &mesh, const Implicit &implicit,
const Reconstructor::LevelSetExtractionParameters &parameters)
{
std::vector<std::vector<int>> polygons;
polygon_stream<int> faces(polygons);
vertex_stream<real_type, 3> vertices(mesh.vertices);
implicit.extractLevelSet(vertices, faces, parameters);
if (mesh.vertices.empty() || mesh.vertices.size() % 3 ||
mesh.vertices.size() / 3 >
static_cast<size_t>(std::numeric_limits<int>::max()) ||
polygons.empty() ||
polygons.size() > static_cast<size_t>(std::numeric_limits<int>::max()))
return false;
mesh.faces.reserve(polygons.size() * 3);
for (const auto &polygon : polygons) {
if (polygon.size() != 3)
return false;
for (int vertex : polygon) {
if (vertex < 0 ||
static_cast<size_t>(vertex) >= mesh.vertices.size() / 3)
return false;
mesh.faces.push_back(vertex);
}
}
return true;
}
static bool
solve_once(spsr_mesh &mesh,
std::vector<struct bg_3d_spsr_refinement_hint> &hints,
const std::vector<struct bg_3d_spsr_sample> &samples,
const struct bg_3d_spsr_adaptive_opts &options)
{
static std::mutex solver_mutex;
std::lock_guard<std::mutex> guard(solver_mutex);
static const unsigned int fem_signature =
FEMDegreeAndBType<Reconstructor::Poisson::DefaultFEMDegree,
Reconstructor::Poisson::DefaultFEMBoundary>::Signature;
using fem_signatures = IsotropicUIntPack<3, fem_signature>;
using implicit_type =
Reconstructor::Implicit<real_type, 3, fem_signatures>;
using solver_type =
Reconstructor::Poisson::Solver<real_type, 3, fem_signatures>;
Reconstructor::Poisson::SolutionParameters<real_type> solver_parameters;
Reconstructor::LevelSetExtractionParameters extraction_parameters;
set_solver_options(solver_parameters, extraction_parameters,
options.solver);
ThreadPool::ParallelizationType = ThreadPool::ASYNC;
point_stream<real_type, 3> points(samples);
std::unique_ptr<implicit_type> implicit(
solver_type::Solve(points, solver_parameters));
if (!implicit || !extract_mesh(mesh, *implicit, extraction_parameters))
return false;
if (options.target_feature_size > 0.0) {
sample_hints(hints, samples, *implicit,
options.target_feature_size);
density_hints(hints, samples, options.target_feature_size);
surface_variation_hints(hints, mesh,
options.target_feature_size);
limit_hints(hints, options.target_feature_size);
}
return true;
}
static bool
copy_mesh(int **faces, int *face_count, point_t **vertices,
int *vertex_count, const spsr_mesh &mesh)
{
size_t faces_size = mesh.faces.size() * sizeof(int);
size_t vertices_size = mesh.vertices.size() * sizeof(real_type);
int *new_faces = static_cast<int *>(bu_malloc(faces_size,
"SPSR face array"));
point_t *new_vertices = static_cast<point_t *>(bu_malloc(vertices_size,
"SPSR vertex array"));
if (!new_faces || !new_vertices) {
if (new_faces)
bu_free(new_faces, "SPSR face array");
if (new_vertices)
bu_free(new_vertices, "SPSR vertex array");
return false;
}
std::memcpy(new_faces, mesh.faces.data(), faces_size);
std::memcpy(new_vertices, mesh.vertices.data(), vertices_size);
*faces = new_faces;
*face_count = static_cast<int>(mesh.faces.size() / 3);
*vertices = new_vertices;
*vertex_count = static_cast<int>(mesh.vertices.size() / 3);
return true;
}
static void
initialize_outputs(int **faces, int *face_count, point_t **vertices,
int *vertex_count, struct bg_3d_spsr_report *report)
{
if (faces)
*faces = NULL;
if (face_count)
*face_count = 0;
if (vertices)
*vertices = NULL;
if (vertex_count)
*vertex_count = 0;
if (report)
std::memset(report, 0, sizeof(*report));
}
} // namespace
extern "C" int
bg_3d_spsr_adaptive(int **faces, int *num_faces, point_t **vertices,
int *num_vertices, const struct bg_3d_spsr_sample *input_samples,
size_t sample_count, const struct bg_3d_spsr_adaptive_opts *input_options,
bg_3d_spsr_refinement_func_t refine, void *client_data,
struct bg_3d_spsr_report *report)
{
initialize_outputs(faces, num_faces, vertices, num_vertices, report);
if (!faces || !num_faces || !vertices || !num_vertices ||
!input_samples || !sample_count)
return BRLCAD_ERROR;
struct bg_3d_spsr_adaptive_opts default_options =
BG_3D_SPSR_ADAPTIVE_OPTS_DEFAULT;
const struct bg_3d_spsr_adaptive_opts &options =
input_options ? *input_options : default_options;
if (!valid_options(options.solver) ||
options.target_feature_size < 0.0 || options.max_time < 0.0 ||
(options.max_refinement_passes &&
(!refine || options.target_feature_size <= 0.0)) ||
(options.max_points && options.max_points < sample_count))
return BRLCAD_ERROR;
fastf_t extent = 0.0;
{
std::vector<struct bg_3d_spsr_sample> initial(
input_samples, input_samples + sample_count);
extent = sample_extent(initial);
}
if (!std::isfinite(extent) || extent <= SMALL_FASTF)
return BRLCAD_ERROR;
fastf_t deduplication_distance =
options.target_feature_size > 0.0 ?
options.target_feature_size * SPSR_DEDUP_FRACTION :
std::max(extent * 1.0e-12, static_cast<fastf_t>(SMALL_FASTF));
sample_set accumulated(deduplication_distance, options.max_points);
for (size_t i = 0; i < sample_count; i++)
accumulated.append(input_samples[i]);
if (accumulated.samples().empty())
return BRLCAD_ERROR;
const clock_type::time_point start = clock_type::now();
if (report)
report->initial_sample_count = accumulated.samples().size();
bool point_limit_reached = accumulated.full();
for (size_t pass = 0; ; pass++) {
if (options.max_time > 0.0 &&
elapsed_seconds(start) >= options.max_time) {
if (report)
report->termination = BG_3D_SPSR_TIME_LIMIT;
break;
}
spsr_mesh mesh;
std::vector<struct bg_3d_spsr_refinement_hint> hints;
try {
if (!solve_once(mesh, hints, accumulated.samples(), options)) {
if (report)
report->termination = BG_3D_SPSR_SOLVER_ERROR;
break;
}
} catch (const std::exception &) {
if (report)
report->termination = BG_3D_SPSR_SOLVER_ERROR;
break;
} catch (...) {
if (report)
report->termination = BG_3D_SPSR_SOLVER_ERROR;
break;
}
if (report)
report->solve_count++;
if (!refine) {
if (copy_mesh(faces, num_faces, vertices, num_vertices, mesh)) {
if (report) {
report->termination = BG_3D_SPSR_COMPLETE;
report->validation.passed = 1;
report->final_sample_count = accumulated.samples().size();
report->elapsed_time = elapsed_seconds(start);
}
return BRLCAD_OK;
}
if (report)
report->termination = BG_3D_SPSR_SOLVER_ERROR;
break;
}
double remaining_time = options.max_time > 0.0 ?
std::max(0.0, options.max_time - elapsed_seconds(start)) : 0.0;
if (options.max_time > 0.0 && remaining_time <= 0.0) {
if (report)
report->termination = BG_3D_SPSR_TIME_LIMIT;
break;
}
struct bg_3d_spsr_refinement_request request = {};
request.pass = pass;
request.target_feature_size = options.target_feature_size;
request.remaining_time = remaining_time;
request.vertices =
reinterpret_cast<const point_t *>(mesh.vertices.data());
request.vertex_count = mesh.vertices.size() / 3;
request.faces = mesh.faces.data();
request.face_count = mesh.faces.size() / 3;
request.hints = hints.data();
request.hint_count = hints.size();
struct bg_3d_spsr_refinement_response response = {};
if (refine(&response, &request, client_data) != BRLCAD_OK) {
if (report)
report->termination = BG_3D_SPSR_CALLBACK_STOP;
break;
}
if (report)
report->validation = response.validation;
if (response.validation.passed) {
if (copy_mesh(faces, num_faces, vertices, num_vertices, mesh)) {
if (report) {
report->termination = BG_3D_SPSR_COMPLETE;
report->final_sample_count = accumulated.samples().size();
report->elapsed_time = elapsed_seconds(start);
}
return BRLCAD_OK;
}
if (report)
report->termination = BG_3D_SPSR_SOLVER_ERROR;
break;
}
if (response.stop_refinement) {
if (report)
report->termination = BG_3D_SPSR_CALLBACK_STOP;
break;
}
if (pass == options.max_refinement_passes) {
if (report)
report->termination = point_limit_reached ?
BG_3D_SPSR_POINT_LIMIT : BG_3D_SPSR_CALLBACK_STOP;
break;
}
if (response.sample_count && !response.samples) {
if (report)
report->termination = BG_3D_SPSR_CALLBACK_STOP;
break;
}
if (report)
report->requested_sample_count += response.sample_count;
size_t accepted = 0;
for (size_t i = 0; i < response.sample_count; i++) {
if (accumulated.append(response.samples[i]))
accepted++;
}
if (report)
report->accepted_sample_count += accepted;
point_limit_reached = accumulated.full();
if (!accepted) {
if (report)
report->termination = point_limit_reached ?
BG_3D_SPSR_POINT_LIMIT : BG_3D_SPSR_NO_NEW_SAMPLES;
break;
}
}
if (report) {
report->final_sample_count = accumulated.samples().size();
report->elapsed_time = elapsed_seconds(start);
}
return BRLCAD_ERROR;
}
extern "C" int
bg_3d_spsr(int **faces, int *num_faces, point_t **vertices, int *num_vertices,
const point_t *input_points_3d, const vect_t *input_normals_3d,
int num_input_pnts, struct bg_3d_spsr_opts *spsr_opts)
{
if (!input_points_3d || !input_normals_3d || num_input_pnts <= 0)
return BRLCAD_ERROR;
std::vector<struct bg_3d_spsr_sample> samples(
static_cast<size_t>(num_input_pnts));
for (size_t i = 0; i < samples.size(); i++) {
VMOVE(samples[i].point, input_points_3d[i]);
VMOVE(samples[i].normal, input_normals_3d[i]);
}
struct bg_3d_spsr_adaptive_opts options =
BG_3D_SPSR_ADAPTIVE_OPTS_DEFAULT;
options.max_refinement_passes = 0;
if (spsr_opts)
options.solver = *spsr_opts;
return bg_3d_spsr_adaptive(faces, num_faces, vertices, num_vertices,
samples.data(), samples.size(), &options, NULL, NULL, NULL);
}
/*
* Local Variables:
* tab-width: 8
* mode: C++
* c-basic-offset: 4
* indent-tabs-mode: t
* c-file-style: "stroustrup"
* End:
* ex: shiftwidth=4 tabstop=8 cino=N-s
*/
+4
View File
@@ -33,6 +33,10 @@ brlcad_addexec(bg_aabb_ray aabb_ray.c "${BG_TEST_LIBS}" TEST)
brlcad_add_test(NAME bg_aabb_ray COMMAND bg_aabb_ray)
brlcad_addexec(bg_spsr spsr.cpp "${BG_TEST_LIBS}" TEST)
brlcad_add_test(NAME bg_spsr COMMAND bg_spsr)
brlcad_addexec(bg_polygon_sort polygon_sort.c "${BG_TEST_LIBS}" TEST)
brlcad_add_test(NAME bg_polygon_sort COMMAND bg_polygon_sort)
+200
View File
@@ -0,0 +1,200 @@
/* S P S R . C P P
* BRL-CAD
*
* Copyright (c) 2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library 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 this file; see the file named COPYING for more
* information.
*/
#include "common.h"
#include <cmath>
#include <vector>
#include "vmath.h"
#include "bu/app.h"
#include "bu/log.h"
#include "bu/malloc.h"
#include "bg/spsr.h"
static int failures = 0;
static void
expect(bool condition, const char *message)
{
if (condition)
return;
bu_log("FAIL: %s\n", message);
failures++;
}
static std::vector<struct bg_3d_spsr_sample>
sphere_samples(size_t count)
{
const fastf_t golden_angle = M_PI * (3.0 - std::sqrt(5.0));
std::vector<struct bg_3d_spsr_sample> samples(count);
for (size_t i = 0; i < count; i++) {
fastf_t y = 1.0 - 2.0 *
(static_cast<fastf_t>(i) + 0.5) / count;
fastf_t radius = std::sqrt(std::max(0.0, 1.0 - y * y));
fastf_t angle = golden_angle * i;
VSET(samples[i].point, radius * std::cos(angle), y,
radius * std::sin(angle));
VMOVE(samples[i].normal, samples[i].point);
}
return samples;
}
struct callback_state {
size_t calls;
size_t hints;
struct bg_3d_spsr_sample additional_sample;
bool refine_once;
bool stop;
};
static int
accept_candidate(struct bg_3d_spsr_refinement_response *response,
const struct bg_3d_spsr_refinement_request *request, void *data)
{
struct callback_state *state =
static_cast<struct callback_state *>(data);
state->calls++;
state->hints = request->hint_count;
response->validation.ray_count = 100;
if (state->stop) {
response->validation.passed = 0;
response->stop_refinement = 1;
} else if (state->refine_once && state->calls == 1) {
response->samples = &state->additional_sample;
response->sample_count = 1;
response->validation.passed = 0;
} else {
response->validation.passed = 1;
}
return BRLCAD_OK;
}
int
main(int UNUSED(argc), const char **argv)
{
bu_setprogname(argv[0]);
std::vector<struct bg_3d_spsr_sample> samples = sphere_samples(256);
struct bg_3d_spsr_adaptive_opts options =
BG_3D_SPSR_ADAPTIVE_OPTS_DEFAULT;
options.solver.depth = 5;
options.max_refinement_passes = 0;
int *faces = NULL;
int face_count = 0;
point_t *vertices = NULL;
int vertex_count = 0;
struct bg_3d_spsr_report report = {};
int ret = bg_3d_spsr_adaptive(&faces, &face_count, &vertices,
&vertex_count, samples.data(), samples.size(), &options,
NULL, NULL, &report);
expect(ret == BRLCAD_OK, "fixed structured reconstruction succeeds");
expect(face_count > 0 && vertex_count > 0,
"fixed structured reconstruction returns a mesh");
expect(report.solve_count == 1 && report.validation.passed,
"fixed structured reconstruction reports one successful solve");
if (faces)
bu_free(faces, "SPSR test faces");
if (vertices)
bu_free(vertices, "SPSR test vertices");
struct callback_state state = {};
options.max_refinement_passes = 3;
options.target_feature_size = 0.1;
options.max_points = 512;
faces = NULL;
vertices = NULL;
face_count = 0;
vertex_count = 0;
ret = bg_3d_spsr_adaptive(&faces, &face_count, &vertices,
&vertex_count, samples.data(), samples.size(), &options,
accept_candidate, &state, &report);
expect(ret == BRLCAD_OK, "callback can accept an adaptive candidate");
expect(state.calls == 1, "accepted candidate stops adaptive solving");
expect(report.validation.ray_count == 100,
"adaptive report preserves callback validation");
if (faces)
bu_free(faces, "SPSR test faces");
if (vertices)
bu_free(vertices, "SPSR test vertices");
state = {};
state.stop = true;
faces = NULL;
vertices = NULL;
face_count = 0;
vertex_count = 0;
ret = bg_3d_spsr_adaptive(&faces, &face_count, &vertices,
&vertex_count, samples.data(), samples.size(), &options,
accept_candidate, &state, &report);
expect(ret == BRLCAD_ERROR,
"callback can stop an unproductive adaptive solve");
expect(state.calls == 1 && report.solve_count == 1 &&
report.termination == BG_3D_SPSR_CALLBACK_STOP,
"callback stop preserves the final validation report");
state = {};
state.refine_once = true;
VSET(state.additional_sample.point, 1.0, 0.0, 0.0);
VSET(state.additional_sample.normal, 1.0, 0.0, 0.0);
faces = NULL;
vertices = NULL;
face_count = 0;
vertex_count = 0;
ret = bg_3d_spsr_adaptive(&faces, &face_count, &vertices,
&vertex_count, samples.data(), samples.size(), &options,
accept_candidate, &state, &report);
expect(ret == BRLCAD_OK, "adaptive refinement can add a source sample");
expect(state.calls == 2 && report.solve_count == 2,
"new source sample triggers a second solve");
expect(report.accepted_sample_count == 1 &&
report.final_sample_count == samples.size() + 1,
"adaptive report counts incorporated samples");
if (faces)
bu_free(faces, "SPSR test faces");
if (vertices)
bu_free(vertices, "SPSR test vertices");
options.solver.threads = 1;
ret = bg_3d_spsr_adaptive(&faces, &face_count, &vertices,
&vertex_count, samples.data(), samples.size(), &options,
accept_candidate, &state, NULL);
expect(ret == BRLCAD_ERROR,
"unsupported solver settings are rejected");
expect(bg_3d_spsr_adaptive(NULL, &face_count, &vertices,
&vertex_count, samples.data(), samples.size(), &options,
accept_candidate, &state, NULL) == BRLCAD_ERROR,
"invalid output arguments are rejected");
return failures ? 1 : 0;
}
/*
* Local Variables:
* tab-width: 8
* mode: C++
* c-basic-offset: 4
* indent-tabs-mode: t
* c-file-style: "stroustrup"
* End:
* ex: shiftwidth=4 tabstop=8 cino=N-s
*/
+31 -17
View File
@@ -388,31 +388,45 @@ mem_sysctl(int type, size_t *memsz)
return -2;
#if defined(__FreeBSD__) && defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_SYSCTL)
static const char *const page_size_name = "hw.pagesize";
static const char *const total_memory_name = "hw.physmem";
static const char *const free_pages_name = "vm.stats.vm.v_free_count";
static const char *const available_page_names[] = {
"vm.stats.vm.v_free_count",
"vm.stats.vm.v_inactive_count",
"vm.stats.vm.v_cache_count"
};
uint64_t page_size = 0;
size_t value_size = sizeof(page_size);
if (sysctlbyname(page_size_name, &page_size, &value_size, NULL, 0) != 0 ||
page_size == 0)
return -1;
if (type == BU_MEM_PAGE_SIZE)
return mem_size_from_uint64(page_size, memsz);
return mem_page_size(memsz);
uint64_t memory = 0;
value_size = sizeof(memory);
const char *memory_name = total_memory_name;
if (type == BU_MEM_AVAIL) {
memory_name = free_pages_name;
if (sysctlbyname(memory_name, &memory, &value_size, NULL, 0) != 0 ||
memory > UINT64_MAX / page_size)
return -1;
memory *= page_size;
} else if (sysctlbyname(memory_name, &memory, &value_size, NULL, 0) != 0) {
return -1;
/* FreeBSD's free queue omits clean inactive and cache pages that the VM
* can reclaim without paging another process. Counting only v_free_count
* makes an otherwise idle system appear memory-starved and needlessly
* disables memory-aware parallel work. */
for (size_t i = 0; i < sizeof(available_page_names) / sizeof(available_page_names[0]); i++) {
uint32_t pages = 0;
size_t value_size = sizeof(pages);
if (sysctlbyname(available_page_names[i], &pages, &value_size,
NULL, 0) != 0 || value_size != sizeof(pages)) {
/* v_free_count is required. Cache accounting is absent on some
* supported FreeBSD versions, so supplementary queues are optional. */
if (i == 0)
return -1;
continue;
}
if ((uint64_t)pages > UINT64_MAX - memory)
return -1;
memory += (uint64_t)pages;
}
return mem_pages_to_bytes(memory, memsz);
}
size_t value_size = sizeof(memory);
if (sysctlbyname(total_memory_name, &memory, &value_size, NULL, 0) != 0 ||
(value_size != sizeof(uint32_t) && value_size != sizeof(uint64_t)))
return -1;
return mem_size_from_uint64(memory, memsz);
#endif
return 1;
+47 -1
View File
@@ -24,6 +24,9 @@
#include <ctype.h>
#include <math.h>
#include <string.h>
#if !defined(_WIN32) || defined(__CYGWIN__)
# include <stdatomic.h>
#endif
#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h>
@@ -130,6 +133,36 @@ void parallel_cpp11thread(void (*func)(int, void *), size_t ncpu, void *arg);
int BU_SEM_THREAD = BU_SEM_ID_THREAD;
#if defined(_WIN32) && !defined(__CYGWIN__)
static LONG bu_cpu_limit = 0;
static size_t
cpu_limit_get(void)
{
return (size_t)InterlockedCompareExchange(&bu_cpu_limit, 0, 0);
}
static void
cpu_limit_set(size_t ncpu)
{
(void)InterlockedExchange(&bu_cpu_limit, (LONG)ncpu);
}
#else
static atomic_size_t bu_cpu_limit = ATOMIC_VAR_INIT(0);
static size_t
cpu_limit_get(void)
{
return atomic_load_explicit(&bu_cpu_limit, memory_order_acquire);
}
static void
cpu_limit_set(size_t ncpu)
{
atomic_store_explicit(&bu_cpu_limit, ncpu, memory_order_release);
}
#endif
typedef enum {
PARALLEL_GET = 0,
@@ -355,7 +388,9 @@ bu_avail_cpus(void)
}
if (LIKELY(ncpu > 0)) {
return ncpu;
size_t cpu_limit = cpu_limit_get();
return (cpu_limit && cpu_limit < (size_t)ncpu) ? cpu_limit :
(size_t)ncpu;
}
/* non-PARALLEL */
@@ -363,6 +398,13 @@ bu_avail_cpus(void)
}
void
bu_avail_cpus_set(size_t ncpu)
{
cpu_limit_set((ncpu > MAX_PSW) ? MAX_PSW : ncpu);
}
/**********************************************************************/
@@ -538,6 +580,10 @@ parallel_interface_arg_stub(struct thread_data *user_thread_data)
void
bu_parallel(void (*func)(int, void *), size_t ncpu, void *arg)
{
size_t cpu_limit = cpu_limit_get();
if (ncpu && cpu_limit && ncpu > cpu_limit)
ncpu = cpu_limit;
#ifndef PARALLEL
if (!func)
+8 -2
View File
@@ -1077,11 +1077,17 @@ bu_process_poll(struct bu_process *pinfo, int *exit_status)
}
#if defined(_WIN32)
/* An exit code can be available before process teardown releases
* inherited files and pipes. Only report completion once signaled. */
DWORD wait_result = WaitForSingleObject(pinfo->hProcess, 0);
if (wait_result == WAIT_TIMEOUT)
return 0;
if (wait_result != WAIT_OBJECT_0)
return -1;
DWORD status = 0;
if (!GetExitCodeProcess(pinfo->hProcess, &status))
return -1;
if (status == STILL_ACTIVE)
return 0;
pinfo->exit_status = (status == BU_MSVC_ABORT_EXIT) ?
ERROR_PROCESS_ABORTED : (int)status;
+52 -5
View File
@@ -40,7 +40,7 @@
#include "bio.h"
#include "bresource.h"
#if defined(__APPLE__) && defined(HAVE_SYS_SYSCTL_H)
#if (defined(__APPLE__) || defined(__FreeBSD__)) && defined(HAVE_SYS_SYSCTL_H)
# include <sys/sysctl.h>
#endif
@@ -214,8 +214,12 @@ mem_test_failure(const char *query, ssize_t result, const size_t *output,
static int
platform_mem_tests(ssize_t all_mem)
platform_mem_tests(ssize_t all_mem, ssize_t avail_mem, ssize_t page_mem)
{
(void)all_mem;
(void)avail_mem;
(void)page_mem;
#if defined(__APPLE__) && defined(HAVE_SYS_SYSCTL_H)
uint64_t native_total = 0;
size_t value_size = sizeof(native_total);
@@ -230,8 +234,51 @@ platform_mem_tests(ssize_t all_mem)
"reported %llu\n", all_mem, (unsigned long long)native_total);
return -2;
}
#else
(void)all_mem;
#elif defined(__FreeBSD__) && defined(HAVE_SYS_SYSCTL_H)
uint64_t native_total = 0;
size_t value_size = sizeof(native_total);
if (sysctlbyname("hw.physmem", &native_total, &value_size, NULL, 0) != 0 ||
(value_size != sizeof(uint32_t) && value_size != sizeof(uint64_t))) {
bu_log("bu_mem platform test: unable to query hw.physmem\n");
return -1;
}
if (native_total != (uint64_t)all_mem) {
bu_log("bu_mem platform test: BU_MEM_ALL returned %zd; hw.physmem "
"reported %llu\n", all_mem, (unsigned long long)native_total);
return -2;
}
uint64_t reclaimable_pages = 0;
const char *const page_names[] = {
"vm.stats.vm.v_free_count",
"vm.stats.vm.v_inactive_count",
"vm.stats.vm.v_cache_count"
};
for (size_t i = 0; i < sizeof(page_names) / sizeof(page_names[0]); i++) {
uint32_t pages = 0;
value_size = sizeof(pages);
if (sysctlbyname(page_names[i], &pages, &value_size, NULL, 0) != 0 ||
value_size != sizeof(pages)) {
if (i == 0)
return -3;
continue;
}
reclaimable_pages += pages;
}
/* VM counters may change between the bu_mem and direct sysctl queries.
* A one-percent allowance is ample for that race while still detecting
* the former free-pages-only implementation. */
uint64_t native_available = reclaimable_pages * (uint64_t)page_mem;
uint64_t allowance = native_total / 100u;
uint64_t available_difference = ((uint64_t)avail_mem > native_available) ?
(uint64_t)avail_mem - native_available :
native_available - (uint64_t)avail_mem;
if (available_difference > allowance) {
bu_log("bu_mem platform test: BU_MEM_AVAIL returned %zd; FreeBSD "
"reclaimable queues reported %llu\n", avail_mem,
(unsigned long long)native_available);
return -4;
}
#endif
return 0;
}
@@ -445,7 +492,7 @@ main(int ac, char *av[])
if (avail_mem > all_mem)
return mem_test_failure("BU_MEM_AVAIL exceeds BU_MEM_ALL", avail_mem,
NULL, -5);
if (platform_mem_tests(all_mem) != 0)
if (platform_mem_tests(all_mem, avail_mem, page_mem) != 0)
return -6;
ssize_t process_mem = bu_mem(BU_MEM_PROCESS_AVAIL, NULL);
ssize_t resident_mem = bu_mem(BU_MEM_PROCESS_RESIDENT, NULL);
+26 -1
View File
@@ -121,6 +121,30 @@ main(int argc, char *argv[])
if (bu_getprogname()[0] == '\0')
bu_setprogname(argv[0]);
{
size_t detected_cpus = bu_avail_cpus();
size_t requested_cpus = (detected_cpus > MAX_PSW) ? MAX_PSW :
detected_cpus;
struct parallel_data limit_data = {1, NULL};
bu_avail_cpus_set(1);
if (bu_avail_cpus() != 1) {
bu_log("bu_avail_cpus process limit [FAIL]\n");
return 1;
}
memset(counter, 0, sizeof(counter));
bu_parallel(callback, requested_cpus, &limit_data);
if (tally(MAX_PSW) != 1) {
bu_log("bu_parallel process limit [FAIL]\n");
return 1;
}
bu_avail_cpus_set(0);
if (bu_avail_cpus() != detected_cpus) {
bu_log("bu_avail_cpus process limit reset [FAIL]\n");
return 1;
}
bu_log("bu_avail_cpus and bu_parallel process limit [PASS]\n");
}
while ((c = bu_getopt(argc, argv, "P:!:")) != -1) {
switch (c) {
case 'P':
@@ -137,8 +161,9 @@ main(int argc, char *argv[])
}
/* test calling without a hook function */
memset(counter, 0, sizeof(counter));
bu_parallel(NULL, ncpu, NULL);
if (tally(ncpu) != 0) {
if (tally(MAX_PSW) != 0) {
bu_log("bu_parallel zero callback [FAIL]\n");
return 1;
}
+15 -10
View File
@@ -26,11 +26,10 @@
#include "bu/app.h"
#include "bu/malloc.h"
#include "bu/vfont.h"
#include "bu/vls.h"
#define FONTDIR2 "/usr/lib/vfont"
#define DEFAULT_FONT "nonie.r.12"
#define FONTNAMESZ 128
#include "./vfont.h"
@@ -127,7 +126,7 @@ vfont_get(char *font)
register struct vfont *vfp = VFONT_NULL;
register FILE *fp = NULL;
register int i;
char fname[FONTNAMESZ] = {'\0'};
struct bu_vls fname = BU_VLS_INIT_ZERO;
unsigned char header[2*5]; /* 5 16-bit vax shorts */
unsigned char dispatch[10*256]; /* 256 10-byte structs */
uint16_t magic;
@@ -135,21 +134,24 @@ vfont_get(char *font)
const char *const_font;
const_font = (font == NULL) ? DEFAULT_FONT : (const char *)font;
bu_vls_strcpy(&fname, const_font);
/* Open the file and read in the header information. */
if ((fp = fopen(const_font, "rb")) == NULL) {
snprintf(fname, FONTNAMESZ, "%s/%s", bu_dir(NULL, 0, BU_DIR_DATA, "vfont", NULL), const_font);
if ((fp = fopen(fname, "rb")) == NULL) {
snprintf(fname, FONTNAMESZ, "%s/%s", FONTDIR2, const_font);
if ((fp = fopen(fname, "rb")) == NULL) {
bu_vls_sprintf(&fname, "%s/%s", bu_dir(NULL, 0, BU_DIR_DATA, "vfont", NULL), const_font);
if ((fp = fopen(bu_vls_addr(&fname), "rb")) == NULL) {
bu_vls_sprintf(&fname, "%s/%s", FONTDIR2, const_font);
if ((fp = fopen(bu_vls_addr(&fname), "rb")) == NULL) {
bu_vls_free(&fname);
return VFONT_NULL;
}
}
}
if (fread((char *)header, sizeof(header), 1, fp) != 1 ||
fread((char *)dispatch, sizeof(dispatch), 1, fp) != 1) {
fprintf(stderr, "vfont_get(%s): header read error\n", fname);
fprintf(stderr, "vfont_get(%s): header read error\n", bu_vls_addr(&fname));
fclose(fp);
bu_vls_free(&fname);
return VFONT_NULL;
}
magic = _vax_gshort(&header[0*2]) & 0xFFFF;
@@ -157,8 +159,9 @@ vfont_get(char *font)
if (UNLIKELY(magic != 0436)) {
fprintf(stderr, "vfont_get(%s): bad magic number 0%o\n",
fname, magic);
bu_vls_addr(&fname), magic);
fclose(fp);
bu_vls_free(&fname);
return VFONT_NULL;
}
@@ -166,10 +169,11 @@ vfont_get(char *font)
BU_ALLOC(vfp, struct vfont);
vfp->vf_bits = (char *)bu_malloc((size_t)size, "vfont bits");
if (fread(vfp->vf_bits, (size_t)size, 1, fp) != 1) {
fprintf(stderr, "vfont_get(%s): bitmap read error\n", fname);
fprintf(stderr, "vfont_get(%s): bitmap read error\n", bu_vls_addr(&fname));
fclose(fp);
bu_free(vfp->vf_bits, "vfont bits");
bu_free((char *)vfp, "vfont");
bu_vls_free(&fname);
return VFONT_NULL;
}
@@ -194,6 +198,7 @@ vfont_get(char *font)
vdp->vd_width = _vax_gshort(&cp[8]);
}
fclose(fp);
bu_vls_free(&fname);
return vfp;
}
+6 -8
View File
@@ -62,8 +62,9 @@ constexpr fastf_t DEFAULT_LEADER_MARGIN_SCALE = 2.0;
constexpr fastf_t DEFAULT_SCREEN_TEXT_HEIGHT_MM = 3.0;
/* The display-plane renderer uses this nominal density. --dpi makes the
* physical size explicit for displays whose effective density differs. */
constexpr fastf_t DEFAULT_SCREEN_DPI = RT_ANNOT_SCREEN_DPI;
constexpr fastf_t DISPLAY_PIXELS_PER_MM = RT_ANNOT_SCREEN_PIXELS_PER_MM;
constexpr fastf_t DEFAULT_SCREEN_DPI = 96.0;
constexpr fastf_t MILLIMETERS_PER_INCH = 25.4;
constexpr fastf_t DISPLAY_PIXELS_PER_MM = DEFAULT_SCREEN_DPI / MILLIMETERS_PER_INCH;
constexpr double AUTODIM_TEXT_WIDTH_SCALE = 0.65;
/* Layout penalties deliberately dominate the smaller rewards so avoiding
* collisions and crossings wins over merely moving a label farther out. */
@@ -472,12 +473,10 @@ parse_options(struct ged *gedp, int argc, const char **argv,
bu_vls_printf(gedp->ged_result_str, "Precision must be between 0 and 15");
return -1;
}
if (!std::isfinite(opts.text_height) || !std::isfinite(opts.line_width) ||
opts.text_height < 0.0 || opts.line_width < 0.0 ||
std::isinf(opts.offset) ||
if (opts.text_height < 0.0 || opts.line_width < 0.0 ||
(std::isfinite(opts.offset) && opts.offset < 0.0)) {
bu_vls_printf(gedp->ged_result_str,
"Text height and line width must be finite and non-negative; offset must be finite and non-negative when specified");
"Text height, line width, and offset must not be negative");
return -1;
}
if (!std::isfinite(opts.dpi) || opts.dpi <= 0.0) {
@@ -2905,8 +2904,7 @@ cmd_info(void *data, int argc, const char **argv)
if (rt_db_get_internal(&intern, dp, gedp->dbip, NULL) == ID_ANNOT) {
struct rt_annot_internal *annotation =
static_cast<struct rt_annot_internal *>(intern.idb_ptr);
bu_vls_printf(gedp->ged_result_str,
"\nspace: %s\nsegments: %zu",
bu_vls_printf(gedp->ged_result_str, "\nspace: %s\nsegments: %zu",
(annotation->flags & RT_ANNOT_MODEL_SPACE) ? "model" : "view",
annotation->ant.count);
rt_db_free_internal(&intern);
+5 -5
View File
@@ -3,11 +3,13 @@ brlcad_find_package(manifold REQUIRED)
BRLCAD_Find_Package(TinyGLTF REQUIRED)
set(BOT_LIBS libged libbg libbu manifold::manifold tinygltf::tinygltf ${WINSOCK_LIB})
set(BOT_INTERNAL_INCLUDE_DIRS)
if(BRLCAD_ENABLE_OPENVDB)
set(BOT_LIBS ${BOT_LIBS} ${OpenVDB_LIBRARIES} ${IlmBase_LIBRARIES} ${Tbb_LIBRARIES})
set(BOT_LOCAL_INCLUDE_DIRS ${BOT_LOCAL_INCLUDE_DIRS} ${OpenVDB_INCLUDE_DIRS} ${Tbb_INCLUDE_DIRS} ${IlmBase_INCLUDE_DIRS})
list(APPEND BOT_INTERNAL_INCLUDE_DIRS ${BRLCAD_SOURCE_DIR}/src/librt/primitives/bot)
set(BOT_OPENVDB_DEFS HAVE_OPENVDB_BOT_EXTERIOR BRLCAD_OPENVDB)
endif(BRLCAD_ENABLE_OPENVDB)
@@ -54,11 +56,11 @@ if(BRLCAD_ENABLE_OPENVDB)
# PLUGIN_ONLY these flags are scoped to the plugin .so and do not
# pollute the main libged target.
set_source_files_properties(
remesh.cpp
bot_flood_exterior.cpp
bot_openvdb.cpp
PROPERTIES COMPILE_FLAGS "-w -fno-lto"
)
list(APPEND BOT_SRCS bot_openvdb.cpp bot_flood_exterior.cpp)
list(APPEND BOT_SRCS bot_flood_exterior.cpp)
endif(BRLCAD_ENABLE_OPENVDB)
set(
@@ -78,7 +80,7 @@ set(
ged_plugin_library(ged-bot
PLUGIN_ONLY
${BOT_SRCS}
INCLUDES ${CMAKE_CURRENT_SOURCE_DIR}
INCLUDES ${CMAKE_CURRENT_SOURCE_DIR} ${BOT_INTERNAL_INCLUDE_DIRS}
SYSTEM_INCLUDES ${BOT_LOCAL_INCLUDE_DIRS}
LIBS ${BOT_LIBS}
DEFINITIONS "EIGEN_DONT_VECTORIZE" ${BOT_OPENVDB_DEFS}
@@ -87,8 +89,6 @@ ged_plugin_library(ged-bot
cmakefiles(
CMakeLists.txt
bot_flood_exterior.cpp
bot_openvdb.cpp
bot_openvdb.h
concurrentqueue.h
dump/ged_bot_dump.h
ged_bot.h
+2 -2
View File
@@ -28,7 +28,7 @@
*
* Algorithm
* ---------
* 1. Build an occupancy grid (solid / air) via rt_rtip_to_occupancy_grid
* 1. Build an occupancy grid (solid / air) via rt_rtip_to_openvdb_occupancy
* (implemented in bot_openvdb.cpp). Rays are shot in +X, +Y, +Z.
* A voxel is marked solid when any hit segment encloses its centre.
*
@@ -143,7 +143,7 @@ bot_flood_exterior_classify(struct rt_i *rtip,
/* Step 1: voxelise the model into a solid-occupancy grid. */
bu_log("bot flood exterior: voxel_size=%.4g\n", voxel_size);
openvdb::BoolGrid::Ptr solid = rt_rtip_to_occupancy_grid(rtip, voxel_size, &nx, &ny, &nz);
openvdb::BoolGrid::Ptr solid = rt_rtip_to_openvdb_occupancy(rtip, voxel_size, &nx, &ny, &nz);
bu_log("bot flood exterior: grid %dx%dx%d\n", nx, ny, nz);
/* Step 2: BFS flood fill to find exterior (water-reachable) voxels. */
+1 -1
View File
@@ -37,7 +37,7 @@
* eliminating the need for a separate global sampling phase.
*
* Flood fill (--flood-fill, requires OpenVDB)
* The model is voxelised via rt_rtip_to_occupancy_grid, then a
* The model is voxelised via rt_rtip_to_openvdb_occupancy, then a
* BFS flood-fill from the boundary finds all "water-reachable" voxels.
* A face is exterior when any of its six face-adjacent voxels is
* reachable.
+91 -152
View File
@@ -25,11 +25,9 @@
#include "common.h"
#ifdef OPENVDB_ABI_VERSION_NUMBER
# include <openvdb/openvdb.h>
# include <openvdb/tools/VolumeToMesh.h>
# include <openvdb/tools/MeshToVolume.h>
#endif /* OPENVDB_ABI_VERSION_NUMBER */
#ifdef BRLCAD_OPENVDB
# include "bot_openvdb.h"
#endif /* BRLCAD_OPENVDB */
#include "manifold/manifold.h"
@@ -49,115 +47,52 @@
#include "./ged_bot.h"
#ifdef OPENVDB_ABI_VERSION_NUMBER
struct botDataAdapter {
struct rt_bot_internal *bot;
size_t polygonCount() const {
return bot->num_faces;
};
size_t pointCount() const {
return bot->num_vertices;
};
size_t vertexCount(size_t) const {
return 3;
};
void getIndexSpacePoint(size_t n, size_t v, openvdb::Vec3d& pos) const {
int idx = bot->faces[(n*3)+v];
pos[X] = bot->vertices[(idx*3)+X];
pos[Y] = bot->vertices[(idx*3)+Y];
pos[Z] = bot->vertices[(idx*3)+Z];
return;
};
/* constructor */
botDataAdapter(struct rt_bot_internal *bip) : bot(bip) {}
};
#ifdef BRLCAD_OPENVDB
static bool
bot_remesh_vdb(struct ged *UNUSED(gedp), struct rt_bot_internal *bot, double voxelSize)
bot_remesh_vdb(struct ged *gedp, struct rt_bot_internal **obot,
struct rt_bot_internal *bot,
double voxel_size, double adaptivity)
{
const float exteriorBandWidth = 10.0;
const float interiorBandWidth = std::numeric_limits<float>::max();
struct botDataAdapter bda(bot);
openvdb::initialize();
bu_log("...voxelizing");
openvdb::math::Transform::Ptr xform = openvdb::math::Transform::createLinearTransform(voxelSize);
openvdb::FloatGrid::Ptr bot2vol = openvdb::tools::meshToVolume<openvdb::FloatGrid, botDataAdapter>(bda, *xform, exteriorBandWidth, interiorBandWidth);
#if 0
openvdb::io::File file("mesh.vdb");
openvdb::GridPtrVec grids;
grids.push_back(bot2vol);
file.write(grids);
file.close();
return false;
#endif
bu_log("...devoxelizing");
std::vector<openvdb::Vec3s> points;
std::vector<openvdb::Vec3I> triangles;
std::vector<openvdb::Vec4I> quadrilaterals;
openvdb::tools::volumeToMesh<openvdb::FloatGrid>(*bot2vol, points, triangles, quadrilaterals);
bu_log("...storing");
if (bot->vertices) {
bu_free(bot->vertices, "vertices");
bot->num_vertices = 0;
}
if (bot->faces) {
bu_free(bot->faces, "faces");
bot->num_faces = 0;
}
if (bot->normals) {
bu_free(bot->normals, "normals");
}
if (bot->face_normals) {
bu_free(bot->face_normals, "face normals");
if (bot->mode != RT_BOT_SOLID) {
bu_vls_printf(gedp->ged_result_str,
"ERROR: OpenVDB remesh requires a SOLID BoT.\n"
"Surface and plate-mode BoTs have no volume; "
"use Geogram remesh instead.\n");
return false;
}
bot->num_vertices = points.size();
bot->vertices = (fastf_t *)bu_malloc(bot->num_vertices * ELEMENTS_PER_POINT * sizeof(fastf_t), "vertices");
for (size_t i = 0; i < points.size(); i++) {
bot->vertices[(i*3)+X] = points[i].x();
bot->vertices[(i*3)+Y] = points[i].y();
bot->vertices[(i*3)+Z] = points[i].z();
}
bot->num_faces = triangles.size() + (quadrilaterals.size() * 2);
bot->faces = (int *)bu_malloc(bot->num_faces * 3 * sizeof(int), "triangles");
for (size_t i = 0; i < triangles.size(); i++) {
bot->faces[(i*3)+X] = triangles[i].x();
bot->faces[(i*3)+Y] = triangles[i].y();
bot->faces[(i*3)+Z] = triangles[i].z();
}
size_t ntri = triangles.size();
for (size_t i = 0; i < quadrilaterals.size(); i++) {
bot->faces[((ntri+i)*3)+X] = quadrilaterals[i][0];
bot->faces[((ntri+i)*3)+Y] = quadrilaterals[i][1];
bot->faces[((ntri+i)*3)+Z] = quadrilaterals[i][2];
bu_log("...voxelizing (voxel_size=%.4g, adaptivity=%.2f)\n",
voxel_size > 0.0 ? voxel_size : -1.0, adaptivity);
bot->faces[((ntri+i+1)*3)+X] = quadrilaterals[i][0];
bot->faces[((ntri+i+1)*3)+Y] = quadrilaterals[i][2];
bot->faces[((ntri+i+1)*3)+Z] = quadrilaterals[i][3];
openvdb::FloatGrid::Ptr grid = rt_bot_to_openvdb_sdf(bot, voxel_size);
if (!grid) {
bu_vls_printf(gedp->ged_result_str, "ERROR: meshToVolume failed\n");
return false;
}
bu_log("...done!\n");
bu_log("...extracting mesh\n");
return (points.size() > 0);
struct rt_bot_internal *nbot = rt_bot_from_openvdb_sdf(grid, adaptivity);
if (!nbot || nbot->num_faces == 0) {
bu_vls_printf(gedp->ged_result_str, "ERROR: volumeToMesh produced no faces\n");
if (nbot) { bu_free(nbot->vertices, "verts"); bu_free(nbot->faces, "faces"); BU_PUT(nbot, struct rt_bot_internal); }
return false;
}
bu_log("...done! %zu vertices, %zu faces\n",
nbot->num_vertices, nbot->num_faces);
*obot = nbot;
return true;
}
#else /* OPENVDB_ABI_VERSION_NUMBER */
#else /* BRLCAD_OPENVDB */
static bool
bot_remesh_vdb(struct ged *gedp, struct rt_bot_internal *UNUSED(bot), double UNUSED(voxelSize))
bot_remesh_vdb(struct ged *gedp, struct rt_bot_internal **UNUSED(obot),
struct rt_bot_internal *UNUSED(bot),
double UNUSED(voxel_size), double UNUSED(adaptivity))
{
bu_vls_printf(gedp->ged_result_str,
"WARNING: BoT remeshing is unavailable.\n"
@@ -166,7 +101,7 @@ bot_remesh_vdb(struct ged *gedp, struct rt_bot_internal *UNUSED(bot), double UNU
return false;
}
#endif /* OPENVDB_ABI_VERSION_NUMBER */
#endif /* BRLCAD_OPENVDB */
static int
bot_remesh_geogram(struct rt_bot_internal **obot, struct ged *gedp, struct rt_bot_internal *bot)
@@ -240,7 +175,7 @@ _bot_cmd_remesh(void *bs, int argc, const char **argv)
struct _ged_bot_info *gb = (struct _ged_bot_info *)bs;
struct ged *gedp = gb->gedp;
const char *usage_string = "bot [options] remesh <objname> <output_bot>\n";
const char *usage_string = "bot [options] remesh <objname> [output_bot]\n";
const char *purpose_string = "Store a remeshed version of the BoT in object <output_bot>";
if (_bot_cmd_msgs(bs, argc, argv, usage_string, purpose_string)) {
return BRLCAD_OK;
@@ -257,14 +192,17 @@ _bot_cmd_remesh(void *bs, int argc, const char **argv)
int print_help = 0;
int use_vdb = 0;
fastf_t vdb_voxel_size = 0.0; /* 0 = auto */
fastf_t vdb_adaptivity = 0.0; /* 0 = full voxel density */
struct bu_vls output_bot_name = BU_VLS_INIT_ZERO;
struct bu_opt_desc d[7];
BU_OPT(d[0], "h", "help", "", NULL, &print_help, "Print help");
BU_OPT(d[1], "o", "output", "oname", &bu_opt_vls, &output_bot_name, "Name to use for output BoT");
BU_OPT(d[2], "", "vdb", "", NULL, &use_vdb, "Use OpenVDB based remeshing");
BU_OPT_NULL(d[3]);
BU_OPT(d[0], "h", "help", "", NULL, &print_help, "Print help");
BU_OPT(d[1], "o", "output", "oname", &bu_opt_vls, &output_bot_name, "Name to use for output BoT");
BU_OPT(d[2], "", "vdb", "", NULL, &use_vdb, "Use OpenVDB level-set remeshing (solid BoTs only)");
BU_OPT(d[3], "", "openvdb-voxel-size", "#", &bu_opt_fastf_t, &vdb_voxel_size, "OpenVDB voxel size in model units (default: bbox_diagonal/100)");
BU_OPT(d[4], "", "openvdb-adaptivity", "#", &bu_opt_fastf_t, &vdb_adaptivity, "OpenVDB mesh simplification [0.0=full density, 1.0=max simplification]");
BU_OPT_NULL(d[5]);
argc--; argv++;
@@ -283,15 +221,13 @@ _bot_cmd_remesh(void *bs, int argc, const char **argv)
}
const char *input_bot_name = gb->dp->d_namep;
if (gb->intern->idb_major_type != DB5_MAJORTYPE_BRLCAD || gb->intern->idb_minor_type != DB5_MINORTYPE_BRLCAD_BOT) {
if (gb->intern->idb_major_type != DB5_MAJORTYPE_BRLCAD ||
gb->intern->idb_minor_type != DB5_MINORTYPE_BRLCAD_BOT) {
bu_vls_printf(gedp->ged_result_str, "%s is not a BOT primitive\n", input_bot_name);
bu_vls_free(&output_bot_name);
return BRLCAD_ERROR;
}
struct directory *dp_input = RT_DIR_NULL;
struct directory *dp_output = RT_DIR_NULL;
GED_CHECK_READ_ONLY(gedp, BRLCAD_ERROR);
if ((bu_vls_strlen(&output_bot_name) && argc > 1) || argc > 2) {
@@ -303,11 +239,10 @@ _bot_cmd_remesh(void *bs, int argc, const char **argv)
if (!bu_vls_strlen(&output_bot_name) && argc == 2)
bu_vls_printf(&output_bot_name, "%s", argv[1]);
// If we've got no specified output, we're overwriting
/* If no output name, overwrite the original. */
if (!bu_vls_strlen(&output_bot_name))
bu_vls_printf(&output_bot_name, "%s", input_bot_name);
if (!BU_STR_EQUAL(input_bot_name, bu_vls_cstr(&output_bot_name))) {
GED_CHECK_EXISTS(gedp, bu_vls_cstr(&output_bot_name), LOOKUP_QUIET, BRLCAD_ERROR);
}
@@ -315,61 +250,66 @@ _bot_cmd_remesh(void *bs, int argc, const char **argv)
struct rt_bot_internal *input_bot = (struct rt_bot_internal *)gb->intern->idb_ptr;
RT_BOT_CK_MAGIC(input_bot);
bu_log("INPUT BoT has %zu vertices and %zu faces\n", input_bot->num_vertices, input_bot->num_faces);
bu_log("INPUT BoT has %zu vertices and %zu faces\n",
input_bot->num_vertices, input_bot->num_faces);
/* TODO: stash a backup if overwriting the original */
struct rt_bot_internal *obot = NULL;
if (use_vdb) {
bool ok = bot_remesh_vdb(gedp, input_bot, 50);
if (!ok) {
if (!bot_remesh_vdb(gedp, &obot, input_bot, vdb_voxel_size, vdb_adaptivity)) {
bu_vls_free(&output_bot_name);
return BRLCAD_ERROR;
}
} else {
struct rt_bot_internal *obot = NULL;
if (bot_remesh_geogram(&obot, gedp, input_bot) != BRLCAD_OK || !obot) {
bu_vls_free(&output_bot_name);
return BRLCAD_ERROR;
}
struct rt_db_internal intern;
RT_DB_INTERNAL_INIT(&intern);
intern.idb_major_type = DB5_MAJORTYPE_BRLCAD;
intern.idb_type = ID_BOT;
intern.idb_meth = &OBJ[ID_BOT];
intern.idb_ptr = (void *)obot;
const char *rname = bu_vls_cstr(&output_bot_name);
struct directory *dp = db_diradd(gedp->dbip, rname, RT_DIR_PHONY_ADDR, 0, RT_DIR_SOLID, (void *)&intern.idb_type);
if (dp == RT_DIR_NULL) {
bu_vls_printf(gedp->ged_result_str, "Failed to write out new BoT %s\n", rname);
rt_db_free_internal(&intern);
bu_vls_free(&output_bot_name);
return BRLCAD_ERROR;
}
if (rt_db_put_internal(dp, gedp->dbip, &intern) < 0) {
bu_vls_printf(gedp->ged_result_str, "Failed to write out new BoT %s\n", rname);
rt_db_free_internal(&intern);
bu_vls_free(&output_bot_name);
return BRLCAD_ERROR;
}
rt_db_free_internal(&intern);
bu_vls_printf(gedp->ged_result_str, "Remesh complete\n");
return BRLCAD_OK;
}
bu_log("OUTPUT BoT has %zu vertices and %zu faces\n", input_bot->num_vertices, input_bot->num_faces);
if (!obot) {
bu_vls_printf(gedp->ged_result_str, "ERROR: remesh produced no output\n");
bu_vls_free(&output_bot_name);
return BRLCAD_ERROR;
}
if (BU_STR_EQUAL(input_bot_name, bu_vls_cstr(&output_bot_name))) {
dp_output = dp_input;
bu_log("OUTPUT BoT has %zu vertices and %zu faces\n",
obot->num_vertices, obot->num_faces);
/* Write out the result. */
struct rt_db_internal intern;
RT_DB_INTERNAL_INIT(&intern);
intern.idb_major_type = DB5_MAJORTYPE_BRLCAD;
intern.idb_type = ID_BOT;
intern.idb_meth = &OBJ[ID_BOT];
intern.idb_ptr = (void *)obot;
const char *rname = bu_vls_cstr(&output_bot_name);
struct directory *dp;
if (BU_STR_EQUAL(input_bot_name, rname)) {
/* Overwrite in place. */
dp = gb->dp;
} else {
GED_DB_DIRADD(gedp, dp_output, bu_vls_cstr(&output_bot_name), RT_DIR_PHONY_ADDR, 0, RT_DIR_SOLID, (void *)&gb->intern->idb_type, BRLCAD_ERROR);
dp = db_diradd(gedp->dbip, rname, RT_DIR_PHONY_ADDR, 0,
RT_DIR_SOLID, (void *)&intern.idb_type);
if (dp == RT_DIR_NULL) {
bu_vls_printf(gedp->ged_result_str, "Failed to create output BoT %s\n", rname);
rt_db_free_internal(&intern);
bu_vls_free(&output_bot_name);
return BRLCAD_ERROR;
}
}
GED_DB_PUT_INTERN(gedp, dp_output, gb->intern, BRLCAD_ERROR);
if (rt_db_put_internal(dp, gedp->dbip, &intern) < 0) {
bu_vls_printf(gedp->ged_result_str, "Failed to write output BoT %s\n", rname);
rt_db_free_internal(&intern);
bu_vls_free(&output_bot_name);
return BRLCAD_ERROR;
}
rt_db_free_internal(&intern);
bu_vls_printf(gedp->ged_result_str, "Remesh complete\n");
bu_vls_free(&output_bot_name);
return BRLCAD_OK;
@@ -384,4 +324,3 @@ _bot_cmd_remesh(void *bs, int argc, const char **argv)
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
+9 -13
View File
@@ -3,16 +3,21 @@ brlcad_find_package(manifold REQUIRED)
set(FACETIZE_LIBS libged libbu manifold::manifold)
add_subdirectory(subprocess)
add_subdirectory(tests)
set(
FACETIZE_SRCS
brep.cpp
facetize.cpp
nmg.cpp
orchestrator.cpp
plan.cpp
process.cpp
regions.cpp
transfer.cpp
tri.cpp
util.cpp
validation.cpp
worker.cpp
)
@@ -26,23 +31,14 @@ ged_plugin_library(ged-facetize
# Plugin requires subprocess to work
add_dependencies(ged-facetize ged_exec facetize_process)
# Old version of facetize
set(OLD_FACETIZE_SRCS
old_facetize.cpp
old_facetize_log.c
)
ged_plugin_library(ged-old_facetize
${OLD_FACETIZE_SRCS}
INCLUDES ${CMAKE_CURRENT_SOURCE_DIR}
LIBS ${FACETIZE_LIBS}
)
cmakefiles(
CMakeLists.txt
tess_opts.h
ged_facetize.h
old_facetize.h
orchestrator.h
process.h
transfer.h
validation.h
worker.h
TODO
)
+41 -30
View File
@@ -35,26 +35,27 @@
#include "./ged_facetize.h"
int
_nonovlp_brep_facetize(struct _ged_facetize_state *s, int argc, const char **argv)
_nonovlp_brep_facetize(struct _ged_facetize_state *s, const FacetizePlan &plan)
{
int newobj_cnt;
struct directory **dpa = NULL;
RT_CHECK_DBI(s->dbip);
if (argc <= 0) return BRLCAD_ERROR;
dpa = (struct directory **)bu_calloc(argc, sizeof(struct directory *), "dp array");
newobj_cnt = _ged_sort_existing_objs(s->dbip, argc, argv, dpa);
if (_ged_validate_objs_list(s, argc, argv, newobj_cnt) == BRLCAD_ERROR) {
bu_free(dpa, "dp array");
return BRLCAD_ERROR;
int argc = (int)plan.inputs.size();
std::vector<const char *> argv = plan.input_argv();
struct directory **dpa = (struct directory **)bu_calloc(argc,
sizeof(struct directory *), "BRep input directory array");
for (int i = 0; i < argc; i++) {
dpa[i] = db_lookup(s->dbip, argv[i], LOOKUP_QUIET);
if (!dpa[i]) {
facetize_failure(s, "BRep input object '%s' disappeared before processing", argv[i]);
bu_free(dpa, "BRep input directory array");
return BRLCAD_ERROR;
}
}
/* If anything specified has subtractions or intersections, we can't facetize it with
* this logic - that would require all-up Boolean evaluation processing. */
const char *non_union = "-bool + -or -bool -";
if (db_search(NULL, DB_SEARCH_QUIET, non_union, newobj_cnt, dpa, s->dbip, NULL, NULL, NULL) > 0) {
if (db_search(NULL, DB_SEARCH_QUIET, non_union, argc, dpa, s->dbip, NULL, NULL, NULL) > 0) {
bu_free(dpa, "dp array");
bu_vls_printf(s->gedp->ged_result_str, "Found intersection or subtraction objects in specified inputs - currently unsupported. Aborting.\n");
return BRLCAD_ERROR;
@@ -63,7 +64,7 @@ _nonovlp_brep_facetize(struct _ged_facetize_state *s, int argc, const char **arg
/* If anything other than combs or breps exists in the specified inputs, we can't
* process with this logic - requires a preliminary brep conversion. */
const char *obj_types = "! -type c -and ! -type brep";
if (db_search(NULL, DB_SEARCH_QUIET, obj_types, newobj_cnt, dpa, s->dbip, NULL, NULL, NULL) > 0) {
if (db_search(NULL, DB_SEARCH_QUIET, obj_types, argc, dpa, s->dbip, NULL, NULL, NULL) > 0) {
bu_free(dpa, "dp array");
bu_vls_printf(s->gedp->ged_result_str, "Found objects in specified inputs which are not of type comb or brep- currently unsupported. Aborting.\n");
return BRLCAD_ERROR;
@@ -83,12 +84,17 @@ _nonovlp_brep_facetize(struct _ged_facetize_state *s, int argc, const char **arg
bu_free(dpa, "dp array");
return BRLCAD_ERROR;
}
for (int i = 0; i < newobj_cnt; i++) {
int xac = 3;
for (int i = 0; i < argc; i++) {
int xac = 2;
const char *xav[3] = {NULL};
xav[0] = "xpush";
xav[1] = dpa[i]->d_namep;
ged_exec_xpush(wgedp, xac, (const char **)xav);
if (ged_exec_xpush(wgedp, xac, (const char **)xav) != BRLCAD_OK) {
facetize_failure(s, "xpush failed for BRep input '%s'", dpa[i]->d_namep);
ged_close(wgedp);
bu_free(dpa, "BRep input directory array");
return BRLCAD_ERROR;
}
}
/* Used the libged tolerances */
@@ -103,7 +109,7 @@ _nonovlp_brep_facetize(struct _ged_facetize_state *s, int argc, const char **arg
const char *active_breps = "-type brep";
struct bu_ptbl *br;
BU_ALLOC(br, struct bu_ptbl);
if (db_search(br, DB_SEARCH_RETURN_UNIQ_DP, active_breps, newobj_cnt, dpa, wgedp->dbip, NULL, NULL, NULL) < 0) {
if (db_search(br, DB_SEARCH_RETURN_UNIQ_DP, active_breps, argc, dpa, wgedp->dbip, NULL, NULL, NULL) < 0) {
bu_free(dpa, "dp array");
bu_free(br, "brep results");
return BRLCAD_ERROR;
@@ -210,13 +216,6 @@ _nonovlp_brep_facetize(struct _ged_facetize_state *s, int argc, const char **arg
}
}
/* Done changing stuff in working database. */
ged_close(wgedp);
for (size_t i = 0; i < ss_cdt.size(); i++) {
ON_Brep_CDT_Destroy(ss_cdt[i]);
}
/* Keep out just what we asked for into a .g file */
struct bu_vls kwfile = BU_VLS_INIT_ZERO;
bu_vls_sprintf(&kwfile, "%s_keep", bu_vls_cstr(s->wfile));
@@ -227,7 +226,21 @@ _nonovlp_brep_facetize(struct _ged_facetize_state *s, int argc, const char **arg
av[i+2] = argv[i];
}
av[argc+2] = NULL;
ged_exec_keep(wgedp, argc+2, av);
if (ged_exec_keep(wgedp, argc+2, av) != BRLCAD_OK) {
facetize_failure(s, "unable to stage processed BRep hierarchy");
bu_free(av, "av");
bu_vls_free(&kwfile);
ged_close(wgedp);
for (size_t i = 0; i < ss_cdt.size(); i++)
ON_Brep_CDT_Destroy(ss_cdt[i]);
return BRLCAD_ERROR;
}
/* Done changing stuff in working database. */
ged_close(wgedp);
for (size_t i = 0; i < ss_cdt.size(); i++)
ON_Brep_CDT_Destroy(ss_cdt[i]);
/* Merge working geometry into original file */
av[0] = "dbconcat";
@@ -235,14 +248,13 @@ _nonovlp_brep_facetize(struct _ged_facetize_state *s, int argc, const char **arg
av[2] = bu_vls_cstr(&kwfile);
av[3] = "brep_facetize_"; // TODO - customize
av[4] = NULL;
ged_exec_dbconcat(s->gedp, 4, av);
int concat_ret = ged_exec_dbconcat(s->gedp, 4, av);
bu_free(av, "av");
bu_vls_free(&kwfile);
/* Clean up */
bu_dirclear(s->wdir);
s->cleanup_workspace = true;
return BRLCAD_OK;
return (concat_ret == BRLCAD_OK) ? BRLCAD_OK : BRLCAD_ERROR;
}
// Local Variables:
@@ -253,4 +265,3 @@ _nonovlp_brep_facetize(struct _ged_facetize_state *s, int argc, const char **arg
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
+199 -299
View File
@@ -32,6 +32,7 @@
#include <vector>
#include "bu/app.h"
#include "bu/file.h"
#include "bu/path.h"
#include "bu/opt.h"
#include "wdb.h"
@@ -42,6 +43,8 @@
#include "./tess_opts.h"
#include "./ged_facetize.h"
static const char FACETIZE_NMG_OUTPUT_FILE_SUFFIX[] = "_nmg_outputs.g";
static int
facetize_process_output(struct bu_vls *output, const char **command)
{
@@ -98,223 +101,132 @@ _facetize_methods_help(struct ged *gedp)
bu_vls_free(&method_output);
}
struct _ged_facetize_state *
_ged_facetize_state_create()
static int
facetize_commit_nmg_outputs(struct _ged_facetize_state *s,
const std::vector<std::string> &output_names)
{
struct _ged_facetize_state *s = NULL;
BU_GET(s, struct _ged_facetize_state);
s->verbosity = 0;
s->no_empty = 0;
s->make_nmg = 0;
s->nonovlp_brep = 0;
s->no_fixup = 0;
s->nmg_booleval = 0;
s->use_variant_plan = 1;
s->tolerate_failures = 0;
s->tolerated_failures = 0;
s->tolerated_failure_details = 0;
s->tolerated_failure_omitted = 0;
s->inspection_regions = 0;
s->perturb_sa_tol = 10.0;
s->perturb_vol_tol = 10.0;
if (!s || output_names.empty())
return BRLCAD_ERROR;
s->wdir = NULL;
BU_GET(s->log_file, struct bu_vls);
bu_vls_init(s->log_file);
s->log_file_is_temporary = 0;
s->lfile = NULL;
BU_GET(s->failure_msg, struct bu_vls);
bu_vls_init(s->failure_msg);
BU_GET(s->tolerated_failure_log, struct bu_vls);
bu_vls_init(s->tolerated_failure_log);
BU_GET(s->region_summary, struct bu_vls);
bu_vls_init(s->region_summary);
BU_GET(s->primitive_summary, struct bu_vls);
bu_vls_init(s->primitive_summary);
BU_GET(s->inspection_log, struct bu_vls);
bu_vls_init(s->inspection_log);
BU_GET(s->wfile, struct bu_vls);
bu_vls_init(s->wfile);
BU_GET(s->bname, struct bu_vls);
bu_vls_init(s->bname);
s->regions = 0;
s->resume = 0;
s->in_place = 0;
BU_GET(s->suffix, struct bu_vls);
bu_vls_init(s->suffix);
BU_GET(s->prefix, struct bu_vls);
bu_vls_init(s->prefix);
BU_GET(s->solid_suffix, struct bu_vls);
bu_vls_init(s->solid_suffix);
bu_vls_sprintf(s->solid_suffix, ".bot");
s->max_time = 0;
s->max_pnts = 0;
s->tol = NULL;
s->nonovlp_threshold = 0;
s->gedp = NULL;
s->write_profiled = 0;
s->write_profile_bytes = 0.0;
s->write_profile_usec = 0.0;
s->variant_plan = NULL;
return s;
}
void _ged_facetize_state_destroy(struct _ged_facetize_state *s)
{
if (!s)
return;
if (s->wdir)
bu_free(s->wdir, "wdir");
if (s->bname) {
bu_vls_free(s->bname);
BU_PUT(s->bname, struct bu_vls);
}
if (s->lfile) {
fclose(s->lfile);
s->lfile = NULL;
}
if (s->log_file) {
bu_vls_free(s->log_file);
BU_PUT(s->log_file, struct bu_vls);
}
if (s->failure_msg) {
bu_vls_free(s->failure_msg);
BU_PUT(s->failure_msg, struct bu_vls);
}
if (s->tolerated_failure_log) {
bu_vls_free(s->tolerated_failure_log);
BU_PUT(s->tolerated_failure_log, struct bu_vls);
}
if (s->region_summary) {
bu_vls_free(s->region_summary);
BU_PUT(s->region_summary, struct bu_vls);
}
if (s->primitive_summary) {
bu_vls_free(s->primitive_summary);
BU_PUT(s->primitive_summary, struct bu_vls);
}
if (s->inspection_log) {
bu_vls_free(s->inspection_log);
BU_PUT(s->inspection_log, struct bu_vls);
}
if (s->wfile) {
bu_vls_free(s->wfile);
BU_PUT(s->wfile, struct bu_vls);
}
if (s->prefix) {
bu_vls_free(s->prefix);
BU_PUT(s->prefix, struct bu_vls);
}
if (s->suffix) {
bu_vls_free(s->suffix);
BU_PUT(s->suffix, struct bu_vls);
}
if (s->solid_suffix) {
bu_vls_free(s->solid_suffix);
BU_PUT(s->solid_suffix, struct bu_vls);
}
if (s->variant_plan) {
delete (FacetizeVariantPlan *)s->variant_plan;
s->variant_plan = NULL;
}
BU_PUT(s, struct _ged_facetize_state);
}
int
_ged_facetize_objs(struct _ged_facetize_state *s, int argc, const char **argv)
{
int ret = BRLCAD_ERROR;
int newobj_cnt, i;
int ok_cnt = 0;
const char *oname = NULL;
const char *av[2];
struct directory **dpa = NULL;
struct directory *idpa[2];
struct db_i *dbip = s->dbip;
RT_CHECK_DBI(dbip);
if (argc < 0) return BRLCAD_ERROR;
dpa = (struct directory **)bu_calloc(argc, sizeof(struct directory *), "dp array");
newobj_cnt = _ged_sort_existing_objs(dbip, argc, argv, dpa);
if (_ged_validate_objs_list(s, argc, argv, newobj_cnt) == BRLCAD_ERROR) {
bu_free(dpa, "dp array");
std::string keep_file = std::string(bu_vls_cstr(s->wfile)) +
FACETIZE_NMG_OUTPUT_FILE_SUFFIX;
(void)bu_file_delete(keep_file.c_str());
struct ged *working_gedp = ged_open("db", bu_vls_cstr(s->wfile), 1);
if (!working_gedp) {
facetize_failure(s, "unable to open staged NMG Boolean database '%s'",
bu_vls_cstr(s->wfile));
return BRLCAD_ERROR;
}
if (!s->in_place) {
oname = argv[argc-1];
argc--;
std::vector<const char *> keep_argv;
keep_argv.reserve(output_names.size() + 2);
keep_argv.push_back("keep");
keep_argv.push_back(keep_file.c_str());
for (const std::string &output_name : output_names)
keep_argv.push_back(output_name.c_str());
int keep_result = ged_exec_keep(working_gedp, (int)keep_argv.size(),
keep_argv.data());
ged_close(working_gedp);
if (keep_result != BRLCAD_OK) {
facetize_failure(s, "unable to stage NMG Boolean outputs for import");
(void)bu_file_delete(keep_file.c_str());
return BRLCAD_ERROR;
}
/* If we're doing an NMG output, or we have been instructed to, use the
* old-school libnmg booleval */
if (s->make_nmg || s->nmg_booleval) {
if (!s->in_place) {
ret = _ged_facetize_nmgeval(s, argc, argv, oname);
goto booleval_cleanup;
} else {
for (i = 0; i < argc; i++) {
av[0] = argv[i];
av[1] = NULL;
ret = _ged_facetize_nmgeval(s, 1, av, av[0]);
if (ret == BRLCAD_ERROR && s->tolerate_failures) {
facetize_tolerated_failure(s, "object '%s' failed during NMG boolean evaluation and was skipped", argv[i]);
continue;
}
if (ret == BRLCAD_ERROR)
goto booleval_cleanup;
ok_cnt++;
}
if (s->tolerate_failures && ok_cnt > 0)
ret = BRLCAD_OK;
goto booleval_cleanup;
const char *concat_argv[] = {"dbconcat", "-O", keep_file.c_str(), NULL};
int concat_result = ged_exec_dbconcat(s->gedp, 3, concat_argv);
(void)bu_file_delete(keep_file.c_str());
if (concat_result != BRLCAD_OK) {
facetize_failure(s, "unable to import staged NMG Boolean outputs");
return BRLCAD_ERROR;
}
bu_vls_trunc(s->gedp->ged_result_str, 0);
db_update_nref(s->dbip);
return BRLCAD_OK;
}
int
_ged_facetize_objs(struct _ged_facetize_state *s, const FacetizePlan &plan)
{
int ret = BRLCAD_ERROR;
int ok_cnt = 0;
struct db_i *dbip = s->dbip;
RT_CHECK_DBI(dbip);
int argc = (int)plan.inputs.size();
std::vector<const char *> argv = plan.input_argv();
struct directory **dpa = (struct directory **)bu_calloc(argc,
sizeof(struct directory *), "facetize input directory array");
for (int i = 0; i < argc; i++) {
dpa[i] = db_lookup(dbip, argv[i], LOOKUP_QUIET);
if (!dpa[i]) {
facetize_failure(s, "input object '%s' disappeared before evaluation", argv[i]);
bu_free(dpa, "facetize input directory array");
return BRLCAD_ERROR;
}
}
// If we're not doing NMG, use the Manifold booleval
if (!s->in_place) {
ret = _ged_facetize_booleval(s, argc, dpa, oname, false, false);
const char *output_name = plan.execution.writes_in_place() ?
NULL : plan.output.c_str();
if (plan.execution.uses_nmg_boolean()) {
if (_ged_facetize_working_file_setup(s, NULL) != BRLCAD_OK) {
facetize_failure(s,
"unable to prepare the NMG Boolean working database");
goto booleval_cleanup;
}
struct db_i *work_dbip = db_open(bu_vls_cstr(s->wfile),
DB_OPEN_READWRITE);
if (!work_dbip || db_dirbuild(work_dbip) < 0) {
if (work_dbip)
db_close(work_dbip);
facetize_failure(s,
"unable to open the NMG Boolean working database");
goto booleval_cleanup;
}
std::vector<std::string> successful_outputs;
if (!plan.execution.writes_in_place()) {
ret = _ged_facetize_nmgeval(s, work_dbip,
s->dbip->dbi_filename, plan.inputs, output_name);
if (ret == BRLCAD_OK)
successful_outputs.emplace_back(output_name);
} else {
for (int i = 0; i < argc; i++) {
std::vector<std::string> object_input(1, plan.inputs[i]);
ret = _ged_facetize_nmgeval(s, work_dbip,
s->dbip->dbi_filename, object_input, argv[i]);
if (ret == BRLCAD_ERROR && s->tolerate_failures) {
facetize_tolerated_failure(s,
"object '%s' failed during NMG boolean evaluation and was skipped",
argv[i]);
continue;
}
if (ret == BRLCAD_ERROR)
break;
successful_outputs.emplace_back(argv[i]);
}
if (s->tolerate_failures && !successful_outputs.empty())
ret = BRLCAD_OK;
}
db_close(work_dbip);
if (ret == BRLCAD_OK)
ret = facetize_commit_nmg_outputs(s, successful_outputs);
if (ret == BRLCAD_OK)
s->cleanup_workspace = true;
goto booleval_cleanup;
}
if (!plan.execution.writes_in_place()) {
ret = _ged_facetize_booleval(s, argc, dpa, output_name, false, false);
} else {
for (i = 0; i < argc; i++) {
idpa[0] = dpa[i];
idpa[1] = NULL;
ret = _ged_facetize_booleval(s, 1, (struct directory **)idpa, argv[i], false, false);
for (int i = 0; i < argc; i++) {
struct directory *object_dpa[] = {dpa[i], NULL};
ret = _ged_facetize_booleval(s, 1, object_dpa, argv[i], false, false);
if (ret == BRLCAD_ERROR && s->tolerate_failures) {
facetize_tolerated_failure(s, "object '%s' failed during BoT boolean evaluation and was skipped", argv[i]);
facetize_tolerated_failure(s,
"object '%s' failed during BoT boolean evaluation and was skipped",
argv[i]);
continue;
}
if (ret == BRLCAD_ERROR)
@@ -328,11 +240,10 @@ _ged_facetize_objs(struct _ged_facetize_state *s, int argc, const char **argv)
// Report on the primitive processing
facetize_collect_primitive_summary(s);
// After collecting info for summary, we can now clean up working files
bu_dirclear(s->wdir);
s->cleanup_workspace = true;
booleval_cleanup:
bu_free(dpa, "dp array");
bu_free(dpa, "facetize input directory array");
return ret;
}
@@ -348,22 +259,32 @@ ged_facetize_core(struct ged *gedp, int argc, const char *argv[])
long verbosity = 0;
int force_perturb = 0;
int disable_perturb = 0;
method_options_t *method_options = new method_options_t;
struct _ged_facetize_state *s = _ged_facetize_state_create();
s->gedp = gedp;
s->dbip = gedp->dbip;
s->method_opts = method_options;
int nmg_output = 0;
int region_mode = 0;
int in_place = 0;
int nmg_boolean = 0;
int nonoverlap_brep = 0;
bool use_perturbation = false;
GED_CHECK_DATABASE_OPEN(gedp, BRLCAD_ERROR);
GED_CHECK_READ_ONLY(gedp, BRLCAD_ERROR);
GED_CHECK_ARGC_GT_0(gedp, argc, BRLCAD_ERROR);
FacetizeSession session(gedp);
struct _ged_facetize_state *s = session.state();
method_options_t *method_options = session.method_options();
FacetizePlan plan;
/* General options */
struct bu_opt_desc d[25];
struct bu_opt_desc d[26];
BU_OPT(d[ 0], "h", "help", "", NULL, &print_help, "Print help and exit");
BU_OPT(d[ 1], "v", "verbose", "", &bu_opt_incr_long, &verbosity, "Verbose output (multiple flags increase verbosity)");
BU_OPT(d[ 2], "q", "quiet", "", NULL, &quiet, "Suppress all output (overrides verbose flag)");
BU_OPT(d[ 3], "n", "nmg-output", "", NULL, &(s->make_nmg), "Create an N-Manifold Geometry (NMG) object (default is to create a triangular BoT mesh). Note that this will disable most other processing options and may reduce the conversion success rate.");
BU_OPT(d[ 4], "r", "regions", "", NULL, &(s->regions), "For combs, walk the trees and create new copies of the hierarchies with each region's CSG tree replaced by a facetized evaluation of that region. By default, enables perturb methodology (can be disabled - see --no-perturb)");
BU_OPT(d[ 3], "n", "nmg-output", "", NULL, &nmg_output, "Create an N-Manifold Geometry (NMG) object (default is to create a triangular BoT mesh). Note that this will disable most other processing options and may reduce the conversion success rate.");
BU_OPT(d[ 4], "r", "regions", "", NULL, &region_mode, "For combs, walk the trees and create new copies of the hierarchies with each region's CSG tree replaced by a facetized evaluation of that region. By default, enables perturb methodology (can be disabled - see --no-perturb)");
BU_OPT(d[ 5], "s", "suffix", "<str>", &bu_opt_vls, s->suffix, "When creating new objects for facetize outputs, use this suffix to avoid conflicts");
BU_OPT(d[ 6], "p", "prefix", "<str>", &bu_opt_vls, s->prefix, "When creating new objects for facetize, use this prefix to avoid conflicts");
BU_OPT(d[ 7], "", "in-place", "", NULL, &(s->in_place), "Replace the specified object(s) with their facetizations. (Warning: this option changes pre-existing geometry!)");
BU_OPT(d[ 7], "", "in-place", "", NULL, &in_place, "Replace the specified object(s) with their facetizations. (Warning: this option changes pre-existing geometry!)");
BU_OPT(d[ 8], "", "max-time", "#", &bu_opt_int, &(s->max_time), "Maximum time to spend per object (in seconds). Default is method specific. Note that specifying shorter times may cut off conversions (particularly using sampling methods) that could succeed with longer runtimes. Per-method time limits can also be adjusted to allow longer runtimes on slower methods.");
BU_OPT(d[ 9], "", "max-pnts", "#", &bu_opt_int, &(s->max_pnts), "Maximum number of pnts per object to use when applying ray sampling methods.");
BU_OPT(d[10], "", "resume", "", NULL, &(s->resume), "Resume an interrupted conversion");
@@ -371,20 +292,17 @@ ged_facetize_core(struct ged *gedp, int argc, const char *argv[])
BU_OPT(d[12], "", "method-opts", "METHOD opt1=val opt2=val...", &_tess_method_opts, method_options, "For the specified method, set the specified options.");
BU_OPT(d[13], "", "no-empty", "", NULL, &(s->no_empty), "Do not output empty BoT objects if the boolean evaluation results in an empty solid.");
BU_OPT(d[14], "", "log-file", "<filename>", &bu_opt_vls, s->log_file, "Specify a location to use for the log file.");
BU_OPT(d[15], "", "nmg-booleval", "", NULL, &s->nmg_booleval, "Use libnmg Boolean evaluation algorithm, even if we're producing a BoT. Less robust, but if it succeeds it may produce cleaner output for coplanar inputs.");
BU_OPT(d[15], "", "nmg-booleval", "", NULL, &nmg_boolean, "Use libnmg Boolean evaluation algorithm, even if we're producing a BoT. Less robust, but if it succeeds it may produce cleaner output for coplanar inputs.");
BU_OPT(d[16], "", "disable-fixup", "", NULL, &s->no_fixup, "Disable post-processing steps intended to improve generated meshes.");
BU_OPT(d[17], "", "perturb", "", NULL, &force_perturb, "Enable the coplanarity-avoidance perturbation step (overrides non -r option default, conflicts with --no-perturb).");
BU_OPT(d[18], "", "no-perturb", "", NULL, &disable_perturb, "Disable the coplanarity-avoidance perturbation step (overrides -r option default, conflicts with --perturb).");
BU_OPT(d[19], "B", "", "", NULL, &s->nonovlp_brep, "EXPERIMENTAL: non-overlapping facetization to BoT objects of union-only brep comb tree.");
BU_OPT(d[19], "B", "", "", NULL, &nonoverlap_brep, "EXPERIMENTAL: non-overlapping facetization to BoT objects of union-only brep comb tree.");
BU_OPT(d[20], "t", "threshold", "#", &bu_opt_fastf_t, &s->nonovlp_threshold, "EXPERIMENTAL: max ovlp threshold length for -B mode.");
BU_OPT(d[21], "", "perturb-sa-tol", "#", &bu_opt_fastf_t, &s->perturb_sa_tol, "Surface-area percentage threshold (0-100) that triggers the coplanarity-avoidance perturb retry when the CSG Crofton SA differs from the BoT SA by more than this amount. Default is 10.");
BU_OPT(d[22], "", "perturb-vol-tol", "#", &bu_opt_fastf_t, &s->perturb_vol_tol, "Volume percentage threshold (0-100) that triggers the coplanarity-avoidance perturb retry when the CSG Crofton volume differs from the BoT volume by more than this amount. Default is 10.");
BU_OPT(d[23], "", "tolerate-failures", "", NULL, &s->tolerate_failures, "Continue after failed primitive or subtree evaluations and generate a partial result. The output will not be a complete representation of the input if any failures are tolerated.");
BU_OPT_NULL(d[24]);
GED_CHECK_DATABASE_OPEN(gedp, BRLCAD_ERROR);
GED_CHECK_READ_ONLY(gedp, BRLCAD_ERROR);
GED_CHECK_ARGC_GT_0(gedp, argc, BRLCAD_ERROR);
BU_OPT(d[24], "j", "jobs", "#", &bu_opt_int, &s->max_workers, "Maximum number of facetize worker processes. The default is selected conservatively from CPU and memory availability.");
BU_OPT_NULL(d[25]);
/* skip command name argv[0] */
argc-=(argc>0); argv+=(argc>0);
@@ -399,7 +317,7 @@ ged_facetize_core(struct ged *gedp, int argc, const char *argv[])
bu_vls_printf(gedp->ged_result_str, "option parsing failed: %s\n", bu_vls_cstr(&omsg));
ret = BRLCAD_ERROR;
bu_vls_free(&omsg);
goto ged_facetize_memfree;
goto ged_facetize_done;
}
bu_vls_free(&omsg);
@@ -407,17 +325,49 @@ ged_facetize_core(struct ged *gedp, int argc, const char *argv[])
if (force_perturb && disable_perturb) {
bu_vls_printf(gedp->ged_result_str, "Can only specify one of --perturb or --no-perturb\n");
ret = BRLCAD_ERROR;
goto ged_facetize_memfree;
goto ged_facetize_done;
}
if (s->max_workers < 0 || s->max_workers > MAX_PSW) {
bu_vls_printf(gedp->ged_result_str,
"--jobs must be between 0 and %d\n", MAX_PSW);
ret = BRLCAD_ERROR;
goto ged_facetize_done;
}
if (s->max_time < 0) {
bu_vls_printf(gedp->ged_result_str,
"--max-time must be greater than or equal to 0\n");
ret = BRLCAD_ERROR;
goto ged_facetize_done;
}
if (s->max_pnts < 0) {
bu_vls_printf(gedp->ged_result_str,
"--max-pnts must be greater than or equal to 0\n");
ret = BRLCAD_ERROR;
goto ged_facetize_done;
}
// Set no_perturb according to options. Enable by default for -r, disable
// if not doing -r (one large BoT, generally a less likely candidate for
// worrying about volume/surf_area matching.)
s->no_perturb = (s->regions) ? 0 : 1;
if (region_mode && nonoverlap_brep) {
bu_vls_printf(gedp->ged_result_str,
"--regions and -B select different processing scopes and cannot be combined\n");
ret = BRLCAD_ERROR;
goto ged_facetize_done;
}
s->execution.output_format = nmg_output ?
FacetizeOutputFormat::Nmg : FacetizeOutputFormat::Bot;
s->execution.boolean_engine = (nmg_output || nmg_boolean) ?
FacetizeBooleanEngine::Nmg : FacetizeBooleanEngine::Manifold;
s->execution.scope = nonoverlap_brep ? FacetizeScope::NonOverlappingBrep :
(region_mode ? FacetizeScope::Regions : FacetizeScope::Objects);
s->execution.commit_mode = in_place ?
FacetizeCommitMode::InPlace : FacetizeCommitMode::NewObject;
use_perturbation = region_mode;
if (disable_perturb)
s->no_perturb = 1;
use_perturbation = false;
if (force_perturb)
s->no_perturb = 0;
use_perturbation = true;
s->execution.perturb_mode = use_perturbation ?
FacetizePerturbMode::Enabled : FacetizePerturbMode::Disabled;
s->verbosity = (int)verbosity;
@@ -442,88 +392,38 @@ ged_facetize_core(struct ged *gedp, int argc, const char *argv[])
s->verbosity = -1;
/* Don't allow incorrect type suffixes */
if (s->make_nmg && BU_STR_EQUAL(bu_vls_cstr(s->solid_suffix), ".bot")) {
if (s->execution.writes_nmg() && BU_STR_EQUAL(bu_vls_cstr(s->solid_suffix), ".bot")) {
bu_vls_sprintf(s->solid_suffix, ".nmg");
}
if (!s->make_nmg && BU_STR_EQUAL(bu_vls_cstr(s->solid_suffix), ".nmg")) {
if (!s->execution.writes_nmg() && BU_STR_EQUAL(bu_vls_cstr(s->solid_suffix), ".nmg")) {
bu_vls_sprintf(s->solid_suffix, ".bot");
}
/* Check if we want/need help */
need_help += (argc < 1);
need_help += (argc < 2 && !s->in_place && !s->regions && !s->resume && !s->nonovlp_brep);
if (print_help || need_help || argc < 1) {
need_help = argc < (s->execution.writes_in_place() ? 1 : 2);
if (print_help || need_help) {
_ged_cmd_help(gedp, usage, d);
_facetize_methods_help(gedp);
ret = (need_help) ? BRLCAD_ERROR : BRLCAD_OK;
goto ged_facetize_memfree;
goto ged_facetize_done;
}
/* Beyond this point, we're likely to need info on the cache directory. Generate some
* paths and strings we will need. */
{
// Get the root filename
char rfname[MAXPATHLEN];
bu_file_realpath(gedp->dbip->dbi_filename, rfname);
bu_path_component(s->bname, rfname, BU_PATH_BASENAME);
// Hash the path string and construct a location in the cache directory
unsigned long long hash_num = bu_data_hash((void *)bu_vls_cstr(s->bname), bu_vls_strlen(s->bname));
struct bu_vls dname = BU_VLS_INIT_ZERO;
bu_vls_sprintf(&dname, "facetize_%llu", hash_num);
s->wdir = (char *)bu_calloc(MAXPATHLEN, sizeof(char), "wdir");
bu_dir(s->wdir, MAXPATHLEN, BU_DIR_CACHE, bu_vls_cstr(&dname), NULL);
// If we're starting over, clear the old working directory
if (!s->resume && bu_file_directory(s->wdir)) {
bu_dirclear(s->wdir);
}
if (!bu_file_directory(s->wdir)) {
// Set up the directory
bu_mkdir(s->wdir);
}
if (!bu_vls_strlen(s->log_file)) {
char tmplfile[MAXPATHLEN];
s->log_file_is_temporary = 1;
bu_vls_sprintf(&dname, "facetize_%s.log", bu_vls_cstr(s->bname));
bu_dir(tmplfile, MAXPATHLEN, s->wdir, bu_vls_cstr(&dname), NULL);
bu_vls_sprintf(s->log_file, "%s", tmplfile);
}
bu_vls_free(&dname);
s->lfile = fopen(bu_vls_cstr(s->log_file), "a");
if (!s->lfile) {
bu_vls_printf(gedp->ged_result_str, "Unable to open log file %s for writing\n", bu_vls_cstr(s->log_file));
ret = BRLCAD_ERROR;
goto ged_facetize_memfree;
}
if (s->execution.processes_breps() &&
NEAR_ZERO(s->nonovlp_threshold, SMALL_FASTF)) {
bu_vls_printf(gedp->ged_result_str,
"-B option requires a specified length threshold\n");
ret = BRLCAD_ERROR;
goto ged_facetize_done;
}
/* If we're doing the experimental brep-only logic, it's a separate process */
if (s->nonovlp_brep) {
if (NEAR_ZERO(s->nonovlp_threshold, SMALL_FASTF)) {
bu_vls_printf(gedp->ged_result_str, "-B option requires a specified length threshold\n");
ret = BRLCAD_ERROR;
goto ged_facetize_memfree;
}
ret = _nonovlp_brep_facetize(s, argc, argv);
goto ged_facetize_memfree;
if (facetize_build_plan(s, argc, argv, plan) != BRLCAD_OK ||
facetize_prepare_workspace(s, plan) != BRLCAD_OK) {
ret = BRLCAD_ERROR;
goto ged_facetize_done;
}
ret = facetize_execute_plan(s, plan);
/* Multi-region mode has a different processing logic */
if (s->regions) {
ret = _ged_facetize_regions(s, argc, argv);
} else {
ret = _ged_facetize_objs(s, argc, argv);
}
ged_facetize_memfree:
facetize_summary(s);
_ged_facetize_state_destroy(s);
delete method_options;
ged_facetize_done:
return ret;
}
+28 -17
View File
@@ -36,11 +36,12 @@
#include "vmath.h"
#include "bu/vls.h"
#include "bn/tol.h"
#include "bg/spsr.h"
#include "rt/geom.h"
#include "raytrace.h"
#include "ged/defines.h"
#include "./orchestrator.h"
__BEGIN_DECLS
#define FACETIZE_METHOD_ATTR "facetize_method"
@@ -50,10 +51,7 @@ struct _ged_facetize_state {
// Output
int verbosity;
int no_empty;
int make_nmg;
int nonovlp_brep;
int no_fixup;
int no_perturb;
int use_variant_plan;
int tolerate_failures;
int tolerated_failures;
@@ -68,6 +66,7 @@ struct _ged_facetize_state {
fastf_t perturb_vol_tol;
char *wdir;
bool cleanup_workspace;
struct bu_vls *wfile;
struct bu_vls *bname;
struct bu_vls *log_file;
@@ -80,14 +79,13 @@ struct _ged_facetize_state {
struct bu_vls *inspection_log;
// Processing
int regions;
FacetizeExecutionOptions execution;
int resume;
int in_place;
int nmg_booleval;
// Settings
int max_time;
int max_pnts;
int max_workers;
struct bu_vls *prefix;
struct bu_vls *suffix;
@@ -102,7 +100,6 @@ struct _ged_facetize_state {
struct db_i *dbip;
union tree *facetize_tree;
void *method_opts;
void *log_s;
/* Cache-local write measurements seed and refine worker write deadlines. */
int write_profiled;
@@ -132,13 +129,15 @@ extern int
_db_uniq_test(struct bu_vls *n, void *data);
extern int
_ged_validate_objs_list(struct _ged_facetize_state *s, int argc, const char *argv[], int newobj_cnt);
_ged_facetize_regions(struct _ged_facetize_state *s, const FacetizePlan &plan);
extern int
_ged_facetize_regions(struct _ged_facetize_state *s, int argc, const char **argv);
_ged_facetize_objs(struct _ged_facetize_state *s, const FacetizePlan &plan);
extern int
_ged_facetize_nmgeval(struct _ged_facetize_state *s, int argc, const char **argv, const char *newname);
_ged_facetize_nmgeval(struct _ged_facetize_state *s,
struct db_i *target_dbip, const char *database_path,
const std::vector<std::string> &input_names, const char *newname);
extern int
_ged_facetize_booleval(struct _ged_facetize_state *s, int argc, struct directory **dpa, const char *newname, bool output_to_working, bool cleanup);
@@ -158,7 +157,16 @@ _ged_facetize_leaves_tri(struct _ged_facetize_state *s, struct db_i *dbip, struc
extern int
_ged_facetize_booleval_tri(struct _ged_facetize_state *s, struct db_i *dbip, struct rt_wdb *wdbp, int argc, const char **argv, const char *newname, struct bu_list *vlfree, bool output_to_working, int curr_cnt, int total_cnt);
extern int _nonovlp_brep_facetize(struct _ged_facetize_state *s, int argc, const char **argv);
/**
* Evaluate a tessellated CSG tree and write the resulting BoT to an explicit
* database. The input database is never modified unless it is also supplied
* as @p output_dbip. This form lets isolated workers evaluate into an
* in-memory database before entering the staged-write protocol.
*/
extern int
_ged_facetize_booleval_tri_to_db(struct _ged_facetize_state *s, struct db_i *dbip, struct rt_wdb *wdbp, int argc, const char **argv, const char *newname, struct bu_list *vlfree, struct db_i *output_dbip, int curr_cnt, int total_cnt);
extern int _nonovlp_brep_facetize(struct _ged_facetize_state *s, const FacetizePlan &plan);
extern struct rt_bot_internal *
bot_fixup(struct _ged_facetize_state *s, struct db_i *wdbip, struct directory *bot_dp, const char *bname);
@@ -229,17 +237,20 @@ struct FacetizeVariantPlan {
* Returns an allocated FacetizeVariantPlan owned by the caller (or NULL on
* allocation failure). Primitives without ft_perturb support are counted in
* n_perturb_fallbacks and will fall back to the original mesh at booleval time.
* If working_dbip is non-NULL it must be an indexed writable handle for the
* working database; it is borrowed and remains open on return.
*/
extern FacetizeVariantPlan *
_ged_facetize_build_variant_plan(struct _ged_facetize_state *s,
int argc,
struct directory **dpa);
struct directory **dpa,
struct db_i *working_dbip);
/**
* Tessellate the variant primitives in the working .g using the NMG method.
* Called after _ged_facetize_leaves_tri() once original leaves are already
* BoTs, either eagerly for direct booleval or lazily on the first
* validation-triggered retry in region mode. Updates
* Tessellate the variant primitives in the working .g using the configured
* primitive methods and options. Called after _ged_facetize_leaves_tri() once
* original leaves are already BoTs, either eagerly for direct booleval or
* lazily on the first validation-triggered retry in region mode. Updates
* plan->n_variant_tess_failures for any variants that could not be
* tessellated (they will silently fall back to the original mesh at booleval).
*/
+158 -380
View File
@@ -19,405 +19,183 @@
*/
/** @file libged/facetize/nmg.cpp
*
* Classic NMG boolean evaluation path.
*
* Parent-side launch policy for isolated NMG Boolean evaluation.
*/
#include "common.h"
#include <string.h>
#include "bio.h"
#include <string>
#include <vector>
#include "bu/app.h"
#include "bu/datetime.h"
#include "bu/file.h"
#include "bu/hook.h"
#include "bu/vls.h"
#include "bu/log.h"
#include "bu/path.h"
#include "bu/process.h"
#include "bu/snooze.h"
#include "raytrace.h"
#include "../ged_private.h"
#include "./ged_facetize.h"
#include "./process.h"
#include "./transfer.h"
#include "./worker.h"
struct _ged_facetize_logging_state {
struct bu_hook_list *saved_bomb_hooks;
struct bu_hook_list *saved_log_hooks;
struct bu_vls *nmg_log;
struct bu_vls *nmg_log_header;
int nmg_log_print_header;
int stderr_stashed;
int serr;
int fnull;
};
extern "C" {
static int
_facetize_bomb_hook(void *cdata, void *str)
{
struct _ged_facetize_state *o = (struct _ged_facetize_state *)cdata;
struct _ged_facetize_logging_state *log_s = (struct _ged_facetize_logging_state *)o->log_s;
if (log_s->nmg_log_print_header) {
bu_vls_printf(log_s->nmg_log, "%s\n", bu_vls_addr(log_s->nmg_log_header));
log_s->nmg_log_print_header = 0;
}
bu_vls_printf(log_s->nmg_log, "%s\n", (const char *)str);
return 0;
}
static int
_facetize_nmg_logging_hook(void *data, void *str)
{
struct _ged_facetize_state *o = (struct _ged_facetize_state *)data;
struct _ged_facetize_logging_state *log_s = (struct _ged_facetize_logging_state *)o->log_s;
if (log_s->nmg_log_print_header) {
bu_vls_printf(log_s->nmg_log, "%s\n", bu_vls_addr(log_s->nmg_log_header));
log_s->nmg_log_print_header = 0;
}
bu_vls_printf(log_s->nmg_log, "%s\n", (const char *)str);
return 0;
}
static void
_facetize_log_nmg(struct _ged_facetize_state *o)
{
if (fileno(stderr) < 0)
return;
/* Seriously, bu_bomb, we don't want you blathering
* to stderr... shut down stderr temporarily. */
struct _ged_facetize_logging_state *log_s = (struct _ged_facetize_logging_state *)o->log_s;
log_s->fnull = open(bu_file_null(), O_WRONLY);
if (log_s->fnull != -1) {
log_s->serr = fileno(stderr);
log_s->stderr_stashed = dup(log_s->serr);
dup2(log_s->fnull, log_s->serr);
close(log_s->fnull);
}
/* Set bu_log logging to capture in nmg_log, rather than the
* application defaults */
bu_log_hook_delete_all();
bu_log_add_hook(_facetize_nmg_logging_hook, (void *)o);
/* Also engage the nmg bomb hooks */
bu_bomb_delete_all_hooks();
bu_bomb_add_hook(_facetize_bomb_hook, (void *)o);
}
static void
_facetize_log_default(struct _ged_facetize_state *o)
{
if (fileno(stderr) < 0 || !o || !o->log_s)
return;
/* Put stderr back */
struct _ged_facetize_logging_state *log_s = (struct _ged_facetize_logging_state *)o->log_s;
if (log_s->fnull != -1) {
fflush(stderr);
dup2(log_s->stderr_stashed, log_s->serr);
close(log_s->stderr_stashed);
log_s->fnull = -1;
}
/* Restore bu_bomb hooks to the application defaults */
bu_bomb_delete_all_hooks();
bu_bomb_restore_hooks(log_s->saved_bomb_hooks);
/* Restore bu_log hooks to the application defaults */
bu_log_hook_delete_all();
bu_log_hook_restore_all(log_s->saved_log_hooks);
}
}
static union tree *
facetize_region_end(struct db_tree_state *tsp,
const struct db_full_path *pathp,
union tree *curtree,
void *client_data)
{
union tree **facetize_tree;
if (tsp) RT_CK_DBTS(tsp);
if (pathp) RT_CK_FULL_PATH(pathp);
struct _ged_facetize_state *s = (struct _ged_facetize_state *)client_data;
facetize_tree = &s->facetize_tree;
if (curtree->tr_op == OP_NOP) return curtree;
if (*facetize_tree) {
union tree *tr;
BU_ALLOC(tr, union tree);
RT_TREE_INIT(tr);
tr->tr_op = OP_UNION;
tr->tr_b.tb_regionp = REGION_NULL;
tr->tr_b.tb_left = *facetize_tree;
tr->tr_b.tb_right = curtree;
*facetize_tree = tr;
} else {
*facetize_tree = curtree;
}
/* Tree has been saved, and will be freed later */
return TREE_NULL;
}
static union tree *
facetize_nmg_leaf_tess(struct db_tree_state *tsp, const struct db_full_path *pathp, struct rt_db_internal *ip, void *client_data)
{
union tree *ret = rt_booltree_leaf_tess(tsp, pathp, ip, NULL);
if (!ret) {
struct _ged_facetize_state *s = (struct _ged_facetize_state *)client_data;
if (s && s->tolerate_failures && pathp) {
char *path_str = db_path_to_string(pathp);
facetize_tolerated_failure(s, "NMG leaf tessellation failed for '%s'; leaf will be omitted from boolean evaluation", path_str ? path_str : "(unknown)");
if (path_str)
bu_free(path_str, "path string");
}
}
return ret;
}
static struct model *
_try_nmg_facetize(struct _ged_facetize_state *s, struct bu_list *vlfree, int argc, const char **argv)
{
struct db_i *dbip = s->dbip;
int i;
int failed = 0;
struct db_tree_state init_state;
union tree *facetize_tree;
struct model *nmg_model;
struct rt_wdb *wdbp = wdb_dbopen(dbip, RT_WDB_TYPE_DB_DEFAULT);
struct _ged_facetize_logging_state *log_s;
BU_GET(log_s, struct _ged_facetize_logging_state);
BU_GET(log_s->nmg_log, struct bu_vls);
bu_vls_init(log_s->nmg_log);
BU_GET(log_s->nmg_log_header, struct bu_vls);
bu_vls_init(log_s->nmg_log_header);
s->log_s = log_s;
_facetize_log_nmg(s);
db_init_db_tree_state(&init_state, dbip);
/* Establish tolerances */
init_state.ts_ttol = &wdbp->wdb_ttol;
init_state.ts_tol = &wdbp->wdb_tol;
s->facetize_tree = (union tree *)0;
facetize_tree = (union tree *)0;
nmg_model = nmg_mm();
init_state.ts_m = &nmg_model;
if (!BU_SETJUMP) {
/* try */
i = db_walk_tree(dbip, argc, (const char **)argv,
1,
&init_state,
0, /* take all regions */
facetize_region_end,
facetize_nmg_leaf_tess,
(void *)s
);
} else {
/* catch */
BU_UNSETJUMP;
_facetize_log_default(s);
bu_vls_free(log_s->nmg_log_header);
bu_vls_free(log_s->nmg_log);
BU_PUT(log_s->nmg_log_header, struct _ged_facetize_logging_state);
BU_PUT(log_s->nmg_log, struct _ged_facetize_logging_state);
BU_PUT(log_s, struct _ged_facetize_logging_state);
s->log_s = NULL;
if (s->facetize_tree) {
db_free_tree(s->facetize_tree);
s->facetize_tree = NULL;
}
return NULL;
} BU_UNSETJUMP;
facetize_tree = s->facetize_tree;
if (i < 0) {
/* Destroy NMG */
_facetize_log_default(s);
bu_vls_free(log_s->nmg_log_header);
bu_vls_free(log_s->nmg_log);
BU_PUT(log_s->nmg_log_header, struct _ged_facetize_logging_state);
BU_PUT(log_s->nmg_log, struct _ged_facetize_logging_state);
BU_PUT(log_s, struct _ged_facetize_logging_state);
s->log_s = NULL;
if (s->facetize_tree) {
db_free_tree(s->facetize_tree);
s->facetize_tree = NULL;
}
return NULL;
}
if (facetize_tree) {
if (!BU_SETJUMP) {
/* try */
failed = nmg_boolean(facetize_tree, nmg_model, vlfree, &wdbp->wdb_tol);
} else {
/* catch */
BU_UNSETJUMP;
_facetize_log_default(s);
bu_vls_free(log_s->nmg_log_header);
bu_vls_free(log_s->nmg_log);
BU_PUT(log_s->nmg_log_header, struct _ged_facetize_logging_state);
BU_PUT(log_s->nmg_log, struct _ged_facetize_logging_state);
BU_PUT(log_s, struct _ged_facetize_logging_state);
s->log_s = NULL;
if (s->facetize_tree) {
db_free_tree(s->facetize_tree);
s->facetize_tree = NULL;
}
return NULL;
} BU_UNSETJUMP;
} else {
failed = 1;
}
if (!failed && facetize_tree) {
NMG_CK_REGION(facetize_tree->tr_d.td_r);
facetize_tree->tr_d.td_r = (struct nmgregion *)NULL;
}
if (failed && s->tolerate_failures) {
facetize_tolerated_failure(s, "NMG boolean evaluation failed after leaf tessellation; no partial NMG result could be generated for this tree");
}
if (facetize_tree) {
db_free_tree(facetize_tree);
s->facetize_tree = NULL;
}
_facetize_log_default(s);
bu_vls_free(log_s->nmg_log_header);
bu_vls_free(log_s->nmg_log);
BU_PUT(log_s->nmg_log_header, struct _ged_facetize_logging_state);
BU_PUT(log_s->nmg_log, struct _ged_facetize_logging_state);
BU_PUT(log_s, struct _ged_facetize_logging_state);
s->log_s = NULL;
return (failed) ? NULL : nmg_model;
}
static int
_write_nmg(struct _ged_facetize_state *s, struct model *nmg_model, const char *name)
{
struct db_i *dbip = s->dbip;
struct rt_db_internal intern;
struct directory *dp;
/* Export NMG as a new solid */
RT_DB_INTERNAL_INIT(&intern);
intern.idb_major_type = DB5_MAJORTYPE_BRLCAD;
intern.idb_type = ID_NMG;
intern.idb_meth = &OBJ[ID_NMG];
intern.idb_ptr = (void *)nmg_model;
dp = db_diradd(dbip, name, RT_DIR_PHONY_ADDR, 0, RT_DIR_SOLID, (void *)&intern.idb_type);
if (dp == RT_DIR_NULL) {
if (s->verbosity > 0) {
bu_log("Cannot add %s to directory\n", name);
}
return BRLCAD_ERROR;
}
if (rt_db_put_internal(dp, dbip, &intern) < 0) {
if (s->verbosity > 0) {
bu_log("Failed to write %s to database\n", name);
}
rt_db_free_internal(&intern);
return BRLCAD_ERROR;
}
return BRLCAD_OK;
}
static int
_write_bot(struct _ged_facetize_state *s, struct rt_bot_internal *bot, const char *name)
{
struct db_i *dbip = s->dbip;
struct rt_db_internal intern;
struct directory *dp;
/* Export BoT as a new solid */
RT_DB_INTERNAL_INIT(&intern);
intern.idb_major_type = DB5_MAJORTYPE_BRLCAD;
intern.idb_type = ID_BOT;
intern.idb_meth = &OBJ[ID_BOT];
intern.idb_ptr = (void *)bot;
dp = db_diradd(dbip, name, RT_DIR_PHONY_ADDR, 0, RT_DIR_SOLID, (void *)&intern.idb_type);
if (dp == RT_DIR_NULL) {
if (s->verbosity > 0) {
bu_log("Cannot add %s to directory\n", name);
}
return BRLCAD_ERROR;
}
if (rt_db_put_internal(dp, dbip, &intern) < 0) {
if (s->verbosity > 0) {
bu_log("Failed to write %s to database\n", name);
}
rt_db_free_internal(&intern);
return BRLCAD_ERROR;
}
return BRLCAD_OK;
}
static const int FACETIZE_NMG_POLL_USEC = 1000;
static const char FACETIZE_NMG_RESULT_FILE[] = "nmg_boolean_result.g";
int
_ged_facetize_nmgeval(struct _ged_facetize_state *s, int argc, const char **argv, const char *oname)
_ged_facetize_nmgeval(struct _ged_facetize_state *s,
struct db_i *target_dbip, const char *database_path,
const std::vector<std::string> &input_names, const char *output_name)
{
int ret = BRLCAD_OK;
struct db_i *dbip = s->dbip;
struct rt_wdb *wdbp;
struct rt_bot_internal *bot = NULL;
struct bu_list *vlfree = &rt_vlfree;
struct model *nmg_model = _try_nmg_facetize(s, vlfree, argc, argv);
if (!s || !target_dbip || !database_path || !database_path[0] ||
input_names.empty() || !output_name || !output_name[0] || !s->wdir)
return BRLCAD_ERROR;
if (nmg_model == NULL) {
if (s->verbosity > 1) {
bu_log("NMG(%s): no resulting region, aborting\n", oname);
FacetizeWorkerRequest request;
request.operation = s->execution.writes_nmg() ?
FacetizeWorkerOperation::NmgBooleanToNmg :
FacetizeWorkerOperation::NmgBooleanToBot;
request.input_names = input_names;
request.output_name = output_name;
if (!request.valid())
return BRLCAD_ERROR;
char result_file[MAXPATHLEN];
bu_dir(result_file, MAXPATHLEN, s->wdir, FACETIZE_NMG_RESULT_FILE, NULL);
(void)bu_file_delete(result_file);
char executable[MAXPATHLEN];
bu_dir(executable, MAXPATHLEN, BU_DIR_BIN, "ged_exec", BU_DIR_EXT, NULL);
std::vector<std::string> command;
command.push_back(executable);
command.push_back("facetize_process");
command.push_back(database_path);
struct bu_process *process = NULL;
FILE *process_input = NULL;
FacetizeWorkerClient channel;
if (facetize_process_start(&process, &process_input, channel, command,
result_file, "--nmg-server") != BRLCAD_OK) {
(void)bu_file_delete(result_file);
facetize_log(s, 0,
"FACETIZE: unable to start the NMG Boolean worker for %s\n",
output_name);
return BRLCAD_ERROR;
}
if (!channel.send_request(request)) {
(void)facetize_process_stop(s, &process, process_input, channel, true);
(void)bu_file_delete(result_file);
facetize_log(s, 0,
"FACETIZE: unable to submit %s to the NMG Boolean worker\n",
output_name);
return BRLCAD_ERROR;
}
facetize_log(s, 1, "FACETIZE: evaluating %s with NMG Boolean...\n",
output_name);
FacetizeWorkerStatus status;
int64_t request_start = bu_gettime();
int64_t write_deadline = 0;
bool write_permitted = false;
bool interrupted = false;
bool evaluation_timed_out = false;
bool write_timed_out = false;
while (!status.result_received) {
facetize_process_drain_stdout(s, process, channel, &status);
facetize_process_drain_stderr(s, process);
int64_t now = bu_gettime();
if (status.write_ready && !write_permitted) {
if (s->max_time > 0 && now - request_start >=
BU_SEC2USEC(s->max_time)) {
interrupted = true;
evaluation_timed_out = true;
break;
}
write_permitted = true;
double write_timeout = facetize_write_timeout_seconds(
status.payload_size, 0.0, 0.0);
write_deadline = now + BU_SEC2USEC(write_timeout);
if (!channel.send_write_proceed()) {
interrupted = true;
break;
}
continue;
}
ret = BRLCAD_ERROR;
goto ged_nmg_obj_memfree;
if (status.result_received) {
if (status.write_started && !status.write_done)
interrupted = true;
break;
}
if (bu_process_poll(process, NULL) != 0) {
/* The final status may reach the pipe just before process exit.
* Drain once more before deciding the worker was interrupted. */
facetize_process_drain_stdout(s, process, channel, &status);
facetize_process_drain_stderr(s, process);
interrupted = !status.result_received ||
(status.write_started && !status.write_done);
break;
}
if (!write_permitted && s->max_time > 0 &&
now - request_start >= BU_SEC2USEC(s->max_time)) {
interrupted = true;
evaluation_timed_out = true;
break;
}
if (write_permitted && now >= write_deadline) {
interrupted = true;
write_timed_out = true;
break;
}
(void)bu_snooze(FACETIZE_NMG_POLL_USEC);
}
if (!s->make_nmg) {
wdbp = wdb_dbopen(dbip, RT_WDB_TYPE_DB_DEFAULT);
if (!BU_SETJUMP) {
/* try */
bot = (struct rt_bot_internal *)nmg_mdl_to_bot(nmg_model, vlfree, &wdbp->wdb_tol);
} else {
/* catch */
BU_UNSETJUMP;
return BRLCAD_ERROR;
} BU_UNSETJUMP;
ret = _write_bot(s, bot, oname);
int process_status = facetize_process_stop(s, &process, process_input,
channel, interrupted);
int ret = BRLCAD_ERROR;
if (!interrupted && process_status == BRLCAD_OK &&
status.result_received && status.write_done &&
status.result == BRLCAD_OK) {
int expected_type = request.operation ==
FacetizeWorkerOperation::NmgBooleanToNmg ? ID_NMG : ID_BOT;
ret = facetize_transfer_staged_object(target_dbip, result_file,
output_name, expected_type);
}
(void)bu_file_delete(result_file);
if (ret == BRLCAD_OK) {
facetize_log(s, 1,
"FACETIZE: NMG Boolean evaluation succeeded for %s\n",
output_name);
return BRLCAD_OK;
}
if (evaluation_timed_out) {
facetize_log(s, 0,
"FACETIZE: NMG Boolean evaluation timed out after %d seconds for %s\n",
s->max_time, output_name);
} else if (write_timed_out) {
facetize_log(s, 0,
"FACETIZE: staging the NMG Boolean result timed out for %s\n",
output_name);
} else if (interrupted) {
facetize_log(s, 0,
"FACETIZE: NMG Boolean worker exited while processing %s\n",
output_name);
} else if (process_status != BRLCAD_OK) {
facetize_log(s, 0,
"FACETIZE: NMG Boolean worker exited abnormally after processing %s\n",
output_name);
} else if (status.result != BRLCAD_OK) {
facetize_log(s, 0,
"FACETIZE: NMG Boolean evaluation failed for %s\n",
output_name);
} else {
/* Write the NMG */
ret = _write_nmg(s, nmg_model, oname);
facetize_log(s, 0,
"FACETIZE: unable to transfer the staged NMG Boolean result for %s\n",
output_name);
}
ged_nmg_obj_memfree:
if (s->verbosity >= 0 && ret != BRLCAD_OK) {
bu_log("NMG: failed to generate %s\n", oname);
}
return ret;
return BRLCAD_ERROR;
}
// Local Variables:
File diff suppressed because it is too large Load Diff
-92
View File
@@ -1,92 +0,0 @@
/* O L D _ F A C E T I Z E . H
* BRL-CAD
*
* Copyright (c) 2008-2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library 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 this file; see the file named COPYING for more
* information.
*/
/** @file libged/old_facetize.h
*
* The facetize command, circa v7.38.2
*
*/
#include "common.h"
#include "vmath.h"
#include "bu.h"
#include "bg.h"
__BEGIN_DECLS
/* Ideally all of this could be in facetize.cpp, but the open() calls
* used by the logging routines are problematic in C++ with Visual C++. */
struct _old_ged_facetize_opts {
int quiet;
int verbosity;
int regions;
int resume;
int retry;
int in_place;
fastf_t feature_size;
fastf_t feature_scale;
fastf_t d_feature_size;
int max_time;
struct bg_tess_tol *tol;
struct bu_vls *faceted_suffix;
/* NMG specific options */
int triangulate;
int make_nmg;
int nmgbool;
int manifold;
int screened_poisson;
int continuation;
int method_flags;
int nmg_use_tnurbs;
/* Poisson specific options */
int max_pnts;
struct bg_3d_spsr_opts s_opts;
/* Brep specific options */
double nonovlp_threshold;
/* internal */
struct bu_attribute_value_set *c_map;
struct bu_attribute_value_set *s_map;
struct bu_hook_list *saved_bomb_hooks;
struct bu_hook_list *saved_log_hooks;
struct bu_vls *nmg_log;
struct bu_vls *nmg_log_header;
int nmg_log_print_header;
int stderr_stashed;
int serr;
int fnull;
struct bu_vls *froot;
struct bu_vls *manifold_comb;
struct bu_vls *nmg_comb;
struct bu_vls *continuation_comb;
struct bu_vls *spsr_comb;
};
extern void
_old_ged_facetize_log_nmg(struct _old_ged_facetize_opts *o);
extern void
_old_ged_facetize_log_default(struct _old_ged_facetize_opts *o);
__END_DECLS
-119
View File
@@ -1,119 +0,0 @@
/* F A C E T I Z E _ L O G . C
* BRL-CAD
*
* Copyright (c) 2008-2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library 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 this file; see the file named COPYING for more
* information.
*/
/** @file libged/facetize_log.c
*
* logging mechanisms for the facetize command.
*
*/
#include "common.h"
#include <string.h>
#include "bio.h"
#include "bu/hook.h"
#include "bu/vls.h"
#include "../ged_private.h"
#include "./old_facetize.h"
static int
_ged_facetize_bomb_hook(void *cdata, void *str)
{
struct _old_ged_facetize_opts *o = (struct _old_ged_facetize_opts *)cdata;
if (o->nmg_log_print_header) {
bu_vls_printf(o->nmg_log, "%s\n", bu_vls_addr(o->nmg_log_header));
o->nmg_log_print_header = 0;
}
bu_vls_printf(o->nmg_log, "%s\n", (const char *)str);
return 0;
}
static int
_ged_facetize_nmg_logging_hook(void *data, void *str)
{
struct _old_ged_facetize_opts *o = (struct _old_ged_facetize_opts *)data;
if (o->nmg_log_print_header) {
bu_vls_printf(o->nmg_log, "%s\n", bu_vls_addr(o->nmg_log_header));
o->nmg_log_print_header = 0;
}
bu_vls_printf(o->nmg_log, "%s\n", (const char *)str);
return 0;
}
void
_old_ged_facetize_log_nmg(struct _old_ged_facetize_opts *o)
{
if (fileno(stderr) < 0)
return;
/* Seriously, bu_bomb, we don't want you blathering
* to stderr... shut down stderr temporarily. */
o->fnull = open(bu_file_null(), O_WRONLY);
if (o->fnull != -1) {
o->serr = fileno(stderr);
o->stderr_stashed = dup(o->serr);
dup2(o->fnull, o->serr);
close(o->fnull);
}
/* Set bu_log logging to capture in nmg_log, rather than the
* application defaults */
bu_log_hook_delete_all();
bu_log_add_hook(_ged_facetize_nmg_logging_hook, (void *)o);
/* Also engage the nmg bomb hooks */
bu_bomb_delete_all_hooks();
bu_bomb_add_hook(_ged_facetize_bomb_hook, (void *)o);
}
void
_old_ged_facetize_log_default(struct _old_ged_facetize_opts *o)
{
if (fileno(stderr) < 0)
return;
/* Put stderr back */
if (o->fnull != -1) {
fflush(stderr);
dup2(o->stderr_stashed, o->serr);
close(o->stderr_stashed);
o->fnull = -1;
}
/* Restore bu_bomb hooks to the application defaults */
bu_bomb_delete_all_hooks();
bu_bomb_restore_hooks(o->saved_bomb_hooks);
/* Restore bu_log hooks to the application defaults */
bu_log_hook_delete_all();
bu_log_hook_restore_all(o->saved_log_hooks);
}
/*
* Local Variables:
* tab-width: 8
* mode: C
* indent-tabs-mode: t
* c-file-style: "stroustrup"
* End:
* ex: shiftwidth=4 tabstop=8
*/
+363
View File
@@ -0,0 +1,363 @@
/* O R C H E S T R A T O R . C P P
* BRL-CAD
*
* Copyright (c) 2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*/
/** @file libged/facetize/orchestrator.cpp
*
* Command planning, session lifetime, and workspace ownership for facetize.
*/
#include "common.h"
#include <cstring>
#include <cstdio>
#include <fstream>
#include <sstream>
#include <string>
#include <sys/stat.h>
#include "bu/app.h"
#include "bu/file.h"
#include "bu/path.h"
#include "bu/vls.h"
#include "../ged_private.h"
#include "./ged_facetize.h"
#include "./tess_opts.h"
static const unsigned int FACETIZE_WORKSPACE_SCHEMA = 1;
static const char FACETIZE_MANIFEST_NAME[] = "request.manifest";
std::vector<const char *>
FacetizePlan::input_argv() const
{
std::vector<const char *> argv;
argv.reserve(inputs.size());
for (const std::string &input : inputs)
argv.push_back(input.c_str());
return argv;
}
static struct _ged_facetize_state *
facetize_state_create()
{
struct _ged_facetize_state *s = NULL;
BU_GET(s, struct _ged_facetize_state);
s->verbosity = 0;
s->no_empty = 0;
s->no_fixup = 0;
s->use_variant_plan = 1;
s->tolerate_failures = 0;
s->tolerated_failures = 0;
s->tolerated_failure_details = 0;
s->tolerated_failure_omitted = 0;
s->inspection_regions = 0;
s->perturb_sa_tol = 10.0;
s->perturb_vol_tol = 10.0;
s->wdir = NULL;
s->cleanup_workspace = false;
BU_GET(s->log_file, struct bu_vls);
bu_vls_init(s->log_file);
s->log_file_is_temporary = 0;
s->lfile = NULL;
BU_GET(s->failure_msg, struct bu_vls);
bu_vls_init(s->failure_msg);
BU_GET(s->tolerated_failure_log, struct bu_vls);
bu_vls_init(s->tolerated_failure_log);
BU_GET(s->region_summary, struct bu_vls);
bu_vls_init(s->region_summary);
BU_GET(s->primitive_summary, struct bu_vls);
bu_vls_init(s->primitive_summary);
BU_GET(s->inspection_log, struct bu_vls);
bu_vls_init(s->inspection_log);
BU_GET(s->wfile, struct bu_vls);
bu_vls_init(s->wfile);
BU_GET(s->bname, struct bu_vls);
bu_vls_init(s->bname);
BU_GET(s->suffix, struct bu_vls);
bu_vls_init(s->suffix);
BU_GET(s->prefix, struct bu_vls);
bu_vls_init(s->prefix);
BU_GET(s->solid_suffix, struct bu_vls);
bu_vls_init(s->solid_suffix);
bu_vls_sprintf(s->solid_suffix, ".bot");
s->resume = 0;
s->max_time = 0;
s->max_pnts = 0;
s->max_workers = 0;
s->tol = NULL;
s->nonovlp_threshold = 0;
s->error_flag = 0;
s->gedp = NULL;
s->dbip = NULL;
s->facetize_tree = NULL;
s->method_opts = NULL;
s->write_profiled = 0;
s->write_profile_bytes = 0.0;
s->write_profile_usec = 0.0;
s->variant_plan = NULL;
return s;
}
static void
facetize_state_destroy(struct _ged_facetize_state *s)
{
if (!s)
return;
if (s->lfile)
fclose(s->lfile);
/* Windows cannot delete the workspace while its log is still open. */
if (s->cleanup_workspace)
bu_dirclear(s->wdir);
if (s->wdir)
bu_free(s->wdir, "wdir");
struct bu_vls *strings[] = {
s->bname, s->log_file, s->failure_msg, s->tolerated_failure_log,
s->region_summary, s->primitive_summary, s->inspection_log, s->wfile,
s->prefix, s->suffix, s->solid_suffix
};
for (struct bu_vls *str : strings) {
if (!str)
continue;
bu_vls_free(str);
BU_PUT(str, struct bu_vls);
}
delete (FacetizeVariantPlan *)s->variant_plan;
BU_PUT(s, struct _ged_facetize_state);
}
FacetizeSession::FacetizeSession(struct ged *gedp)
{
methods = new method_options_t;
session_state = facetize_state_create();
session_state->gedp = gedp;
session_state->dbip = gedp->dbip;
session_state->method_opts = methods;
}
FacetizeSession::~FacetizeSession()
{
facetize_summary(session_state);
facetize_state_destroy(session_state);
delete methods;
}
int
facetize_build_plan(struct _ged_facetize_state *s, int argc,
const char **argv, FacetizePlan &plan)
{
if (!s || !s->dbip || argc <= 0 || !argv)
return BRLCAD_ERROR;
plan.execution = s->execution;
plan.inputs.clear();
plan.output.clear();
std::vector<std::string> missing;
for (int i = 0; i < argc; i++) {
if (db_lookup(s->dbip, argv[i], LOOKUP_QUIET) == RT_DIR_NULL)
missing.emplace_back(argv[i]);
else
plan.inputs.emplace_back(argv[i]);
}
if (plan.execution.writes_in_place()) {
if (!missing.empty()) {
bu_vls_printf(s->gedp->ged_result_str,
"In-place conversion requires every input object to exist:\n");
for (const std::string &name : missing)
bu_vls_printf(s->gedp->ged_result_str, " %s\n", name.c_str());
return BRLCAD_ERROR;
}
} else {
if (missing.size() != 1) {
if (missing.empty())
bu_vls_printf(s->gedp->ged_result_str,
"A new output object name is required.\n");
else
bu_vls_printf(s->gedp->ged_result_str,
"Exactly one new output object name is required; found %zu.\n",
missing.size());
return BRLCAD_ERROR;
}
plan.output = missing.front();
}
if (plan.inputs.empty()) {
bu_vls_printf(s->gedp->ged_result_str,
"No existing input objects were specified.\n");
return BRLCAD_ERROR;
}
return BRLCAD_OK;
}
static std::string
facetize_request_signature(struct _ged_facetize_state *s,
const FacetizePlan &plan, const char *source_path,
const struct stat &source_stat)
{
std::ostringstream signature;
signature << "schema=" << FACETIZE_WORKSPACE_SCHEMA << '\n';
signature << "source=" << source_path << '\n';
signature << "source_size=" << source_stat.st_size << '\n';
signature << "source_mtime=" << source_stat.st_mtime << '\n';
signature << "scope=" << static_cast<int>(plan.execution.scope) << '\n';
signature << "engine=" << static_cast<int>(plan.execution.boolean_engine) << '\n';
signature << "output_format=" << static_cast<int>(plan.execution.output_format) << '\n';
signature << "commit=" << static_cast<int>(plan.execution.commit_mode) << '\n';
signature << "perturb=" << static_cast<int>(plan.execution.perturb_mode) << '\n';
signature << "no_empty=" << s->no_empty << '\n';
signature << "no_fixup=" << s->no_fixup << '\n';
signature << "tolerate_failures=" << s->tolerate_failures << '\n';
signature << "max_time=" << s->max_time << '\n';
signature << "max_pnts=" << s->max_pnts << '\n';
signature << "max_workers=" << s->max_workers << '\n';
signature << "perturb_sa_tol=" << s->perturb_sa_tol << '\n';
signature << "perturb_vol_tol=" << s->perturb_vol_tol << '\n';
signature << "prefix=" << bu_vls_cstr(s->prefix) << '\n';
signature << "suffix=" << bu_vls_cstr(s->suffix) << '\n';
signature << "output=" << plan.output << '\n';
for (const std::string &input : plan.inputs)
signature << "input=" << input << '\n';
method_options_t *methods = (method_options_t *)s->method_opts;
if (methods) {
for (const std::string &method : methods->methods)
signature << "method=" << method << '\n';
for (const auto &method_entry : methods->options_map)
for (const auto &option_entry : method_entry.second)
signature << "method_option=" << method_entry.first << ':'
<< option_entry.first << '=' << option_entry.second << '\n';
}
return signature.str();
}
static bool
read_file(const char *path, std::string &contents)
{
std::ifstream input(path, std::ios::binary);
if (!input)
return false;
std::ostringstream buffer;
buffer << input.rdbuf();
contents = buffer.str();
return input.good() || input.eof();
}
static bool
write_file(const char *path, const std::string &contents)
{
std::ofstream output(path, std::ios::binary | std::ios::trunc);
if (!output)
return false;
output.write(contents.data(), (std::streamsize)contents.size());
return output.good();
}
int
facetize_prepare_workspace(struct _ged_facetize_state *s,
const FacetizePlan &plan)
{
char source_path[MAXPATHLEN];
if (!bu_file_realpath(s->dbip->dbi_filename, source_path)) {
bu_vls_printf(s->gedp->ged_result_str,
"Unable to resolve database path '%s'.\n", s->dbip->dbi_filename);
return BRLCAD_ERROR;
}
struct stat source_stat;
if (stat(source_path, &source_stat) != 0) {
bu_vls_printf(s->gedp->ged_result_str,
"Unable to inspect database '%s'.\n", source_path);
return BRLCAD_ERROR;
}
bu_path_component(s->bname, source_path, BU_PATH_BASENAME);
unsigned long long path_hash = bu_data_hash(source_path, strlen(source_path));
struct bu_vls workspace_name = BU_VLS_INIT_ZERO;
bu_vls_sprintf(&workspace_name, "facetize_%llu", path_hash);
s->wdir = (char *)bu_calloc(MAXPATHLEN, sizeof(char), "facetize workspace");
bu_dir(s->wdir, MAXPATHLEN, BU_DIR_CACHE, bu_vls_cstr(&workspace_name), NULL);
bool workspace_exists = bu_file_directory(s->wdir);
if (!s->resume && workspace_exists)
bu_dirclear(s->wdir);
if (!bu_file_directory(s->wdir))
bu_mkdir(s->wdir);
if (!bu_file_directory(s->wdir)) {
bu_vls_printf(s->gedp->ged_result_str,
"Unable to create facetize workspace '%s'.\n", s->wdir);
bu_vls_free(&workspace_name);
return BRLCAD_ERROR;
}
char manifest_path[MAXPATHLEN];
bu_dir(manifest_path, MAXPATHLEN, s->wdir, FACETIZE_MANIFEST_NAME, NULL);
std::string expected_manifest = facetize_request_signature(s, plan,
source_path, source_stat);
if (s->resume) {
std::string actual_manifest;
if (!read_file(manifest_path, actual_manifest) || actual_manifest != expected_manifest) {
bu_vls_printf(s->gedp->ged_result_str,
"Cannot resume: workspace does not match the database and facetize options.\n");
bu_vls_free(&workspace_name);
return BRLCAD_ERROR;
}
} else if (!write_file(manifest_path, expected_manifest)) {
bu_vls_printf(s->gedp->ged_result_str,
"Unable to write facetize workspace manifest '%s'.\n", manifest_path);
bu_vls_free(&workspace_name);
return BRLCAD_ERROR;
}
if (!bu_vls_strlen(s->log_file)) {
char log_path[MAXPATHLEN];
s->log_file_is_temporary = 1;
bu_vls_sprintf(&workspace_name, "facetize_%s.log", bu_vls_cstr(s->bname));
bu_dir(log_path, MAXPATHLEN, s->wdir, bu_vls_cstr(&workspace_name), NULL);
bu_vls_sprintf(s->log_file, "%s", log_path);
}
bu_vls_free(&workspace_name);
s->lfile = fopen(bu_vls_cstr(s->log_file), "a");
if (!s->lfile) {
bu_vls_printf(s->gedp->ged_result_str,
"Unable to open log file %s for writing\n", bu_vls_cstr(s->log_file));
return BRLCAD_ERROR;
}
return BRLCAD_OK;
}
int
facetize_execute_plan(struct _ged_facetize_state *s,
const FacetizePlan &plan)
{
if (plan.execution.processes_breps())
return _nonovlp_brep_facetize(s, plan);
if (plan.execution.processes_regions())
return _ged_facetize_regions(s, plan);
return _ged_facetize_objs(s, plan);
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
+96
View File
@@ -0,0 +1,96 @@
/* O R C H E S T R A T O R . H
* BRL-CAD
*
* Copyright (c) 2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*/
#ifndef LIBGED_FACETIZE_ORCHESTRATOR_H
#define LIBGED_FACETIZE_ORCHESTRATOR_H
#include <string>
#include <vector>
#include "bu/defines.h"
struct ged;
struct _ged_facetize_state;
class method_options_t;
enum class FacetizeOutputFormat {
Bot,
Nmg
};
enum class FacetizeBooleanEngine {
Manifold,
Nmg
};
enum class FacetizeScope {
Objects,
Regions,
NonOverlappingBrep
};
enum class FacetizeCommitMode {
NewObject,
InPlace
};
enum class FacetizePerturbMode {
Disabled,
Enabled
};
struct FacetizeExecutionOptions {
FacetizeOutputFormat output_format = FacetizeOutputFormat::Bot;
FacetizeBooleanEngine boolean_engine = FacetizeBooleanEngine::Manifold;
FacetizeScope scope = FacetizeScope::Objects;
FacetizeCommitMode commit_mode = FacetizeCommitMode::NewObject;
FacetizePerturbMode perturb_mode = FacetizePerturbMode::Disabled;
bool writes_nmg() const { return output_format == FacetizeOutputFormat::Nmg; }
bool uses_nmg_boolean() const { return boolean_engine == FacetizeBooleanEngine::Nmg; }
bool processes_regions() const { return scope == FacetizeScope::Regions; }
bool processes_breps() const { return scope == FacetizeScope::NonOverlappingBrep; }
bool writes_in_place() const { return commit_mode == FacetizeCommitMode::InPlace; }
bool uses_perturbation() const { return perturb_mode == FacetizePerturbMode::Enabled; }
};
struct FacetizePlan {
FacetizeExecutionOptions execution;
std::vector<std::string> inputs;
std::string output;
std::vector<const char *> input_argv() const;
};
class FacetizeSession {
public:
explicit FacetizeSession(struct ged *gedp);
~FacetizeSession();
FacetizeSession(const FacetizeSession &) = delete;
FacetizeSession &operator=(const FacetizeSession &) = delete;
struct _ged_facetize_state *state() const { return session_state; }
method_options_t *method_options() const { return methods; }
private:
struct _ged_facetize_state *session_state = nullptr;
method_options_t *methods = nullptr;
};
int facetize_build_plan(struct _ged_facetize_state *s, int argc,
const char **argv, FacetizePlan &plan);
int facetize_prepare_workspace(struct _ged_facetize_state *s,
const FacetizePlan &plan);
int facetize_execute_plan(struct _ged_facetize_state *s,
const FacetizePlan &plan);
#endif /* LIBGED_FACETIZE_ORCHESTRATOR_H */
+22 -13
View File
@@ -344,7 +344,10 @@ create_variant_in_working_g(struct db_i *wdbip,
point_t bmin, bmax;
/* If bounds fail, keep -1 and fall back to the non-micro/default floor. */
fastf_t bbox_diag = -1.0;
if (rt_bound_internal(src_dbip, src_dp, bmin, bmax) == 0)
struct bn_tol tol;
BN_TOL_INIT(&tol);
if (src_intern.idb_meth && src_intern.idb_meth->ft_bbox &&
src_intern.idb_meth->ft_bbox(&src_intern, &bmin, &bmax, &tol) == 0)
bbox_diag = DIST_PNT_PNT(bmin, bmax);
fastf_t factor = variant_perturb_factor(src_name, is_sub, idx, bbox_diag);
@@ -395,7 +398,8 @@ create_variant_in_working_g(struct db_i *wdbip,
FacetizeVariantPlan *
_ged_facetize_build_variant_plan(struct _ged_facetize_state *s,
int argc,
struct directory **dpa)
struct directory **dpa,
struct db_i *working_dbip)
{
if (!s || !s->dbip || argc <= 0 || !dpa)
return NULL;
@@ -427,18 +431,22 @@ _ged_facetize_build_variant_plan(struct _ged_facetize_state *s,
* name is not in dbnames, then insert the chosen name into
* dbnames to reserve it for subsequent instances.
* ============================================================ */
struct db_i *wdbip =
db_open(bu_vls_cstr(s->wfile), DB_OPEN_READWRITE);
struct db_i *wdbip = working_dbip;
bool close_wdbip = false;
if (!wdbip) {
delete plan;
return NULL;
wdbip = db_open(bu_vls_cstr(s->wfile), DB_OPEN_READWRITE);
if (!wdbip) {
delete plan;
return NULL;
}
close_wdbip = true;
if (db_dirbuild(wdbip) < 0) {
db_close(wdbip);
delete plan;
return NULL;
}
db_update_nref(wdbip);
}
if (db_dirbuild(wdbip) < 0) {
db_close(wdbip);
delete plan;
return NULL;
}
db_update_nref(wdbip);
/* Pre-collect all names currently in the working .g */
std::set<std::string> dbnames;
@@ -553,7 +561,8 @@ _ged_facetize_build_variant_plan(struct _ged_facetize_state *s,
}
}
db_close(wdbip);
if (close_wdbip)
db_close(wdbip);
return plan;
}
+237
View File
@@ -0,0 +1,237 @@
/* P R O C E S S . C P P
* BRL-CAD
*
* Copyright (c) 2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library 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.
*/
/* Apple's POSIX feature profile hides F_SETNOSIGPIPE. */
#if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE)
# define _DARWIN_C_SOURCE
#endif
#include "common.h"
#include <algorithm>
#include <fstream>
#if defined(__APPLE__)
# include <errno.h>
# include <fcntl.h>
# include <string.h>
#endif
#include "bu/datetime.h"
#include "bu/file.h"
#include "bu/log.h"
#include "bu/process.h"
#include "bu/snooze.h"
#include "./ged_facetize.h"
#include "./process.h"
static const size_t FACETIZE_PROCESS_IO_BUFFER_SIZE = 4096u;
static const size_t FACETIZE_FILE_COPY_BUFFER_SIZE = 1024u * 1024u;
static const int FACETIZE_PROCESS_POLL_USEC = 1000;
static const int FACETIZE_PROCESS_SHUTDOWN_TIMEOUT_SEC = 5;
static const double FACETIZE_USEC_TO_SEC_DIVISOR = 1.0e6;
static const double FACETIZE_WRITE_TIMEOUT_FACTOR = 10.0;
static const double FACETIZE_WRITE_TIMEOUT_MIN_SEC = 5.0;
static const double FACETIZE_WRITE_TIMEOUT_MAX_SEC = 300.0;
const size_t FACETIZE_WRITE_PROFILE_MIN_BYTES = 1024u * 1024u;
void
facetize_process_drain_stdout(struct _ged_facetize_state *state,
struct bu_process *process, FacetizeWorkerClient &channel,
FacetizeWorkerStatus *status)
{
char buffer[FACETIZE_PROCESS_IO_BUFFER_SIZE];
int fd = bu_process_fileno(process, BU_PROCESS_STDOUT);
FacetizeWorkerStatus ignored_status;
FacetizeWorkerStatus *output_status = status ? status : &ignored_status;
std::vector<std::string> diagnostics;
while (fd >= 0 && bu_process_pending(fd)) {
int count = bu_process_read_n(process, BU_PROCESS_STDOUT,
(int)sizeof(buffer), buffer);
if (count <= 0)
break;
channel.consume_output(buffer, (size_t)count, *output_status,
diagnostics);
}
for (const std::string &diagnostic : diagnostics)
facetize_log(state, 1, "%s\n", diagnostic.c_str());
}
void
facetize_process_drain_stderr(struct _ged_facetize_state *state,
struct bu_process *process)
{
char buffer[FACETIZE_PROCESS_IO_BUFFER_SIZE];
int fd = bu_process_fileno(process, BU_PROCESS_STDERR);
while (fd >= 0 && bu_process_pending(fd)) {
int count = bu_process_read_n(process, BU_PROCESS_STDERR,
(int)sizeof(buffer), buffer);
if (count <= 0)
break;
facetize_log(state, 1, "%.*s", count, buffer);
}
}
int
facetize_process_reap(struct _ged_facetize_state *state,
struct bu_process **process, FacetizeWorkerClient &channel,
bool terminate)
{
if (!process || !*process)
return BRLCAD_ERROR;
if (terminate)
(void)bu_process_terminate(*process);
int64_t deadline = bu_gettime() +
BU_SEC2USEC(FACETIZE_PROCESS_SHUTDOWN_TIMEOUT_SEC);
int poll_result = bu_process_poll(*process, NULL);
while (poll_result == 0 && bu_gettime() < deadline) {
facetize_process_drain_stdout(state, *process, channel, NULL);
facetize_process_drain_stderr(state, *process);
(void)bu_snooze(FACETIZE_PROCESS_POLL_USEC);
poll_result = bu_process_poll(*process, NULL);
}
facetize_process_drain_stdout(state, *process, channel, NULL);
facetize_process_drain_stderr(state, *process);
if (poll_result != 1)
(void)bu_process_terminate(*process);
return bu_process_wait_n(process, 0);
}
int
facetize_process_stop(struct _ged_facetize_state *state,
struct bu_process **process, FILE *&process_input,
FacetizeWorkerClient &channel, bool terminate)
{
int status = facetize_process_reap(state, process, channel, terminate);
process_input = NULL;
channel.reset(NULL);
return status;
}
int
facetize_process_start(struct bu_process **process, FILE **process_input,
FacetizeWorkerClient &channel,
const std::vector<std::string> &command,
const std::string &result_file, const char *mode)
{
if (!process || !process_input || !mode)
return BRLCAD_ERROR;
std::vector<const char *> process_command;
for (const std::string &argument : command)
process_command.push_back(argument.c_str());
if (!result_file.empty()) {
process_command.push_back("--result-file");
process_command.push_back(result_file.c_str());
}
process_command.push_back(mode);
process_command.push_back(NULL);
*process = NULL;
*process_input = NULL;
channel.reset(NULL);
bu_process_create(process, process_command.data(), BU_PROCESS_HIDE_WINDOW);
if (*process)
*process_input = bu_process_file_open(*process, BU_PROCESS_STDIN);
bool input_ready = *process && *process_input;
#if defined(__APPLE__)
if (input_ready && fcntl(fileno(*process_input), F_SETNOSIGPIPE, 1) < 0) {
/* Darwin sends a broken pipe's SIGPIPE to the process, so masking
* only the writing thread cannot protect this worker channel. */
bu_log("FACETIZE: unable to suppress SIGPIPE on worker stdin: %s\n",
strerror(errno));
input_ready = false;
}
#endif
if (input_ready && setvbuf(*process_input, NULL, _IONBF, 0) == 0) {
channel.reset(*process_input);
return BRLCAD_OK;
}
if (*process) {
(void)bu_process_terminate(*process);
(void)bu_process_wait_n(process, 0);
}
*process_input = NULL;
return BRLCAD_ERROR;
}
double
facetize_write_timeout_seconds(size_t payload_size,
double profiled_write_bytes, double profiled_write_usec)
{
if (profiled_write_bytes <= 0.0 || profiled_write_usec <= 0.0)
return FACETIZE_WRITE_TIMEOUT_MAX_SEC;
double bytes_per_second = profiled_write_bytes *
FACETIZE_USEC_TO_SEC_DIVISOR / profiled_write_usec;
double projected_seconds = (double)payload_size / bytes_per_second;
double timeout_seconds = projected_seconds * FACETIZE_WRITE_TIMEOUT_FACTOR;
return std::min(FACETIZE_WRITE_TIMEOUT_MAX_SEC,
std::max(FACETIZE_WRITE_TIMEOUT_MIN_SEC, timeout_seconds));
}
int
facetize_file_copy(const char *source, const char *destination,
FacetizeFileCopyProgress progress, void *progress_data)
{
if (!source || !destination)
return BRLCAD_ERROR;
std::ifstream input(source, std::ios::binary);
if (!input.is_open())
return BRLCAD_ERROR;
std::ofstream output(destination, std::ios::binary | std::ios::trunc);
if (!output.is_open())
return BRLCAD_ERROR;
std::vector<char> buffer(FACETIZE_FILE_COPY_BUFFER_SIZE);
uint64_t bytes_copied = 0;
bool copy_succeeded = true;
while (input) {
input.read(buffer.data(), (std::streamsize)buffer.size());
std::streamsize count = input.gcount();
if (count <= 0)
break;
output.write(buffer.data(), count);
if (!output.good()) {
copy_succeeded = false;
break;
}
bytes_copied += (uint64_t)count;
if (progress)
progress(bytes_copied, progress_data);
}
copy_succeeded = copy_succeeded && input.eof() && !input.bad();
if (copy_succeeded) {
output.flush();
copy_succeeded = output.good();
}
input.close();
output.close();
if (!copy_succeeded)
bu_file_delete(destination);
return copy_succeeded ? BRLCAD_OK : BRLCAD_ERROR;
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
+64
View File
@@ -0,0 +1,64 @@
/* P R O C E S S . H
* BRL-CAD
*
* Copyright (c) 2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*/
#ifndef LIBGED_FACETIZE_PROCESS_H
#define LIBGED_FACETIZE_PROCESS_H
#include <cstdio>
#include <cstdint>
#include <string>
#include <vector>
#include "bu/defines.h"
#include "./worker.h"
struct bu_process;
struct _ged_facetize_state;
extern const size_t FACETIZE_WRITE_PROFILE_MIN_BYTES;
typedef void (*FacetizeFileCopyProgress)(uint64_t bytes_copied, void *data);
void
facetize_process_drain_stdout(struct _ged_facetize_state *state,
struct bu_process *process, FacetizeWorkerClient &channel,
FacetizeWorkerStatus *status);
void
facetize_process_drain_stderr(struct _ged_facetize_state *state,
struct bu_process *process);
int
facetize_process_start(struct bu_process **process, FILE **process_input,
FacetizeWorkerClient &channel,
const std::vector<std::string> &command,
const std::string &result_file, const char *mode);
int
facetize_process_reap(struct _ged_facetize_state *state,
struct bu_process **process, FacetizeWorkerClient &channel,
bool terminate);
int
facetize_process_stop(struct _ged_facetize_state *state,
struct bu_process **process, FILE *&process_input,
FacetizeWorkerClient &channel, bool terminate);
double
facetize_write_timeout_seconds(size_t payload_size,
double profiled_write_bytes, double profiled_write_usec);
int
facetize_file_copy(const char *source, const char *destination,
FacetizeFileCopyProgress progress = NULL, void *progress_data = NULL);
#endif /* LIBGED_FACETIZE_PROCESS_H */
File diff suppressed because it is too large Load Diff
@@ -4,12 +4,18 @@ set(TESS_LIBS libged manifold::manifold)
set(
GED_TESS_SRCS
brep_csg.cpp
continuation.cpp
sample.cpp
spsr.cpp
main.cpp
mdc.cpp
nmg.cpp
nmg_boolean.cpp
util.cpp
../plan.cpp
../process.cpp
../tri.cpp
../transfer.cpp
../util.cpp
../validation.cpp
../worker.cpp
)
@@ -20,6 +26,7 @@ ged_subprocess_library(facetize_process
cmakefiles(
CMakeLists.txt
nmg_boolean.h
tessellate.h
${GED_TESS_SRCS}
)
@@ -1,293 +0,0 @@
/* C O N T I N U A T I O N . C P P
* BRL-CAD
*
* Copyright (c) 2008-2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library 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 this file; see the file named COPYING for more
* information.
*/
/** @file libged/facetize/continuation.cpp
*
* The facetize command's Continuation Method implementation.
*/
#include "common.h"
#include <sstream>
#include <string>
#include <vector>
#include "vmath.h"
#include "bu/datetime.h"
#include "bg/trimesh.h"
#include "raytrace.h"
#include "analyze/polygonize.h"
#include "../../ged_private.h"
#include "./tessellate.h"
#define FACETIZE_MEMORY_THRESHOLD 150000000
static void
_pnts_bbox(point_t rpp_min, point_t rpp_max, int pnt_cnt, point_t *pnts)
{
int i = 0;
if (!rpp_min || !rpp_max || !pnts || !pnts || !pnt_cnt) return;
VSETALL(rpp_min, INFINITY);
VSETALL(rpp_max, -INFINITY);
for (i = 0; i < pnt_cnt; i++) {
VMINMAX(rpp_min, rpp_max, pnts[i]);
}
}
static double
_bbox_vol(point_t b_min, point_t b_max)
{
double bbox_vol = 0.0;
fastf_t b_xlen, b_ylen, b_zlen;
b_xlen = fabs(b_max[X] - b_min[X]);
b_ylen = fabs(b_max[Y] - b_min[Y]);
b_zlen = fabs(b_max[Z] - b_min[Z]);
bbox_vol = b_xlen * b_ylen * b_zlen;
return bbox_vol;
}
void free_bot_internal(struct rt_bot_internal *bot)
{
if (!bot)
return;
if (bot->faces)
bu_free(bot->faces, "faces");
if (bot->vertices)
bu_free(bot->vertices, "vertices");
BU_PUT(bot, struct rt_bot_internal);
}
int
bot_gen(struct rt_bot_internal **obot, fastf_t feature_size, point_t seed, const char *objname, struct db_i *dbip, struct analyze_polygonize_params *params)
{
/* Build the BoT */
struct rt_bot_internal *bot;
BU_GET(bot, struct rt_bot_internal);
bot->magic = RT_BOT_INTERNAL_MAGIC;
bot->mode = RT_BOT_SOLID;
bot->orientation = RT_BOT_UNORIENTED;
bot->thickness = (fastf_t *)NULL;
bot->face_mode = (struct bu_bitv *)NULL;
bot->faces = NULL;
bot->vertices = NULL;
int ret = analyze_polygonize(&(bot->faces), (int *)&(bot->num_faces),
(point_t **)&(bot->vertices),
(int *)&(bot->num_vertices),
feature_size, seed, objname, dbip, params);
if (ret == 3)
bu_log("CM: Too little available memory to continue, aborting\n");
if (ret == 2)
bu_log("CM: timed out after %d seconds with size %g\n", params->max_cycle_time, feature_size);
if (!ret) {
*obot = bot;
} else {
free_bot_internal(bot);
}
return ret;
}
int
continuation_mesh(struct rt_bot_internal **obot, struct db_i *dbip, const char *objname, tess_opts *s, point_t seed)
{
int first_run = 1;
int fatal_error_cnt = 0;
double successful_feature_size = 0.0;
unsigned long int successful_bot_count = 1000;
int decimation_succeeded = 0;
struct rt_bot_internal *bot = NULL;
struct rt_bot_internal *dbot = NULL;
int pret = 0;
int total_elapsed = 0;
struct analyze_polygonize_params params = ANALYZE_POLYGONIZE_PARAMS_DEFAULT;
double feature_size = (s->cm_options.feature_size > 0) ? s->cm_options.feature_size : 2*s->cm_options.avg_thickness;
/* Run the polygonize routine. Because it is quite simple to
* accidentally specify inputs that will take huge amounts of time
* to run, we will attempt a series of progressively courser
* polygonize runs until we either succeed, or reach a feature
* size that is greater than 2x the average thickness according to
* the raytracer without succeeding. If max_time has been
* explicitly set to 0 by the caller this will run unbounded, but
* the algorithm is n**2 and we're trying the finest level first
* so may run a *very* long time... */
params.max_time = s->cm_options.max_time;
params.max_cycle_time = s->cm_options.max_cycle_time;
params.verbosity = 1;
params.minimum_free_mem = FACETIZE_MEMORY_THRESHOLD;
while (!pret && (feature_size > 0.9*s->cm_options.target_feature_size) && fatal_error_cnt < 8 ) {
struct rt_bot_internal *candidate = NULL;
double timestamp = bu_gettime();
params.time_offset = total_elapsed + 10; // Allow a few seconds extra for decimation
pret = bot_gen(&candidate, feature_size, seed, objname, dbip, &params);
fastf_t delta = (int)((bu_gettime() - timestamp)/1e6);
if (pret || candidate->num_faces < successful_bot_count || delta < 2) {
if (pret == 3)
break;
if (pret == 2) {
/* If we still haven't had a successful run, back the feature size out and try again */
if (first_run) {
pret = 0;
feature_size = feature_size * 5;
fatal_error_cnt++;
continue;
}
}
if (pret != 2 && !(s->cm_options.feature_size > 0)) {
/* Something about the previous size didn't work - nudge the feature size and try again
* unless we've had multiple fatal errors. */
pret = 0;
bu_log("CM: error at size %g\n", feature_size);
/* If we've had a successful first run, just nudge the feature
* size down and retry. If we haven't succeeded yet, and we've
* got just this one error, try dropping the feature size down
* by an order of magnitude. If we haven't succeed yet *and*
* we've got multiple fatal errors, try dropping it by half. */
feature_size = feature_size * ((!first_run) ? 0.95 : ((fatal_error_cnt) ? 0.5 : 0.1));
bu_log("CM: retrying with size %g\n", feature_size);
fatal_error_cnt++;
continue;
}
feature_size = successful_feature_size;
if (bot && bot->faces) {
if (s->cm_options.feature_size <= 0) {
bu_log("CM: unable to polygonize at target size (%g), using last successful BoT with %d faces, feature size %g\n", s->cm_options.target_feature_size, (int)bot->num_faces, successful_feature_size);
} else {
bu_log("CM: successfully created %d faces, feature size %g\n", (int)bot->num_faces, successful_feature_size);
}
}
} else {
/* if we have had a fatal error in the past, reset on subsequent success */
fatal_error_cnt = 0;
successful_feature_size = feature_size;
bu_log("CM: completed in %g seconds with size %g\n", delta, feature_size);
feature_size = feature_size * ((delta < 5) ? 0.7 : 0.9);
successful_bot_count = candidate->num_faces;
if (bot)
free_bot_internal(bot);
bot = candidate;
}
// If we got this far, we've had a successful first run
first_run = 0;
// If we're about to run up against our max time limit, bail rather than keep trying
total_elapsed += delta;
if (s->cm_options.max_cycle_time < delta*2) {
if (total_elapsed + s->cm_options.max_cycle_time > s->cm_options.max_time) {
feature_size = successful_feature_size;
break;
}
} else {
if (total_elapsed + delta*2 > s->cm_options.max_time) {
feature_size = successful_feature_size;
break;
}
}
}
if (bot && bot->num_faces) {
bu_log("CM: successfully polygonized BoT with %d faces at feature size %g\n", (int)bot->num_faces, successful_feature_size);
}
if (!bot || !bot->faces) {
bu_log("CM: surface reconstruction failed: %s\n", objname);
if (bot && bot->vertices) bu_free(bot->vertices, "verts");
if (bot && bot->faces) bu_free(bot->faces, "verts");
if (bot)
BU_PUT(bot, struct rt_bot_internal *);
return BRLCAD_ERROR;
}
/* do decimation */
{
double d_feature_size = (s->cm_options.d_feature_size > 0) ? s->cm_options.d_feature_size : 1.5 * feature_size;
*obot = bot;
bu_log("CM: decimating with feature size %g\n", d_feature_size);
dbot = _tess_facetize_decimate(bot, d_feature_size);
if (bot == dbot || !dbot->num_vertices || !dbot->num_faces) {
bu_log("decimation failed\n");
return BRLCAD_ERROR;
}
bot = dbot;
decimation_succeeded = 1;
}
/* Get the volume of the bounding box of the decimated BoT */
point_t b_min, b_max;
VSETALL(b_min, INFINITY);
VSETALL(b_max, -INFINITY);
_pnts_bbox(b_min, b_max, bot->num_vertices, (point_t *)bot->vertices);
double bot_bbox_vol = _bbox_vol(b_min, b_max);
/* Check the BoT bbox vol against the bounding box
* of the point cloud - a large difference means something probably isn't
* right. For the moment, use >50% difference. */
if (fabs(s->cm_options.pnts_bbox_vol - bot_bbox_vol) > s->cm_options.pnts_bbox_vol * 0.5) {
if (bot->vertices) bu_free(bot->vertices, "verts");
if (bot->faces) bu_free(bot->faces, "verts");
BU_PUT(bot, struct rt_bot_internal);
return BRLCAD_ERROR;
}
/* Check validity - do not return an invalid BoT */
{
int not_solid = bg_trimesh_solid2(bot->num_vertices, bot->num_faces, (fastf_t *)bot->vertices, (int *)bot->faces, NULL);
if (not_solid) {
if (bot->vertices) bu_free(bot->vertices, "verts");
if (bot->faces) bu_free(bot->faces, "verts");
BU_PUT(bot, struct rt_bot_internal);
bu_log("CM: facetization failed, final BoT was not solid\n");
return BRLCAD_ERROR;
}
}
if (decimation_succeeded) {
bu_log("CM: decimation succeeded, final BoT has %d faces\n", (int)bot->num_faces);
}
*obot = bot;
return BRLCAD_OK;
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
+537 -102
View File
@@ -34,17 +34,67 @@
#include <string>
#include <vector>
#include <stdlib.h>
#include "bu/app.h"
#include "bu/env.h"
#include "bu/file.h"
#include "bu/opt.h"
#include "bg/trimesh.h"
#include "rt/primitives/bot.h"
#include "ged.h"
#define TESS_OPTS_IMPLEMENTATION
#include "../ged_facetize.h"
#include "../tess_opts.h"
#include "../transfer.h"
#include "../validation.h"
#include "../worker.h"
#include "./nmg_boolean.h"
#include "./tessellate.h"
static const char FACETIZE_TEST_FAULT_ENV[] =
"LIBGED_FACETIZE_TEST_FAULT";
static const char FACETIZE_TEST_FAULT_FILE_ENV[] =
"LIBGED_FACETIZE_TEST_FAULT_FILE";
static const char FACETIZE_TEST_FAULT_TESS_READY[] = "tess-before-ready";
static const char FACETIZE_TEST_FAULT_STAGE_DONE[] = "stage-before-done";
static const char FACETIZE_TEST_FAULT_WRITER_PROCEED[] =
"writer-before-proceed";
static const char FACETIZE_TEST_FAULT_WRITER_DONE[] = "writer-before-done";
static const char FACETIZE_TEST_FAULT_NMG_READY[] = "nmg-before-ready";
/**
* Terminate at a named protocol boundary when explicitly armed by a test.
* Requiring both an exact stage/object selector and a writable one-shot claim
* file keeps this inaccessible during normal operation and prevents restarted
* workers from repeatedly taking the same fault.
*/
static void
facetize_test_fault(const char *stage, const char *object_name)
{
const char *fault = getenv(FACETIZE_TEST_FAULT_ENV);
const char *claim_file = getenv(FACETIZE_TEST_FAULT_FILE_ENV);
if (!fault || !fault[0] || !claim_file || !claim_file[0] ||
!stage || !object_name)
return;
std::string expected = std::string(stage) + ":" + object_name;
if (expected != fault || bu_file_exists(claim_file, NULL))
return;
FILE *claim = fopen(claim_file, "wb");
if (!claim)
return;
bool written = fwrite(expected.data(), 1, expected.size(), claim) ==
expected.size();
bool closed = fclose(claim) == 0;
if (!written || !closed)
return;
bu_exit(BRLCAD_ERROR, "FACETIZE: injected test fault at %s for %s\n",
stage, object_name);
}
static void
facetize_payload_add(size_t *payload_size, size_t count, size_t item_size)
{
@@ -96,19 +146,11 @@ facetize_bot_payload_size(const struct rt_bot_internal *bot)
return payload_size;
}
static void
rt_pnts_free(struct rt_pnts_internal *pnts)
static size_t
facetize_resident_size()
{
struct pnt_normal *rpnt = (struct pnt_normal *)pnts->point;
if (rpnt) {
struct pnt_normal *entry;
while (BU_LIST_WHILE(entry, pnt_normal, &(rpnt->l))) {
BU_LIST_DEQUEUE(&(entry->l));
BU_PUT(entry, struct pnt_normal);
}
BU_PUT(rpnt, struct pnt_normal);
}
BU_PUT(pnts, struct rt_pnts_internal);
ssize_t resident_size = bu_mem(BU_MEM_PROCESS_RESIDENT, NULL);
return (resident_size > 0) ? (size_t)resident_size : 0;
}
static void
@@ -118,28 +160,14 @@ method_setup(tess_opts *s)
return;
std::vector<std::string> *methods = &s->method_opts.methods;
if (!methods->size()) {
methods->push_back(std::string("NMG"));
methods->push_back(std::string("CM"));
methods->push_back(std::string("SPSR"));
}
if (!methods->size())
*methods = tess_default_methods();
// Now that we've set any default overrides for multiple types, get the
// method specific options for each method set up
s->nmg_options.sync(s->method_opts);
s->cm_options.sync(s->method_opts);
s->mdc_options.sync(s->method_opts);
s->spsr_options.sync(s->method_opts);
// Set the sampling options. If CM is active we will be using its settings
// to sample first, so default to those values.
bool sample_sync = false;
if (std::find(methods->begin(), methods->end(), std::string("CM")) != methods->end()) {
s->pnt_options.sync(s->cm_options);
sample_sync = true;
}
if (!sample_sync && std::find(methods->begin(), methods->end(), std::string("SPSR")) != methods->end()) {
s->pnt_options.sync(s->spsr_options);
}
}
static int
@@ -163,8 +191,8 @@ dp_tessellate(struct rt_bot_internal **obot, struct bu_vls *method_flag, struct
}
struct rt_pnts_internal *pnts = NULL;
bool free_pnts = false;
struct rt_bot_internal *bot = NULL;
bool best_effort_source = false;
int propVal;
int ret = BRLCAD_OK;
@@ -199,7 +227,7 @@ dp_tessellate(struct rt_bot_internal **obot, struct bu_vls *method_flag, struct
// If we are going to try a pnts wrapping, there are only a few
// candidates in the fallback methods list that we can use.
mset.erase(std::string("NMG"));
mset.erase(std::string("CM"));
mset.erase(std::string("MDC"));
// point the pnts arguments to the internal point data
pnts = (struct rt_pnts_internal *)intern.idb_ptr;
@@ -227,6 +255,7 @@ dp_tessellate(struct rt_bot_internal **obot, struct bu_vls *method_flag, struct
// Volumetric bot - if it can be manifold we're good, but if
// not we need to try and repair it.
if (!bot_is_manifold(bot)) {
best_effort_source = true;
// Nope - try repairing
struct rt_bot_repair_info settings = RT_BOT_REPAIR_INFO_INIT;
// We're aggressive preparing facetize inputs, since non-lint-passing
@@ -234,6 +263,8 @@ dp_tessellate(struct rt_bot_internal **obot, struct bu_vls *method_flag, struct
settings.strict = 0;
bu_vls_sprintf(method_flag, "REPAIR");
ret = rt_bot_repair(obot, bot, &settings);
if (ret == BRLCAD_OK && settings.used_openvdb)
bu_vls_sprintf(method_flag, "REPAIR_OPENVDB");
} else {
// Already a valid BoT - tessellate is a no-op.
*obot = NULL;
@@ -273,53 +304,22 @@ dp_tessellate(struct rt_bot_internal **obot, struct bu_vls *method_flag, struct
}
}
if (mset.find(std::string("CM")) != mset.end()) {
// The continuation method (CM) is a marching algorithm using an
// inside/outside test, building from a seed point on the surface.
//
// CM needs some awareness of properties of the solid, so we use the
// raytrace interrogation to build up that data. Unlike the sampling
// methods we don't make direct use of the points beyond using one of
// them for the seed, but we do use information collected during the
// sampling process.
if (!pnts) {
pnts = _tess_pnts_sample(dp->d_namep, dbip, s);
free_pnts = (pnts != NULL);
}
if (pnts) {
s->cm_options.sync(s->pnt_options);
struct pnt_normal *seed = BU_LIST_PNEXT(pnt_normal, (struct pnt_normal *)pnts->point);
ret = continuation_mesh(obot, dbip, dp->d_namep, s, seed->v);
if (ret == BRLCAD_OK) {
bu_vls_sprintf(method_flag, "CM");
goto dp_tessellate_cleanup;
}
if (mset.find(std::string("MDC")) != mset.end()) {
ret = mdc_mesh(obot, dbip, dp->d_namep, s);
if (ret == BRLCAD_OK) {
bu_vls_sprintf(method_flag, "MDC");
goto dp_tessellate_cleanup;
}
}
pnt_sampling_methods:
if (mset.find(std::string("SPSR")) != mset.end()) {
if (!pnts) {
pnts = _tess_pnts_sample(dp->d_namep, dbip, s);
free_pnts = (pnts != NULL);
} else {
if (!s->spsr_options.equals(s->pnt_options)) {
s->pnt_options.sync(s->spsr_options);
if (free_pnts)
rt_pnts_free(pnts);
pnts = _tess_pnts_sample(dp->d_namep, dbip, s);
free_pnts = (pnts != NULL);
}
}
if (pnts) {
s->spsr_options.sync(s->pnt_options);
ret = spsr_mesh(obot, dbip, pnts, s);
if (ret == BRLCAD_OK) {
bu_vls_sprintf(method_flag, "SPSR");
goto dp_tessellate_cleanup;
}
ret = spsr_mesh(obot, dbip, dp->d_namep, pnts,
best_effort_source, s);
if (ret == BRLCAD_OK) {
bu_vls_sprintf(method_flag, "SPSR");
goto dp_tessellate_cleanup;
}
}
@@ -341,8 +341,6 @@ pnt_sampling_methods:
ret = BRLCAD_ERROR;
dp_tessellate_cleanup:
if (free_pnts && pnts)
rt_pnts_free(pnts);
if (ret != BRLCAD_OK && *obot) {
_tess_facetize_free_bot(*obot);
*obot = NULL;
@@ -355,13 +353,13 @@ void
print_methods_info()
{
nmg_opts nopts;
cm_opts cmopts;
mdc_opts mdcopts;
spsr_opts spsropts;
std::string info;
info.append(nopts.print_options_help());
info.append(std::string("\n"));
info.append(cmopts.print_options_help());
info.append(mdcopts.print_options_help());
info.append(std::string("\n"));
info.append(spsropts.print_options_help());
fprintf(stdout, "%s\n", info.c_str());
@@ -370,36 +368,70 @@ print_methods_info()
void
print_tess_methods()
{
fprintf(stdout, "NMG CM SPSR");
fprintf(stdout, "NMG MDC SPSR\n");
}
static int
facetize_server_request(struct ged *gedp, const char *object_name,
tess_opts *s, FacetizeWorkerServer &worker_channel, bool *result_sent)
facetize_server_request(struct ged *gedp, struct db_i *result_dbip,
const FacetizeWorkerRequest &request,
FacetizeWorkerServer &worker_channel, bool *result_sent)
{
if (!gedp || !object_name || !s || !result_sent)
if (!gedp || !result_sent ||
request.operation != FacetizeWorkerOperation::TessellatePrimitive ||
request.input_names.size() != 1)
return BRLCAD_ERROR;
*result_sent = false;
if (!request.primitive.cache_directory.empty()) {
bu_mkdir(request.primitive.cache_directory.c_str());
if (bu_setenv("BU_DIR_CACHE",
request.primitive.cache_directory.c_str(), 1) != 0)
return BRLCAD_ERROR;
}
tess_opts options;
options.method_opts.methods = request.primitive.methods;
for (const std::string &option_string :
request.primitive.method_options) {
const char *option = option_string.c_str();
if (_tess_method_opts(NULL, 1, &option, &options.method_opts) != 1)
return BRLCAD_ERROR;
}
method_setup(&options);
if (request.primitive.point_limit > 0) {
options.spsr_options.max_pnts = request.primitive.point_limit;
}
const char *object_name = request.input_names.front().c_str();
struct directory *dp = db_lookup(gedp->dbip, object_name, LOOKUP_QUIET);
if (!dp || dp->d_major_type != DB5_MAJORTYPE_BRLCAD)
return BRLCAD_ERROR;
struct rt_bot_internal *obot = NULL;
struct bu_vls method = BU_VLS_INIT_ZERO;
int ret = dp_tessellate(&obot, &method, gedp, dp, s);
int ret = dp_tessellate(&obot, &method, gedp, dp, &options);
if (ret == BRLCAD_OK && obot) {
// Waiting here lets the parent stop an over-time tessellation without
// risking a partially replaced object in the working database.
facetize_test_fault(FACETIZE_TEST_FAULT_TESS_READY, object_name);
size_t payload_size = facetize_bot_payload_size(obot);
if (!worker_channel.send_write_ready(payload_size) ||
!worker_channel.receive_write_proceed()) {
if (!worker_channel.send_write_ready(payload_size,
facetize_resident_size()) ||
!worker_channel.receive_write_proceed() ||
!worker_channel.send_write_started()) {
_tess_facetize_free_bot(obot);
ret = BRLCAD_ERROR;
} else {
ret = _tess_facetize_write_bot(gedp->dbip, obot, object_name,
struct db_i *output_dbip = result_dbip ? result_dbip : gedp->dbip;
const char *output_name = result_dbip ?
FACETIZE_WORKER_RESULT_OBJECT : object_name;
ret = _tess_facetize_write_bot(output_dbip, obot, output_name,
bu_vls_cstr(&method));
if (!worker_channel.send_write_result(ret)) {
if (result_dbip && ret == BRLCAD_OK)
facetize_test_fault(FACETIZE_TEST_FAULT_STAGE_DONE,
object_name);
if (!worker_channel.send_write_result(ret,
facetize_resident_size())) {
ret = BRLCAD_ERROR;
} else {
*result_sent = true;
@@ -413,7 +445,7 @@ facetize_server_request(struct ged *gedp, const char *object_name,
}
static int
facetize_server(const char *work_file, tess_opts *s)
facetize_server(const char *work_file, const char *result_file)
{
int server_status = BRLCAD_OK;
setvbuf(stdout, NULL, _IONBF, 0);
@@ -422,11 +454,18 @@ facetize_server(const char *work_file, tess_opts *s)
if (!gedp)
return BRLCAD_ERROR;
struct db_i *result_dbip = result_file ?
db_create(result_file, BRLCAD_DB_FORMAT_LATEST) : NULL;
if (result_file && !result_dbip) {
ged_close(gedp);
return BRLCAD_ERROR;
}
FacetizeWorkerServer worker_channel(stdin, stdout);
while (true) {
std::string object_name;
FacetizeWorkerRequest request;
FacetizeWorkerReadResult read_result =
worker_channel.receive_request(object_name);
worker_channel.receive_request(request);
if (read_result == FacetizeWorkerReadResult::End)
break;
if (read_result == FacetizeWorkerReadResult::Error) {
@@ -435,14 +474,335 @@ facetize_server(const char *work_file, tess_opts *s)
}
bool result_sent = false;
int ret = facetize_server_request(gedp, object_name.c_str(), s,
worker_channel, &result_sent);
if (!result_sent && !worker_channel.send_tessellation_result(ret)) {
int ret = facetize_server_request(gedp, result_dbip,
request, worker_channel, &result_sent);
if (!result_sent && !worker_channel.send_tessellation_result(ret,
facetize_resident_size())) {
server_status = BRLCAD_ERROR;
break;
}
}
if (result_dbip)
db_close(result_dbip);
ged_close(gedp);
return server_status;
}
static int
facetize_validation_server(const char *source_file)
{
if (!source_file)
return BRLCAD_ERROR;
setvbuf(stdout, NULL, _IONBF, 0);
struct db_i *dbip = db_open(source_file, DB_OPEN_READONLY);
if (!dbip)
return BRLCAD_ERROR;
if (db_dirbuild(dbip) < 0) {
db_close(dbip);
return BRLCAD_ERROR;
}
int server_status = BRLCAD_OK;
FacetizeWorkerServer channel(stdin, stdout);
while (true) {
FacetizeWorkerRequest request;
FacetizeWorkerReadResult read_result =
channel.receive_request(request);
if (read_result == FacetizeWorkerReadResult::End)
break;
if (read_result == FacetizeWorkerReadResult::Error ||
request.operation != FacetizeWorkerOperation::ValidateCsg ||
request.input_names.size() != 1) {
server_status = BRLCAD_ERROR;
break;
}
const std::string &object_name = request.input_names.front();
double surface_area = -1.0;
double volume = -1.0;
long crossings = facetize_csg_metrics(dbip, object_name.c_str(),
&surface_area, &volume);
int result = (crossings >= 0) ? BRLCAD_OK : BRLCAD_ERROR;
if (!channel.send_csg_result(result, crossings, surface_area, volume,
facetize_resident_size())) {
server_status = BRLCAD_ERROR;
break;
}
}
db_close(dbip);
return server_status;
}
static int
facetize_region_server_request(struct _ged_facetize_state *state,
struct db_i *work_dbip, struct rt_wdb *work_wdbp,
struct db_i *staging_dbip, struct rt_wdb *staging_wdbp,
const char *object_name, FacetizeWorkerServer &channel,
bool *result_sent)
{
if (!state || !work_dbip || !work_wdbp || !staging_dbip ||
!staging_wdbp || !object_name || !result_sent)
return BRLCAD_ERROR;
*result_sent = false;
struct db_i *result_dbip = db_create_inmem();
if (!result_dbip)
return BRLCAD_ERROR;
const char *inputs[] = {object_name};
int ret = _ged_facetize_booleval_tri_to_db(state, work_dbip,
work_wdbp, 1, inputs, FACETIZE_WORKER_RESULT_OBJECT, &rt_vlfree,
result_dbip, 0, 0);
struct rt_db_internal result_internal;
RT_DB_INTERNAL_INIT(&result_internal);
bool result_internal_consumed = false;
struct directory *result_dp = (ret == BRLCAD_OK) ?
db_lookup(result_dbip, FACETIZE_WORKER_RESULT_OBJECT, LOOKUP_QUIET) :
RT_DIR_NULL;
if (!result_dp || result_dp->d_minor_type != ID_BOT ||
rt_db_get_internal(&result_internal, result_dp, result_dbip,
NULL) < 0) {
ret = BRLCAD_ERROR;
}
if (ret == BRLCAD_OK) {
struct rt_bot_internal *result_bot =
(struct rt_bot_internal *)result_internal.idb_ptr;
size_t payload_size = facetize_bot_payload_size(result_bot);
if (!channel.send_region_write_ready(payload_size,
facetize_resident_size(), state->tolerated_failures) ||
!channel.receive_write_proceed() ||
!channel.send_write_started()) {
ret = BRLCAD_ERROR;
} else {
struct directory *old_dp = db_lookup(staging_dbip,
FACETIZE_WORKER_RESULT_OBJECT, LOOKUP_QUIET);
if (old_dp && (db_delete(staging_dbip, old_dp) != 0 ||
db_dirdelete(staging_dbip, old_dp) != 0)) {
ret = BRLCAD_ERROR;
} else {
ret = wdb_put_internal(staging_wdbp,
FACETIZE_WORKER_RESULT_OBJECT, &result_internal,
1.0);
result_internal_consumed = true;
}
if (!channel.send_write_result(ret, facetize_resident_size()))
ret = BRLCAD_ERROR;
else
*result_sent = true;
}
}
if (!result_internal_consumed && result_internal.idb_ptr)
rt_db_free_internal(&result_internal);
db_close(result_dbip);
return ret;
}
static int
facetize_region_server(const char *work_file, const char *source_file,
const char *result_file)
{
if (!work_file || !source_file || !result_file)
return BRLCAD_ERROR;
setvbuf(stdout, NULL, _IONBF, 0);
struct db_i *work_dbip = db_open(work_file, DB_OPEN_READONLY);
struct db_i *source_dbip = db_open(source_file, DB_OPEN_READONLY);
if (!work_dbip || !source_dbip) {
if (work_dbip)
db_close(work_dbip);
if (source_dbip)
db_close(source_dbip);
return BRLCAD_ERROR;
}
if (db_dirbuild(work_dbip) < 0 || db_dirbuild(source_dbip) < 0) {
db_close(source_dbip);
db_close(work_dbip);
return BRLCAD_ERROR;
}
db_update_nref(work_dbip);
struct rt_wdb *work_wdbp = wdb_dbopen(work_dbip,
RT_WDB_TYPE_DB_DEFAULT);
if (!work_wdbp) {
db_close(source_dbip);
db_close(work_dbip);
return BRLCAD_ERROR;
}
(void)bu_file_delete(result_file);
struct db_i *staging_dbip = db_create(result_file,
BRLCAD_DB_FORMAT_LATEST);
struct rt_wdb *staging_wdbp = staging_dbip ?
wdb_dbopen(staging_dbip, RT_WDB_TYPE_DB_DEFAULT) : NULL;
if (!staging_dbip || !staging_wdbp) {
if (staging_dbip)
db_close(staging_dbip);
db_close(source_dbip);
db_close(work_dbip);
return BRLCAD_ERROR;
}
struct bu_vls failure_message = BU_VLS_INIT_ZERO;
struct bu_vls tolerated_failure_log = BU_VLS_INIT_ZERO;
struct _ged_facetize_state state = {};
state.verbosity = -1;
state.failure_msg = &failure_message;
state.tolerated_failure_log = &tolerated_failure_log;
state.dbip = source_dbip;
int server_status = BRLCAD_OK;
FacetizeWorkerServer channel(stdin, stdout);
while (true) {
FacetizeWorkerRequest request;
FacetizeWorkerReadResult read_result =
channel.receive_request(request);
if (read_result == FacetizeWorkerReadResult::End)
break;
if (read_result == FacetizeWorkerReadResult::Error ||
request.operation != FacetizeWorkerOperation::EvaluateRegion ||
request.input_names.size() != 1) {
server_status = BRLCAD_ERROR;
break;
}
const std::string &object_name = request.input_names.front();
state.no_empty = request.region.no_empty;
state.no_fixup = request.region.no_fixup;
state.tolerate_failures = request.region.tolerate_failures;
state.error_flag = 0;
state.facetize_tree = NULL;
state.tolerated_failures = 0;
state.tolerated_failure_details = 0;
state.tolerated_failure_omitted = 0;
bu_vls_trunc(&failure_message, 0);
bu_vls_trunc(&tolerated_failure_log, 0);
bool result_sent = false;
int ret = facetize_region_server_request(&state, work_dbip,
work_wdbp, staging_dbip, staging_wdbp, object_name.c_str(),
channel, &result_sent);
if (ret != BRLCAD_OK && bu_vls_strlen(&failure_message))
bu_log("FACETIZE: region Boolean evaluation failed for %s: %s\n",
object_name.c_str(), bu_vls_cstr(&failure_message));
if (!result_sent && !channel.send_tessellation_result(ret,
facetize_resident_size())) {
server_status = BRLCAD_ERROR;
break;
}
}
bu_vls_free(&tolerated_failure_log);
bu_vls_free(&failure_message);
db_close(staging_dbip);
db_close(source_dbip);
db_close(work_dbip);
return server_status;
}
static int
facetize_writer(const char *work_file)
{
setvbuf(stdout, NULL, _IONBF, 0);
struct db_i *dbip = db_open(work_file, DB_OPEN_READWRITE);
if (!dbip)
return BRLCAD_ERROR;
if (db_dirbuild(dbip) < 0) {
db_close(dbip);
return BRLCAD_ERROR;
}
int writer_status = BRLCAD_OK;
FacetizeWorkerServer channel(stdin, stdout);
while (true) {
FacetizeCommitRequest request;
FacetizeWorkerReadResult read_result = channel.receive_commit(request);
if (read_result == FacetizeWorkerReadResult::End)
break;
if (read_result == FacetizeWorkerReadResult::Error ||
!channel.send_write_ready(request.payload_size,
facetize_resident_size())) {
writer_status = BRLCAD_ERROR;
break;
}
facetize_test_fault(FACETIZE_TEST_FAULT_WRITER_PROCEED,
request.object_name.c_str());
if (!channel.receive_write_proceed()) {
writer_status = BRLCAD_ERROR;
break;
}
if (!channel.send_write_started()) {
writer_status = BRLCAD_ERROR;
break;
}
int ret = facetize_transfer_staged_object(dbip,
request.result_file.c_str(), request.object_name.c_str(), ID_BOT);
if (ret == BRLCAD_OK)
facetize_test_fault(FACETIZE_TEST_FAULT_WRITER_DONE,
request.object_name.c_str());
if (!channel.send_write_result(ret, facetize_resident_size())) {
writer_status = BRLCAD_ERROR;
break;
}
}
db_close(dbip);
return writer_status;
}
static int
facetize_nmg_server(const char *source_file, const char *result_file)
{
if (!source_file || !result_file)
return BRLCAD_ERROR;
setvbuf(stdout, NULL, _IONBF, 0);
struct ged *gedp = ged_open("db", source_file, 1);
if (!gedp)
return BRLCAD_ERROR;
struct db_i *result_dbip = db_create(result_file,
BRLCAD_DB_FORMAT_LATEST);
if (!result_dbip) {
ged_close(gedp);
return BRLCAD_ERROR;
}
FacetizeWorkerServer channel(stdin, stdout);
FacetizeWorkerRequest request;
FacetizeWorkerReadResult read_result = channel.receive_request(request);
int server_status = BRLCAD_OK;
FacetizeNmgBooleanResult *result = NULL;
int ret = (read_result == FacetizeWorkerReadResult::Request) ?
facetize_nmg_boolean_evaluate(gedp, request, &result) : BRLCAD_ERROR;
if (read_result != FacetizeWorkerReadResult::Request) {
server_status = BRLCAD_ERROR;
} else if (ret == BRLCAD_OK) {
size_t payload_size = facetize_nmg_boolean_payload_size(result);
facetize_test_fault(FACETIZE_TEST_FAULT_NMG_READY,
request.output_name.c_str());
if (!channel.send_write_ready(payload_size,
facetize_resident_size()) ||
!channel.receive_write_proceed() ||
!channel.send_write_started()) {
server_status = BRLCAD_ERROR;
} else {
ret = facetize_nmg_boolean_write(result_dbip, result);
if (!channel.send_write_result(ret, facetize_resident_size()))
server_status = BRLCAD_ERROR;
}
} else if (!channel.send_tessellation_result(ret,
facetize_resident_size())) {
server_status = BRLCAD_ERROR;
}
facetize_nmg_boolean_destroy(result);
db_close(result_dbip);
ged_close(gedp);
return server_status;
}
@@ -465,10 +825,16 @@ facetize_process(int argc, const char **argv)
int list_methods = 0;
int server_mode = 0;
int writer_mode = 0;
int validation_server_mode = 0;
int region_server_mode = 0;
int nmg_server_mode = 0;
int max_time = 0;
int max_pnts = 0;
int worker_threads = 0;
struct bu_vls result_file = BU_VLS_INIT_ZERO;
struct bu_opt_desc d[10];
struct bu_opt_desc d[16];
BU_OPT(d[ 0], "h", "help", "", NULL, &print_help, "Print help and exit");
BU_OPT(d[ 1], "", "list-methods", "", NULL, &list_methods, "List available tessellation methods. When used with -h, print an informational summary of each method.");
BU_OPT(d[ 2], "O", "overwrite", "", NULL, &(s.overwrite_obj), "Replace original object with BoT");
@@ -477,8 +843,14 @@ facetize_process(int argc, const char **argv)
BU_OPT(d[ 5], "", "max-time", "#", &bu_opt_int, &max_time, "Maximum number of seconds to allow for runtime (not supported by all methods).");
BU_OPT(d[ 6], "", "max-pnts", "#", &bu_opt_int, &max_pnts, "Maximum number of pnts to use when applying ray sampling methods.");
BU_OPT(d[ 7], "", "cache-dir", "dir", &bu_opt_vls, &cache_dir, "Directory to use for cached outputs (default is libbu cache directory).");
BU_OPT(d[ 8], "", "server", "", NULL, &server_mode, "Run as a persistent worker, overwriting requested objects in the working database.");
BU_OPT_NULL(d[ 9]);
BU_OPT(d[ 8], "", "server", "", NULL, &server_mode, "Run as a persistent worker.");
BU_OPT(d[ 9], "", "threads", "#", &bu_opt_int, &worker_threads, "Maximum CPU threads available to this process.");
BU_OPT(d[10], "", "result-file", "file.g", &bu_opt_vls, &result_file, "Write server results to a staging database.");
BU_OPT(d[11], "", "writer", "", NULL, &writer_mode, "Run as a persistent staged-result writer.");
BU_OPT(d[12], "", "validation-server", "", NULL, &validation_server_mode, "Run as a persistent CSG validation worker.");
BU_OPT(d[13], "", "region-server", "", NULL, &region_server_mode, "Run as a persistent region Boolean worker.");
BU_OPT(d[14], "", "nmg-server", "", NULL, &nmg_server_mode, "Run one isolated NMG Boolean request.");
BU_OPT_NULL(d[15]);
/* parse options */
struct bu_vls omsg = BU_VLS_INIT_ZERO;
@@ -490,13 +862,33 @@ facetize_process(int argc, const char **argv)
}
bu_vls_free(&omsg);
if (worker_threads < 0 || worker_threads > MAX_PSW) {
bu_vls_free(&cache_dir);
bu_vls_free(&result_file);
return BRLCAD_ERROR;
}
if (worker_threads)
bu_avail_cpus_set((size_t)worker_threads);
int worker_mode_count = server_mode + writer_mode +
validation_server_mode + region_server_mode + nmg_server_mode;
if (worker_mode_count > 1) {
bu_vls_free(&cache_dir);
bu_vls_free(&result_file);
return BRLCAD_ERROR;
}
if (list_methods && print_help) {
print_methods_info();
bu_vls_free(&cache_dir);
bu_vls_free(&result_file);
return BRLCAD_OK;
}
if (list_methods) {
print_tess_methods();
bu_vls_free(&cache_dir);
bu_vls_free(&result_file);
return BRLCAD_OK;
}
@@ -513,9 +905,55 @@ facetize_process(int argc, const char **argv)
bu_log("%s\n", bu_vls_cstr(&str));
bu_vls_free(&str);
bu_vls_free(&cache_dir);
bu_vls_free(&result_file);
return BRLCAD_OK;
}
if (writer_mode) {
int ret = (argc == 1 && !bu_vls_strlen(&result_file)) ?
facetize_writer(argv[0]) : BRLCAD_ERROR;
bu_vls_free(&cache_dir);
bu_vls_free(&result_file);
return ret;
}
if (validation_server_mode) {
int ret = (argc == 1 && !bu_vls_strlen(&result_file)) ?
facetize_validation_server(argv[0]) : BRLCAD_ERROR;
bu_vls_free(&cache_dir);
bu_vls_free(&result_file);
return ret;
}
if (region_server_mode) {
int ret = (argc == 2 && bu_vls_strlen(&result_file)) ?
facetize_region_server(argv[0], argv[1],
bu_vls_cstr(&result_file)) : BRLCAD_ERROR;
bu_vls_free(&cache_dir);
bu_vls_free(&result_file);
return ret;
}
if (nmg_server_mode) {
int ret = (argc == 1 && bu_vls_strlen(&result_file)) ?
facetize_nmg_server(argv[0], bu_vls_cstr(&result_file)) :
BRLCAD_ERROR;
bu_vls_free(&cache_dir);
bu_vls_free(&result_file);
return ret;
}
if (server_mode) {
int ret = (argc == 1) ?
facetize_server(argv[0], bu_vls_strlen(&result_file) ?
bu_vls_cstr(&result_file) : NULL) :
BRLCAD_ERROR;
bu_vls_free(&cache_dir);
bu_vls_free(&result_file);
return ret;
}
// If we have a non-default cache directory specified, set it up
if (bu_vls_strlen(&cache_dir)) {
// Make sure it's there first
@@ -524,19 +962,13 @@ facetize_process(int argc, const char **argv)
bu_setenv("BU_DIR_CACHE", bu_vls_cstr(&cache_dir), 1);
}
// Do the setup for the various methods
// Do the setup for the various tessellation methods.
method_setup(&s);
if (server_mode) {
int ret = (argc == 1 && s.overwrite_obj) ?
facetize_server(argv[0], &s) : BRLCAD_ERROR;
bu_vls_free(&cache_dir);
return ret;
}
if (argc < 2) {
bu_log("%s", usage);
bu_vls_free(&cache_dir);
bu_vls_free(&result_file);
return BRLCAD_ERROR;
}
@@ -544,6 +976,7 @@ facetize_process(int argc, const char **argv)
struct ged *gedp = ged_open("db", argv[0], 1);
if (!gedp) {
bu_vls_free(&cache_dir);
bu_vls_free(&result_file);
return BRLCAD_ERROR;
}
@@ -555,6 +988,7 @@ facetize_process(int argc, const char **argv)
bu_ptbl_free(&dps);
ged_close(gedp);
bu_vls_free(&cache_dir);
bu_vls_free(&result_file);
return BRLCAD_ERROR;
}
bu_ptbl_ins(&dps, (long *)dp);
@@ -607,6 +1041,7 @@ facetize_process(int argc, const char **argv)
bu_ptbl_free(&dps);
ged_close(gedp);
bu_vls_free(&cache_dir);
bu_vls_free(&result_file);
return process_ret;
}
+137
View File
@@ -0,0 +1,137 @@
/* M D C . C P P
* BRL-CAD
*
* Copyright (c) 2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library 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 this file; see the file named COPYING for more
* information.
*/
/** @file mdc.cpp
*
* Facetize adapter for libanalyze's ray-driven manifold dual contourer.
*/
#include "common.h"
#include "analyze/contour.h"
#include "bu/log.h"
#include "rt/primitives/bot.h"
#include "./tessellate.h"
#include "../validation.h"
static const char *
mdc_status_message(enum analyze_mdc_status status)
{
switch (status) {
case ANALYZE_MDC_OK:
return "success";
case ANALYZE_MDC_INVALID_INPUT:
return "invalid settings or input";
case ANALYZE_MDC_PREP_FAILED:
return "raytrace preparation failed";
case ANALYZE_MDC_NO_SURFACE:
return "no closed surface was sampled";
case ANALYZE_MDC_RAY_LIMIT:
return "ray limit reached";
case ANALYZE_MDC_TIMEOUT:
return "time limit reached";
case ANALYZE_MDC_MEMORY_LIMIT:
return "free-memory limit reached";
case ANALYZE_MDC_AMBIGUOUS:
return "surface remained ambiguous at the maximum depth";
case ANALYZE_MDC_NOT_MANIFOLD:
return "generated mesh was not a closed oriented manifold";
}
return "unknown error";
}
int
mdc_mesh(struct rt_bot_internal **output, struct db_i *dbip,
const char *object, tess_opts *settings)
{
if (!output || !dbip || !object || !settings)
return BRLCAD_ERROR;
*output = NULL;
const mdc_opts &options = settings->mdc_options;
if (!options.invalid_option.empty()) {
bu_log("MDC: invalid option for %s: %s\n", object,
options.invalid_option.c_str());
return BRLCAD_ERROR;
}
struct analyze_mdc_params params = ANALYZE_MDC_PARAMS_DEFAULT;
params.feature_size = options.feature_size;
params.max_rays = static_cast<size_t>(options.max_rays);
params.minimum_free_mem =
static_cast<size_t>(options.minimum_free_mem);
params.min_depth = options.min_depth;
params.max_depth = options.max_depth;
params.max_time = options.max_time;
params.verbosity = options.verbosity;
int *faces = NULL;
point_t *vertices = NULL;
size_t face_count = 0;
size_t vertex_count = 0;
struct bu_hook_list saved_hooks = BU_HOOK_LIST_INIT_ZERO;
bool silence_logs = (options.verbosity == 0);
if (silence_logs)
facetize_log_hooks_silence(&saved_hooks);
enum analyze_mdc_status status = analyze_mdc(&faces, &face_count,
&vertices, &vertex_count, object, dbip, &params);
if (silence_logs)
facetize_log_hooks_restore(&saved_hooks);
if (status != ANALYZE_MDC_OK) {
bu_log("MDC: failed to tessellate %s: %s\n", object,
mdc_status_message(status));
return BRLCAD_ERROR;
}
struct rt_bot_internal *bot;
BU_ALLOC(bot, struct rt_bot_internal);
bot->magic = RT_BOT_INTERNAL_MAGIC;
bot->mode = RT_BOT_SOLID;
bot->orientation = RT_BOT_CCW;
bot->num_faces = face_count;
bot->num_vertices = vertex_count;
bot->faces = faces;
bot->vertices = reinterpret_cast<fastf_t *>(vertices);
if (!bot_is_manifold(bot)) {
bu_log("MDC: generated mesh for %s is not accepted by Manifold\n",
object);
_tess_facetize_free_bot(bot);
return BRLCAD_ERROR;
}
*output = bot;
return BRLCAD_OK;
}
/*
* Local Variables:
* mode: C++
* tab-width: 8
* c-basic-offset: 4
* indent-tabs-mode: t
* c-file-style: "stroustrup"
* End:
* ex: shiftwidth=4 tabstop=8
*/
+2 -1
View File
@@ -42,7 +42,8 @@ _nmg_tessellate(struct rt_bot_internal **nbot, struct rt_db_internal *intern, te
int ret = BRLCAD_ERROR;
struct bu_list *vlfree = &rt_vlfree;
if (!nbot || !intern || !intern->idb_meth || !s)
if (!nbot || !intern || !intern->idb_meth || !s ||
!intern->idb_meth->ft_tessellate)
return BRLCAD_ERROR;
// TODO - get the nmg debug option from nmg_options and set it
@@ -0,0 +1,279 @@
/* N M G _ B O O L E A N . C P P
* BRL-CAD
*
* Copyright (c) 2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library 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 this file; see the file named COPYING for more
* information.
*/
/** @file libged/facetize/subprocess/nmg_boolean.cpp
*
* Isolated NMG tree evaluation for the facetize worker. An NMG bomb may
* invalidate the model's topology, so a bombed request intentionally leaves
* its allocations to process teardown rather than risking another bomb while
* attempting cleanup.
*/
#include "common.h"
#include <string>
#include <vector>
#include "raytrace.h"
#include "wdb.h"
#include "../../ged_private.h"
#include "../ged_facetize.h"
#include "./nmg_boolean.h"
struct FacetizeNmgBooleanResult {
struct model *nmg_model = NULL;
struct rt_bot_internal *bot = NULL;
};
struct FacetizeNmgBooleanState {
union tree *tree = NULL;
};
static union tree *
facetize_nmg_region_end(struct db_tree_state *tsp,
const struct db_full_path *pathp, union tree *current_tree,
void *client_data)
{
if (tsp)
RT_CK_DBTS(tsp);
if (pathp)
RT_CK_FULL_PATH(pathp);
FacetizeNmgBooleanState *state =
static_cast<FacetizeNmgBooleanState *>(client_data);
if (!state || !current_tree || current_tree->tr_op == OP_NOP)
return current_tree;
if (!state->tree) {
state->tree = current_tree;
return TREE_NULL;
}
union tree *union_tree;
BU_ALLOC(union_tree, union tree);
RT_TREE_INIT(union_tree);
union_tree->tr_op = OP_UNION;
union_tree->tr_b.tb_regionp = REGION_NULL;
union_tree->tr_b.tb_left = state->tree;
union_tree->tr_b.tb_right = current_tree;
state->tree = union_tree;
return TREE_NULL;
}
static union tree *
facetize_nmg_leaf(struct db_tree_state *tsp,
const struct db_full_path *pathp, struct rt_db_internal *ip,
void *UNUSED(client_data))
{
union tree *leaf = rt_booltree_leaf_tess(tsp, pathp, ip, NULL);
if (!leaf && pathp) {
char *path = db_path_to_string(pathp);
bu_log("NMG leaf tessellation failed for '%s'\n",
path ? path : "(unknown)");
if (path)
bu_free(path, "NMG leaf path");
}
return leaf;
}
static int
facetize_nmg_compute(struct ged *gedp,
const FacetizeWorkerRequest &request,
FacetizeNmgBooleanResult *result)
{
struct rt_wdb *wdbp = wdb_dbopen(gedp->dbip, RT_WDB_TYPE_DB_DEFAULT);
if (!wdbp)
return BRLCAD_ERROR;
struct db_tree_state initial_state;
db_init_db_tree_state(&initial_state, gedp->dbip);
initial_state.ts_ttol = &wdbp->wdb_ttol;
initial_state.ts_tol = &wdbp->wdb_tol;
struct model *nmg_model = nmg_mm();
initial_state.ts_m = &nmg_model;
FacetizeNmgBooleanState state;
std::vector<const char *> input_argv;
input_argv.reserve(request.input_names.size());
for (const std::string &input_name : request.input_names)
input_argv.push_back(input_name.c_str());
int walk_result = BRLCAD_ERROR;
if (!BU_SETJUMP) {
walk_result = db_walk_tree(gedp->dbip, (int)input_argv.size(),
input_argv.data(), 1, &initial_state, NULL,
facetize_nmg_region_end, facetize_nmg_leaf, &state);
} else {
BU_UNSETJUMP;
bu_log("NMG tree tessellation bombed while processing %s\n",
request.output_name.c_str());
return BRLCAD_ERROR;
}
BU_UNSETJUMP;
if (walk_result < 0 || !state.tree) {
if (state.tree)
db_free_tree(state.tree);
nmg_km(nmg_model);
return BRLCAD_ERROR;
}
int boolean_result = BRLCAD_ERROR;
if (!BU_SETJUMP) {
boolean_result = nmg_boolean(state.tree, nmg_model, &rt_vlfree,
&wdbp->wdb_tol);
if (boolean_result == 0) {
NMG_CK_REGION(state.tree->tr_d.td_r);
state.tree->tr_d.td_r = NULL;
}
} else {
BU_UNSETJUMP;
bu_log("NMG Boolean evaluation bombed while processing %s\n",
request.output_name.c_str());
return BRLCAD_ERROR;
}
BU_UNSETJUMP;
if (boolean_result != 0) {
db_free_tree(state.tree);
nmg_km(nmg_model);
return BRLCAD_ERROR;
}
db_free_tree(state.tree);
if (request.operation == FacetizeWorkerOperation::NmgBooleanToNmg) {
result->nmg_model = nmg_model;
return BRLCAD_OK;
}
struct rt_bot_internal *bot = NULL;
if (!BU_SETJUMP) {
bot = static_cast<struct rt_bot_internal *>(
nmg_mdl_to_bot(nmg_model, &rt_vlfree, &wdbp->wdb_tol));
} else {
BU_UNSETJUMP;
bu_log("NMG-to-BoT conversion bombed while processing %s\n",
request.output_name.c_str());
return BRLCAD_ERROR;
}
BU_UNSETJUMP;
nmg_km(nmg_model);
if (!bot)
return BRLCAD_ERROR;
result->bot = bot;
return BRLCAD_OK;
}
int
facetize_nmg_boolean_evaluate(struct ged *gedp,
const FacetizeWorkerRequest &request,
FacetizeNmgBooleanResult **result)
{
if (!gedp || !result || !request.valid() ||
(request.operation != FacetizeWorkerOperation::NmgBooleanToBot &&
request.operation != FacetizeWorkerOperation::NmgBooleanToNmg))
return BRLCAD_ERROR;
*result = NULL;
FacetizeNmgBooleanResult *evaluation =
new FacetizeNmgBooleanResult;
if (facetize_nmg_compute(gedp, request, evaluation) != BRLCAD_OK) {
/* Bomb paths deliberately abandon unsafe NMG allocations until this
* one-shot worker exits. */
facetize_nmg_boolean_destroy(evaluation);
return BRLCAD_ERROR;
}
*result = evaluation;
return BRLCAD_OK;
}
size_t
facetize_nmg_boolean_payload_size(
const FacetizeNmgBooleanResult *UNUSED(result))
{
/* NMG model storage is graph-shaped and has no cheap serialized-size
* estimate. The supervisor applies its conservative default write
* timeout when the estimate is zero. */
return 0;
}
int
facetize_nmg_boolean_write(struct db_i *dbip,
FacetizeNmgBooleanResult *result)
{
if (!dbip || !result || (!result->bot && !result->nmg_model))
return BRLCAD_ERROR;
struct rt_db_internal intern;
RT_DB_INTERNAL_INIT(&intern);
intern.idb_major_type = DB5_MAJORTYPE_BRLCAD;
intern.idb_type = result->bot ? ID_BOT : ID_NMG;
intern.idb_meth = &OBJ[intern.idb_type];
intern.idb_ptr = result->bot ? static_cast<void *>(result->bot) :
static_cast<void *>(result->nmg_model);
bu_avs_init_empty(&intern.idb_avs);
(void)bu_avs_add(&intern.idb_avs, "facetized", "1");
(void)bu_avs_add(&intern.idb_avs, FACETIZE_METHOD_ATTR, "NMG Boolean");
struct directory *output = db_diradd(dbip,
FACETIZE_WORKER_RESULT_OBJECT, RT_DIR_PHONY_ADDR, 0,
RT_DIR_SOLID, &intern.idb_type);
if (!output) {
rt_db_free_internal(&intern);
result->bot = NULL;
result->nmg_model = NULL;
return BRLCAD_ERROR;
}
int write_result = rt_db_put_internal(output, dbip, &intern);
result->bot = NULL;
result->nmg_model = NULL;
return write_result < 0 ? BRLCAD_ERROR : BRLCAD_OK;
}
void
facetize_nmg_boolean_destroy(FacetizeNmgBooleanResult *result)
{
if (!result)
return;
if (result->bot) {
struct rt_db_internal intern;
RT_DB_INTERNAL_INIT(&intern);
intern.idb_major_type = DB5_MAJORTYPE_BRLCAD;
intern.idb_type = ID_BOT;
intern.idb_meth = &OBJ[ID_BOT];
intern.idb_ptr = result->bot;
rt_db_free_internal(&intern);
}
if (result->nmg_model)
nmg_km(result->nmg_model);
delete result;
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
@@ -0,0 +1,41 @@
/* N M G _ B O O L E A N . H
* BRL-CAD
*
* Copyright (c) 2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library 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 this file; see the file named COPYING for more
* information.
*/
#ifndef FACETIZE_PROCESS_NMG_BOOLEAN_H
#define FACETIZE_PROCESS_NMG_BOOLEAN_H
#include <cstddef>
#include "../worker.h"
struct db_i;
struct ged;
struct FacetizeNmgBooleanResult;
int facetize_nmg_boolean_evaluate(struct ged *gedp,
const FacetizeWorkerRequest &request,
FacetizeNmgBooleanResult **result);
size_t facetize_nmg_boolean_payload_size(
const FacetizeNmgBooleanResult *result);
int facetize_nmg_boolean_write(struct db_i *dbip,
FacetizeNmgBooleanResult *result);
void facetize_nmg_boolean_destroy(FacetizeNmgBooleanResult *result);
#endif /* FACETIZE_PROCESS_NMG_BOOLEAN_H */
-177
View File
@@ -1,177 +0,0 @@
/* S A M P L E . C P P
* BRL-CAD
*
* Copyright (c) 2008-2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library 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 this file; see the file named COPYING for more
* information.
*/
/** @file libged/facetize/continuation.cpp
*
* The facetize command's Continuation Method implementation.
*/
#include "common.h"
#include "vmath.h"
#include "bu/datetime.h"
#include "bg/trimesh.h"
#include "raytrace.h"
#include "analyze/polygonize.h"
#include "../../ged_private.h"
#include "./tessellate.h"
#define FACETIZE_MEMORY_THRESHOLD 150000000
static void
_rt_pnts_bbox(point_t rpp_min, point_t rpp_max, struct rt_pnts_internal *pnts)
{
struct pnt_normal *pn = NULL;
struct pnt_normal *pl = NULL;
if (!rpp_min || !rpp_max || !pnts || !pnts->point) return;
VSETALL(rpp_min, INFINITY);
VSETALL(rpp_max, -INFINITY);
pl = (struct pnt_normal *)pnts->point;
for (BU_LIST_FOR(pn, pnt_normal, &(pl->l))) {
VMINMAX(rpp_min, rpp_max, pn->v);
}
}
static double
_bbox_vol(point_t b_min, point_t b_max)
{
double bbox_vol = 0.0;
fastf_t b_xlen, b_ylen, b_zlen;
b_xlen = fabs(b_max[X] - b_min[X]);
b_ylen = fabs(b_max[Y] - b_min[Y]);
b_zlen = fabs(b_max[Z] - b_min[Z]);
bbox_vol = b_xlen * b_ylen * b_zlen;
return bbox_vol;
}
struct rt_pnts_internal *
_tess_pnts_sample(const char *oname, struct db_i *dbip, tess_opts *s)
{
if (!oname || !dbip || !s)
return NULL;
struct directory *dp = db_lookup(dbip, oname, LOOKUP_QUIET);
if (!dp)
return NULL;
/* If we have a point cloud or half, this won't work */
if (dp->d_minor_type == DB5_MINORTYPE_BRLCAD_PNTS || dp->d_minor_type == DB5_MINORTYPE_BRLCAD_HALF)
return NULL;
/* Key some settings off the bbox size */
point_t obj_min, obj_max;
struct bu_vls msg = BU_VLS_INIT_ZERO;
rt_obj_bounds(&msg, dbip, 1, (const char **)&oname, 0, obj_min, obj_max);
if (bu_vls_strlen(&msg))
bu_log("Bounds calculation: %s\n", bu_vls_cstr(&msg));
bu_vls_free(&msg);
point_t rpp_min, rpp_max;
VSETALL(rpp_min, INFINITY);
VSETALL(rpp_max, -INFINITY);
VMINMAX(rpp_min, rpp_max, (double *)obj_min);
VMINMAX(rpp_min, rpp_max, (double *)obj_max);
double xlen = fabs(rpp_max[X] - rpp_min[X]);
double ylen = fabs(rpp_max[Y] - rpp_min[Y]);
double zlen = fabs(rpp_max[Z] - rpp_min[Z]);
/* Pick our mode(s) */
int flags = 0;
flags |= RT_GEN_OBJ_PNTS_RAND;
//flags |= RT_GEN_OBJ_PNTS_SOBOL;
struct rt_pnts_internal *pnts = NULL;
BU_GET(pnts, struct rt_pnts_internal);
pnts->magic = RT_PNTS_INTERNAL_MAGIC;
pnts->scale = 0.0;
pnts->count = 0;
pnts->type = RT_PNT_TYPE_NRM;
pnts->point = NULL;
/* Shoot - we need both the avg thickness of the hit partitions and seed points */
struct bn_tol btol = BN_TOL_INIT_TOL;
if (rt_gen_obj_pnts(pnts, &s->pnt_options.avg_thickness, dbip, oname, &btol, flags, s->pnt_options.max_pnts, s->pnt_options.max_sample_time, 1) || pnts->count <= 0) {
struct pnt_normal *rpnt = (struct pnt_normal *)pnts->point;
if (rpnt) {
struct pnt_normal *entry;
while (BU_LIST_WHILE(entry, pnt_normal, &(rpnt->l))) {
BU_LIST_DEQUEUE(&(entry->l));
BU_PUT(entry, struct pnt_normal);
}
BU_PUT(rpnt, struct pnt_normal);
}
BU_PUT(pnts, struct rt_pnts_internal);
return NULL;
}
/* Check the volume of the bounding box of input object against the bounding box
* of the point cloud - a large difference means something probably isn't
* right. This one we are a bit more generous with, since the parent bbox
* may not be terribly tight. */
{
point_t p_min, p_max;
VSETALL(p_min, INFINITY);
VSETALL(p_max, -INFINITY);
_rt_pnts_bbox(p_min, p_max, pnts);
s->pnt_options.pnts_bbox_vol = _bbox_vol(p_min, p_max);
s->pnt_options.obj_bbox_vol = _bbox_vol(rpp_min, rpp_max);
if (fabs(s->pnt_options.obj_bbox_vol - s->pnt_options.pnts_bbox_vol)/s->pnt_options.obj_bbox_vol > 1) {
struct pnt_normal *rpnt = (struct pnt_normal *)pnts->point;
if (rpnt) {
struct pnt_normal *entry;
while (BU_LIST_WHILE(entry, pnt_normal, &(rpnt->l))) {
BU_LIST_DEQUEUE(&(entry->l));
BU_PUT(entry, struct pnt_normal);
}
BU_PUT(rpnt, struct pnt_normal);
}
BU_PUT(pnts, struct rt_pnts_internal);
return NULL;
}
}
/* Find the smallest value from either the bounding box lengths or the avg
* thickness observed by the rays. Some fraction of this value is our box
* size for the polygonizer and the decimation routine */
double min_len = (xlen < ylen) ? xlen : ylen;
min_len = (min_len < zlen) ? min_len : zlen;
min_len = (min_len < s->pnt_options.avg_thickness) ? min_len : s->pnt_options.avg_thickness;
if (s->pnt_options.feature_size > 0) {
s->pnt_options.target_feature_size = 0.5*s->pnt_options.feature_size;
} else {
s->pnt_options.target_feature_size = min_len * s->pnt_options.feature_scale;
}
bu_log("feature_size: %f\n", s->pnt_options.feature_size);
bu_log("feature_scale: %f\n", s->pnt_options.feature_scale);
bu_log("target_feature_size: %f\n", s->pnt_options.target_feature_size);
return pnts;
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
File diff suppressed because it is too large Load Diff
+6 -7
View File
@@ -41,11 +41,10 @@ class tess_opts {
public:
method_options_t method_opts;
nmg_opts nmg_options;
cm_opts cm_options;
mdc_opts mdc_options;
spsr_opts spsr_options;
int overwrite_obj = 0;
sample_opts pnt_options; // Values used by sample.cpp
};
extern struct rt_bot_internal *
@@ -57,9 +56,6 @@ _tess_facetize_write_bot(struct db_i *dbip, struct rt_bot_internal *bot, const c
extern void
_tess_facetize_free_bot(struct rt_bot_internal *bot);
extern struct rt_pnts_internal *
_tess_pnts_sample(const char *oname, struct db_i *dbip, tess_opts *s);
extern int
_brep_csg_tessellate(struct rt_bot_internal **obot, struct ged *gedp,
struct directory *dp, tess_opts *s);
@@ -68,10 +64,13 @@ extern int
_nmg_tessellate(struct rt_bot_internal **nbot, struct rt_db_internal *intern, tess_opts *s);
extern int
continuation_mesh(struct rt_bot_internal **obot, struct db_i *dbip, const char *objname, tess_opts *s, point_t seed);
mdc_mesh(struct rt_bot_internal **output, struct db_i *dbip,
const char *object, tess_opts *settings);
extern int
spsr_mesh(struct rt_bot_internal **obot, struct db_i *dbip, struct rt_pnts_internal *pnts, tess_opts *s);
spsr_mesh(struct rt_bot_internal **obot, struct db_i *dbip,
const char *object, struct rt_pnts_internal *pnts,
bool best_effort_source, tess_opts *s);
extern bool
bot_is_manifold(struct rt_bot_internal *bot);
+165 -134
View File
@@ -39,6 +39,7 @@
#include "bn/tol.h"
#include "bg/defines.h"
#include "bg/spsr.h"
#include "analyze/contour.h"
#include "raytrace.h"
class method_options_t {
@@ -63,6 +64,13 @@ class method_options_t {
std::string method_optstr(std::string &method, struct db_i *dbip);
};
inline const std::vector<std::string> &
tess_default_methods()
{
static const std::vector<std::string> methods = {"NMG", "MDC", "SPSR"};
return methods;
}
int _tess_active_methods(struct bu_vls *msg, size_t argc, const char **argv, void *set_var);
int _tess_method_opts(struct bu_vls *msg, size_t argc, const char **argv, void *set_var);
@@ -111,18 +119,24 @@ class nmg_opts : public method_opts {
int plate_max_time = 1200;
};
class cm_opts : public sample_opts {
class mdc_opts : public method_opts {
public:
std::string about_method();
std::string print_options_help();
int set_var(const std::string &key, const std::string &val);
void sync(method_options_t &mopts);
void sync(sample_opts &sopts);
int max_cycle_time = 30; // Maximum length of a processing cycle to allow before finalizing
int max_time = 600; // Maximum overall time
fastf_t feature_size = 0.0;
long max_rays = ANALYZE_MDC_DEFAULT_MAX_RAYS;
long minimum_free_mem = ANALYZE_MDC_DEFAULT_MINIMUM_FREE_MEM;
int min_depth = ANALYZE_MDC_DEFAULT_MIN_DEPTH;
int max_depth = ANALYZE_MDC_DEFAULT_MAX_DEPTH;
int max_time = ANALYZE_MDC_DEFAULT_MAX_TIME;
int verbosity = 0;
std::string invalid_option;
};
class spsr_opts : public sample_opts {
public:
std::string about_method();
@@ -132,10 +146,8 @@ class spsr_opts : public sample_opts {
void sync(sample_opts &sopts);
struct bg_3d_spsr_opts s_opts = BG_3D_SPSR_OPTS_DEFAULT;
int depth = 8; // Maximum reconstruction depth s_opts.depth
fastf_t interpolate = 2.0; // Lower values (down to 0.0) bias towards a smoother mesh, higher values bias towards interpolation accuracy. s_opts.point_weight
fastf_t samples_per_node = 1.5; // How many samples should go into a cell before it is refined. s_opts.samples_per_node
int max_time = 600; // Maximum overall time
int refinement_passes = BG_3D_SPSR_DEFAULT_REFINEMENT_PASSES;
int max_time = 600;
};
@@ -146,11 +158,11 @@ class spsr_opts : public sample_opts {
method_options_t::method_options_t()
{
nmg_opts n;
cm_opts cm;
mdc_opts mdc;
spsr_opts s;
max_time[std::string("NMG")] = n.max_time;
max_time[std::string("CM")] = cm.max_time;
max_time[std::string("MDC")] = mdc.max_time;
max_time[std::string("SPSR")] = s.max_time;
plate_max_time = n.plate_max_time;
}
@@ -296,52 +308,36 @@ sample_opts::print_options_help()
int
sample_opts::set_var(const std::string &key, const std::string &val)
{
if (key.length() == 0)
if (key.empty())
return BRLCAD_ERROR;
const char *cstr[2];
cstr[0] = val.c_str();
cstr[1] = NULL;
const char *value[2] = {val.c_str(), NULL};
if (key == "feature_scale" || key == "feature_size" ||
key == "d_feature_size") {
fastf_t parsed = 0.0;
if ((!val.empty() &&
bu_opt_fastf_t(NULL, 1, value, &parsed) < 0) ||
parsed < 0.0)
return BRLCAD_ERROR;
if (key == "feature_scale")
feature_scale = parsed;
else if (key == "feature_size")
feature_size = parsed;
else
d_feature_size = parsed;
return BRLCAD_OK;
}
if (key == std::string("feature_scale")) {
if (!val.length()) {
feature_scale = 0.0;
return BRLCAD_OK;
}
if (bu_opt_fastf_t(NULL, 1, (const char **)cstr, (void *)&feature_scale) < 0)
return BRLCAD_ERROR;
}
if (key == std::string("feature_size")) {
if (!val.length()) {
feature_size = 0.0;
return BRLCAD_OK;
}
if (bu_opt_fastf_t(NULL, 1, (const char **)cstr, (void *)&feature_size) < 0)
return BRLCAD_ERROR;
}
if (key == std::string("d_feature_size")) {
if (!val.length()) {
d_feature_size = 0.0;
return BRLCAD_OK;
}
if (bu_opt_fastf_t(NULL, 1, (const char **)cstr, (void *)&d_feature_size) < 0)
return BRLCAD_ERROR;
}
if (key == std::string("max_sample_time")) {
if (!val.length()) {
max_sample_time = 0;
return BRLCAD_OK;
}
if (bu_opt_int(NULL, 1, (const char **)cstr, (void *)&max_sample_time) < 0)
return BRLCAD_ERROR;
}
if (key == std::string("max_pnts")) {
if (!val.length()) {
max_pnts = 0;
return BRLCAD_OK;
}
if (bu_opt_int(NULL, 1, (const char **)cstr, (void *)&max_pnts) < 0)
if (key == "max_sample_time" || key == "max_pnts") {
int parsed = 0;
if ((!val.empty() && bu_opt_int(NULL, 1, value, &parsed) < 0) ||
parsed < 0)
return BRLCAD_ERROR;
if (key == "max_sample_time")
max_sample_time = parsed;
else
max_pnts = parsed;
return BRLCAD_OK;
}
return BRLCAD_ERROR;
@@ -379,77 +375,104 @@ sample_opts::equals(sample_opts &o)
}
std::string
cm_opts::about_method()
mdc_opts::about_method()
{
std::string msg = "Continuation Method (Bloomenthal polygonizer)\n";
return msg;
return std::string("Ray-driven Manifold Dual Contouring\n");
}
std::string
cm_opts::print_options_help()
mdc_opts::print_options_help()
{
std::string h = std::string("Continuation (CM) Method Options:\n") + sample_opts::print_options_help();
h.append("max_cycle_time - Maximum time to take for one processing cycle\n");
h.append(" Default is 30. Zero means run until the target\n");
h.append(" size is met or other termination criteria kick\n");
h.append(" in. Be careful when specifying zero - it can\n");
h.append(" produce very long runs!\n");
h.append("max_time - Maximum overall run time for object conversion\n");
return h;
std::string help;
help.append("Manifold Dual Contouring (MDC) options:\n");
help.append("feature_size - Maximum finest-cell edge length. Zero selects\n");
help.append(" an automatic size from the object bounds.\n");
help.append("max_rays - Optional ray-budget ceiling. Zero uses automatic\n");
help.append(" geometry and system resource limits.\n");
help.append("minimum_free_mem - Stop before free memory falls below this many bytes.\n");
help.append("min_depth - Minimum power-of-two grid depth.\n");
help.append("max_depth - Maximum power-of-two grid depth.\n");
help.append("max_time - Maximum run time in seconds. Zero is unlimited.\n");
help.append("verbosity - Emit diagnostics when non-zero.\n");
return help;
}
int
cm_opts::set_var(const std::string &key, const std::string &val)
mdc_opts::set_var(const std::string &key, const std::string &val)
{
if (key.length() == 0)
return BRLCAD_ERROR;
if (key.empty())
return BRLCAD_ERROR;
const char *cstr[2];
cstr[0] = val.c_str();
cstr[1] = NULL;
const char *value[2] = {val.c_str(), NULL};
if (key == "feature_size") {
fastf_t parsed = 0.0;
if ((!val.empty() &&
bu_opt_fastf_t(NULL, 1, value, &parsed) < 0) ||
parsed < 0.0)
return BRLCAD_ERROR;
feature_size = parsed;
return BRLCAD_OK;
}
if (key == std::string("max_cycle_time")) {
if (!val.length()) {
max_cycle_time = 0;
return BRLCAD_OK;
}
if (bu_opt_int(NULL, 1, (const char **)cstr, (void *)&max_cycle_time) < 0)
return BRLCAD_ERROR;
}
if (key == "max_rays" || key == "minimum_free_mem") {
long parsed = 0;
if ((!val.empty() && bu_opt_long(NULL, 1, value, &parsed) < 0) ||
parsed < 0)
return BRLCAD_ERROR;
if (key == "max_rays")
max_rays = parsed;
else
minimum_free_mem = parsed;
return BRLCAD_OK;
}
if (key == std::string("max_time")) {
if (!val.length()) {
max_time = 0;
return BRLCAD_OK;
}
if (bu_opt_int(NULL, 1, (const char **)cstr, (void *)&max_time) < 0)
return BRLCAD_ERROR;
}
int parsed = 0;
if (!val.empty() && bu_opt_int(NULL, 1, value, &parsed) < 0)
return BRLCAD_ERROR;
if (key == "min_depth") {
if (parsed < 1 || parsed > ANALYZE_MDC_MAX_DEPTH)
return BRLCAD_ERROR;
min_depth = parsed;
return BRLCAD_OK;
}
if (key == "max_depth") {
if (parsed < 1 || parsed > ANALYZE_MDC_MAX_DEPTH)
return BRLCAD_ERROR;
max_depth = parsed;
return BRLCAD_OK;
}
if (key == "max_time") {
if (parsed < 0)
return BRLCAD_ERROR;
max_time = parsed;
return BRLCAD_OK;
}
if (key == "verbosity") {
if (parsed < 0)
return BRLCAD_ERROR;
verbosity = parsed;
return BRLCAD_OK;
}
// If it's not a CM setting directly, it may be for sampling
return sample_opts::set_var(key, val);
return BRLCAD_ERROR;
}
void
cm_opts::sync(method_options_t &o)
mdc_opts::sync(method_options_t &options)
{
std::map<std::string, std::map<std::string,std::string>>::iterator o_it;
o_it = o.options_map.find(std::string("CM"));
if (o_it == o.options_map.end())
invalid_option.clear();
auto method = options.options_map.find("MDC");
if (method == options.options_map.end())
return;
std::map<std::string,std::string>::iterator m_it;
for (m_it = o_it->second.begin(); m_it != o_it->second.end(); m_it++) {
set_var(m_it->first, m_it->second);
for (const auto &option : method->second) {
if (set_var(option.first, option.second) != BRLCAD_OK) {
invalid_option = option.first + "=" + option.second;
return;
}
}
}
void
cm_opts::sync(sample_opts &opts)
{
sample_opts::sync(opts);
}
std::string
nmg_opts::about_method()
{
@@ -568,6 +591,9 @@ spsr_opts::print_options_help()
h.append(" mesh, higher values bias towards interpolation\n");
h.append(" accuracy. (Default is 2.0)\n");
h.append("max_time - Maximum overall run time for object conversion\n");
h.append("refinement_passes- Maximum adaptive source-refinement passes. (Default is ");
h.append(std::to_string(BG_3D_SPSR_DEFAULT_REFINEMENT_PASSES));
h.append(")\n");
h.append("samples_per_node - How many samples should go into a cell before it is\n");
h.append(" refined. (Default is 1.5)\n");
return h;
@@ -576,48 +602,53 @@ spsr_opts::print_options_help()
int
spsr_opts::set_var(const std::string &key, const std::string &val)
{
if (key.length() == 0)
if (key.empty())
return BRLCAD_ERROR;
const char *cstr[2];
cstr[0] = val.c_str();
cstr[1] = NULL;
if (key == std::string("depth")) {
if (!val.length()) {
s_opts.depth = 0;
return BRLCAD_OK;
}
if (bu_opt_int(NULL, 1, (const char **)cstr, (void *)&s_opts.depth) < 0)
const char *value[2] = {val.c_str(), NULL};
if (key == "depth") {
int parsed = BG_3D_SPSR_DEFAULT_DEPTH;
if ((!val.empty() && bu_opt_int(NULL, 1, value, &parsed) < 0) ||
parsed < 1)
return BRLCAD_ERROR;
s_opts.depth = parsed;
return BRLCAD_OK;
}
if (key == std::string("interpolate")) {
if (!val.length()) {
s_opts.point_weight = 0.0;
return BRLCAD_OK;
}
if (bu_opt_fastf_t(NULL, 1, (const char **)cstr, (void *)&s_opts.point_weight) < 0)
if (key == "interpolate") {
fastf_t parsed = BG_3D_SPSR_DEFAULT_POINT_WEIGHT;
if ((!val.empty() &&
bu_opt_fastf_t(NULL, 1, value, &parsed) < 0) ||
parsed < 0.0)
return BRLCAD_ERROR;
s_opts.point_weight = parsed;
return BRLCAD_OK;
}
if (key == std::string("samples_per_node")) {
if (!val.length()) {
s_opts.samples_per_node = 0.0;
return BRLCAD_OK;
}
if (bu_opt_fastf_t(NULL, 1, (const char **)cstr, (void *)&s_opts.samples_per_node) < 0)
if (key == "samples_per_node") {
fastf_t parsed = BG_3D_SPSR_DEFAULT_SAMPLES_PER_NODE;
if ((!val.empty() &&
bu_opt_fastf_t(NULL, 1, value, &parsed) < 0) ||
parsed <= 0.0)
return BRLCAD_ERROR;
s_opts.samples_per_node = parsed;
return BRLCAD_OK;
}
if (key == "refinement_passes") {
int parsed = BG_3D_SPSR_DEFAULT_REFINEMENT_PASSES;
if ((!val.empty() && bu_opt_int(NULL, 1, value, &parsed) < 0) ||
parsed < 0)
return BRLCAD_ERROR;
refinement_passes = parsed;
return BRLCAD_OK;
}
if (key == "max_time") {
int parsed = 600;
if ((!val.empty() && bu_opt_int(NULL, 1, value, &parsed) < 0) ||
parsed < 0)
return BRLCAD_ERROR;
max_time = parsed;
return BRLCAD_OK;
}
if (key == std::string("max_time")) {
if (!val.length()) {
max_time = 0;
return BRLCAD_OK;
}
if (bu_opt_int(NULL, 1, (const char **)cstr, (void *)&max_time) < 0)
return BRLCAD_ERROR;
}
// If it's not a SPSR setting directly, it may be for sampling
return sample_opts::set_var(key, val);
}
+35
View File
@@ -0,0 +1,35 @@
brlcad_addexec(facetize_worker_protocol_test "worker.cpp;../worker.cpp" "libbu;Threads::Threads" TEST)
brlcad_add_test(NAME facetize_worker_protocol COMMAND facetize_worker_protocol_test)
brlcad_addexec(facetize_validation_test "validation.cpp;../validation.cpp" "libwdb;librt;libbu" TEST)
brlcad_add_test(NAME facetize_validation COMMAND facetize_validation_test)
brlcad_addexec(facetize_recovery_test recovery.cpp "libged;libwdb;librt;libbu" TEST_USESDATA)
if(TARGET facetize_recovery_test)
add_dependencies(facetize_recovery_test ged_plugins facetize_process)
set(FACETIZE_RECOVERY_TMP "${CMAKE_CURRENT_BINARY_DIR}/facetize_recovery_tmp")
brlcad_add_test(
NAME facetize_recovery
COMMAND facetize_recovery_test "${FACETIZE_RECOVERY_TMP}"
)
set_tests_properties(
facetize_recovery
PROPERTIES
ENVIRONMENT "BU_DIR_CACHE=${FACETIZE_RECOVERY_TMP}/cache"
TIMEOUT 120
)
endif(TARGET facetize_recovery_test)
cmakefiles(
CMakeLists.txt
recovery.cpp
validation.cpp
worker.cpp
)
# Local Variables:
# tab-width: 8
# mode: cmake
# indent-tabs-mode: t
# End:
# ex: shiftwidth=2 tabstop=8
+398
View File
@@ -0,0 +1,398 @@
/* F A C E T I Z E _ R E C O V E R Y . C P P
* BRL-CAD
*
* Copyright (c) 2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** @file facetize/tests/recovery.cpp
*
* End-to-end fault injection tests for facetize worker write recovery.
*/
#include "common.h"
#include <filesystem>
#include <string>
#include <vector>
#include <string.h>
#include "bu/app.h"
#include "bu/env.h"
#include "bu/file.h"
#include "bu/log.h"
#include "bu/vls.h"
#include "raytrace.h"
#include "wdb.h"
#include "ged.h"
static const char FAULT_ENV[] = "LIBGED_FACETIZE_TEST_FAULT";
static const char FAULT_FILE_ENV[] = "LIBGED_FACETIZE_TEST_FAULT_FILE";
static const char TEST_OBJECT[] = "one.s";
static const char TEST_COMBINATION[] = "model.c";
static const char TEST_OUTPUT[] = "model.bot";
struct recovery_case {
const char *name;
const char *stage;
bool expect_success;
bool expect_replay;
bool expect_resubmit;
};
static int
capture_log(void *data, void *message)
{
if (data && message)
static_cast<std::string *>(data)->append(static_cast<const char *>(message));
return 0;
}
static int
create_input(const char *gfile)
{
(void)bu_file_delete(gfile);
struct db_i *dbip = db_create(gfile, BRLCAD_DB_FORMAT_LATEST);
if (!dbip)
return BRLCAD_ERROR;
struct rt_wdb *wdbp = wdb_dbopen(dbip, RT_WDB_TYPE_DB_DEFAULT);
if (!wdbp) {
db_close(dbip);
return BRLCAD_ERROR;
}
point_t centers[3] = {
{0.0, 0.0, 0.0},
{30.0, 0.0, 0.0},
{60.0, 0.0, 0.0}
};
const char *names[3] = {TEST_OBJECT, "two.s", "three.s"};
int ret = BRLCAD_OK;
for (size_t i = 0; i < 3; i++) {
if (mk_sph(wdbp, names[i], centers[i], 10.0) < 0) {
ret = BRLCAD_ERROR;
break;
}
}
if (ret == BRLCAD_OK) {
struct bu_list members;
BU_LIST_INIT(&members);
for (const char *name : names)
(void)mk_addmember(name, &members, NULL, WMOP_UNION);
if (mk_comb(wdbp, TEST_COMBINATION, &members, 0, NULL, NULL, NULL,
0, 0, 0, 0, 0, 0, 0) < 0)
ret = BRLCAD_ERROR;
}
wdb_close(wdbp);
return ret;
}
static int
run_facetize(const char *gfile, int jobs, std::string &output)
{
struct ged *gedp = ged_open("db", gfile, 1);
if (!gedp)
return BRLCAD_ERROR;
std::string log_output;
struct bu_hook_list saved_hooks = BU_HOOK_LIST_INIT_ZERO;
bu_log_hook_save_all(&saved_hooks);
bu_log_hook_delete_all();
bu_log_add_hook(capture_log, &log_output);
std::string job_count = std::to_string(jobs);
const char *argv[] = {
"facetize", "-v", "--jobs", job_count.c_str(), "--methods", "NMG",
TEST_COMBINATION, TEST_OUTPUT, NULL
};
int ret = ged_exec(gedp, 8, argv);
output = bu_vls_cstr(gedp->ged_result_str);
ged_close(gedp);
bu_log_hook_delete_all();
bu_log_hook_restore_all(&saved_hooks);
bu_hook_delete_all(&saved_hooks);
output.append(log_output);
return ret;
}
static bool
object_exists(const char *gfile, const char *object_name)
{
struct db_i *dbip = db_open(gfile, DB_OPEN_READONLY);
if (!dbip)
return false;
bool exists = db_dirbuild(dbip) >= 0 &&
db_lookup(dbip, object_name, LOOKUP_QUIET) != RT_DIR_NULL;
db_close(dbip);
return exists;
}
static bool
object_external(const char *gfile, const char *object_name,
std::vector<unsigned char> &bytes)
{
bytes.clear();
struct db_i *dbip = db_open(gfile, DB_OPEN_READONLY);
if (!dbip)
return false;
if (db_dirbuild(dbip) < 0) {
db_close(dbip);
return false;
}
struct directory *dp = db_lookup(dbip, object_name, LOOKUP_QUIET);
struct bu_external external;
if (!dp || db_get_external(&external, dp, dbip) < 0) {
db_close(dbip);
return false;
}
const unsigned char *data =
static_cast<const unsigned char *>(external.ext_buf);
bytes.assign(data, data + external.ext_nbytes);
bu_free_external(&external);
db_close(dbip);
return true;
}
static bool
outputs_match(const char *control_file, const char *test_file)
{
std::vector<unsigned char> control;
std::vector<unsigned char> test;
return object_external(control_file, TEST_OUTPUT, control) &&
object_external(test_file, TEST_OUTPUT, test) && control == test;
}
static bool
has_temporary_write_file(const std::filesystem::path &cache_dir)
{
std::error_code error;
std::filesystem::recursive_directory_iterator entry(cache_dir, error);
std::filesystem::recursive_directory_iterator end;
while (!error && entry != end) {
if (entry->is_regular_file(error)) {
std::string name = entry->path().filename().string();
if (name.find(".facetize_worker_") != std::string::npos ||
entry->path().extension() == ".bak" ||
name.find(".io_probe") != std::string::npos)
return true;
}
entry.increment(error);
}
return false;
}
static bool
reset_cache(const std::filesystem::path &cache_dir)
{
std::error_code error;
std::filesystem::remove_all(cache_dir, error);
if (error) {
bu_log("[facetize_recovery] unable to remove %s: %s\n",
cache_dir.string().c_str(), error.message().c_str());
return false;
}
std::filesystem::create_directories(cache_dir, error);
if (error) {
bu_log("[facetize_recovery] unable to create %s: %s\n",
cache_dir.string().c_str(), error.message().c_str());
return false;
}
return true;
}
static bool
cache_is_empty(const std::filesystem::path &cache_dir)
{
std::error_code error;
bool empty = std::filesystem::is_empty(cache_dir, error);
if (error)
bu_log("[facetize_recovery] unable to inspect %s: %s\n",
cache_dir.string().c_str(), error.message().c_str());
return empty && !error;
}
static int
run_recovery_case(const recovery_case &test_case,
const std::filesystem::path &test_dir,
const std::filesystem::path &cache_dir, const char *control_file)
{
std::filesystem::path gfile = test_dir /
(std::string(test_case.name) + ".g");
std::filesystem::path claim_file = test_dir /
(std::string(test_case.name) + ".fault");
std::string selector = std::string(test_case.stage) + ":" + TEST_OBJECT;
bu_log("[facetize_recovery] %s: starting fault %s\n",
test_case.name, selector.c_str());
(void)bu_file_delete(claim_file.string().c_str());
if (create_input(gfile.string().c_str()) != BRLCAD_OK) {
bu_log("[facetize_recovery] %s: unable to create input\n",
test_case.name);
return BRLCAD_ERROR;
}
(void)bu_setenv(FAULT_ENV, selector.c_str(), 1);
(void)bu_setenv(FAULT_FILE_ENV, claim_file.string().c_str(), 1);
std::string output;
int ret = run_facetize(gfile.string().c_str(), 2, output);
(void)bu_setenv(FAULT_ENV, "", 1);
(void)bu_setenv(FAULT_FILE_ENV, "", 1);
bu_log("[facetize_recovery] %s: facetize returned %d\n",
test_case.name, ret);
bool passed = true;
if (!bu_file_exists(claim_file.string().c_str(), NULL)) {
bu_log("[facetize_recovery] %s: fault did not trigger\n",
test_case.name);
passed = false;
}
if ((ret == BRLCAD_OK) != test_case.expect_success) {
bu_log("[facetize_recovery] %s: command result %d; expected %s\n",
test_case.name, ret,
test_case.expect_success ? "success" : "failure");
passed = false;
}
if (test_case.expect_success) {
if (!cache_is_empty(cache_dir)) {
bu_log("[facetize_recovery] %s: workspace was not cleaned\n",
test_case.name);
passed = false;
}
if (!outputs_match(control_file, gfile.string().c_str())) {
bu_log("[facetize_recovery] %s: result differs from serial control\n",
test_case.name);
passed = false;
}
} else if (object_exists(gfile.string().c_str(), TEST_OUTPUT)) {
bu_log("[facetize_recovery] %s: failed command left an output object\n",
test_case.name);
passed = false;
}
bool replay_reported = output.find("retrying tessellation") !=
std::string::npos;
if (replay_reported != test_case.expect_replay) {
bu_log("[facetize_recovery] %s: replay reporting %s; expected %s\n",
test_case.name, replay_reported ? "present" : "absent",
test_case.expect_replay ? "present" : "absent");
passed = false;
}
bool resubmit_reported = output.find("resubmitted staged tessellation") !=
std::string::npos;
if (resubmit_reported != test_case.expect_resubmit) {
bu_log("[facetize_recovery] %s: resubmission reporting %s; expected %s\n",
test_case.name, resubmit_reported ? "present" : "absent",
test_case.expect_resubmit ? "present" : "absent");
passed = false;
}
if (has_temporary_write_file(cache_dir)) {
bu_log("[facetize_recovery] %s: temporary write file was not cleaned\n",
test_case.name);
passed = false;
}
if (!passed)
bu_log("[facetize_recovery] %s: captured command output:\n%s\n",
test_case.name, output.empty() ? "(none)" : output.c_str());
bu_log("[facetize_recovery] %s: %s\n", test_case.name,
passed ? "PASS" : "FAIL");
return passed ? BRLCAD_OK : BRLCAD_ERROR;
}
int
main(int argc, const char **argv)
{
bu_setprogname(argv[0]);
if (argc != 2) {
bu_log("Usage: %s test-directory\n", argv[0]);
return 1;
}
std::filesystem::path test_dir(argv[1]);
std::filesystem::path cache_dir = test_dir / "cache";
std::error_code error;
std::filesystem::remove_all(test_dir, error);
if (error) {
bu_log("[facetize_recovery] unable to clear test directory\n");
return 1;
}
if (!std::filesystem::create_directories(cache_dir, error) || error) {
bu_log("[facetize_recovery] unable to create test directory\n");
return 1;
}
std::filesystem::path control_file = test_dir / "control.g";
std::string control_output;
if (create_input(control_file.string().c_str()) != BRLCAD_OK ||
run_facetize(control_file.string().c_str(), 1, control_output) !=
BRLCAD_OK) {
bu_log("[facetize_recovery] unable to create serial control\n%s\n",
control_output.c_str());
return 1;
}
const recovery_case cases[] = {
{"tess_before_ready", "tess-before-ready", false, false, false},
{"stage_before_done", "stage-before-done", false, false, false},
{"writer_before_proceed", "writer-before-proceed", true, false, true},
{"writer_before_done", "writer-before-done", true, true, false}
};
int ret = 0;
if (!cache_is_empty(cache_dir)) {
bu_log("[facetize_recovery] serial control workspace was not cleaned\n");
ret = 1;
}
for (const recovery_case &test_case : cases) {
if (!reset_cache(cache_dir)) {
bu_log("[facetize_recovery] %s: unable to reset cache directory\n",
test_case.name);
ret = 1;
continue;
}
if (run_recovery_case(test_case, test_dir, cache_dir,
control_file.string().c_str()) != BRLCAD_OK)
ret = 1;
}
if (!ret)
std::filesystem::remove_all(test_dir, error);
return ret;
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
+154
View File
@@ -0,0 +1,154 @@
/* F A C E T I Z E _ V A L I D A T I O N . C P P
* BRL-CAD
*
* Copyright (c) 2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** @file facetize/tests/validation.cpp
*
* Exercise finite and unbounded CSG reference sampling.
*/
#include "common.h"
#include <cmath>
#include <cstdio>
#include "bu/app.h"
#include "bu/log.h"
#include "raytrace.h"
#include "wdb.h"
#include "../validation.h"
static int failures = 0;
static int
count_log(void *data, void *UNUSED(message))
{
if (data)
(*static_cast<int *>(data))++;
return 0;
}
static void
expect(bool condition, const char *message)
{
if (condition)
return;
std::fprintf(stderr, "FAIL: %s\n", message);
failures++;
}
int
main(int UNUSED(argc), const char **argv)
{
bu_setprogname(argv[0]);
struct db_i *dbip = db_create_inmem();
expect(dbip != NULL, "create in-memory database");
if (!dbip)
return 1;
struct rt_wdb *wdbp = wdb_dbopen(dbip, RT_WDB_TYPE_DB_INMEM);
expect(wdbp != NULL, "open in-memory database for writing");
if (!wdbp) {
db_close(dbip);
return 1;
}
point_t center = VINIT_ZERO;
vect_t normal = {1.0, 0.0, 0.0};
expect(mk_sph(wdbp, "sphere.s", center, 10.0) == 0,
"create bounded test solid");
expect(mk_half(wdbp, "half.s", normal, 0.0) == 0,
"create unbounded test solid");
struct bu_list members;
BU_LIST_INIT(&members);
expect(mk_addmember("sphere.s", &members, NULL, WMOP_UNION) != NULL,
"add bounded member");
expect(mk_addmember("half.s", &members, NULL, WMOP_INTERSECT) != NULL,
"add halfspace clipping member");
expect(mk_comb(wdbp, "clipped.r", &members, 1, NULL, NULL, NULL,
0, 0, 0, 0, 0, 0, 0) == 0, "create clipped test region");
struct bu_list empty_members;
BU_LIST_INIT(&empty_members);
expect(mk_comb(wdbp, "empty.c", &empty_members, 0, NULL, NULL, NULL,
0, 0, 0, 0, 0, 0, 0) == 0, "create empty test combination");
double surface_area = -1.0;
double volume = -1.0;
int log_count = 0;
struct bu_hook_list saved_hooks = BU_HOOK_LIST_INIT_ZERO;
bu_log_hook_save_all(&saved_hooks);
bu_log_hook_delete_all();
bu_log_add_hook(count_log, &log_count);
long crossings = facetize_csg_metrics(dbip, "half.s", &surface_area,
&volume);
expect(crossings < 0,
"unbounded halfspace is not assigned Crofton metrics");
crossings = facetize_csg_metrics(dbip, "empty.c", &surface_area,
&volume);
int bound_log_count = log_count;
bu_log("facetize validation hook restoration probe\n");
bu_log_hook_delete_all();
bu_log_hook_restore_all(&saved_hooks);
bu_hook_delete_all(&saved_hooks);
expect(crossings < 0,
"empty combination is not assigned Crofton metrics");
expect(bound_log_count == 0,
"expected bounding failure diagnostics are suppressed");
expect(log_count == 1,
"bounding failure log suppression restores existing hooks");
crossings = facetize_csg_metrics(dbip, "clipped.r", &surface_area,
&volume);
expect(crossings > 0,
"bounded geometry clipped by a halfspace is sampled");
expect(std::isfinite(surface_area) && surface_area > 0.0,
"clipped geometry has finite positive surface area");
expect(std::isfinite(volume) && volume > 0.0,
"clipped geometry has finite positive volume");
db_close(dbip);
return failures ? 1 : 0;
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
+692
View File
@@ -0,0 +1,692 @@
/* F A C E T I Z E _ W O R K E R . C P P
* BRL-CAD
*
* Copyright (c) 2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** @file facetize/tests/worker.cpp
*
* Exercise facetize worker protocol framing and state parsing.
*/
#include "common.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <string>
#include <vector>
#include <errno.h>
#if defined(HAVE_PTHREAD_H) && defined(HAVE_SIGNAL_H) && defined(HAVE_UNISTD_H)
# include <pthread.h>
# include <unistd.h>
#endif
#include "bu/app.h"
#include "bu/interrupt.h"
#include "../worker.h"
static int failures = 0;
static const double METRIC_COMPARISON_TOLERANCE = 1.0e-12;
static const size_t PROTOCOL_OVERSIZED_FIELD_LENGTH = 1024u * 1024u + 1u;
static void
expect(bool condition, const char *message)
{
if (condition)
return;
std::fprintf(stderr, "FAIL: %s\n", message);
failures++;
}
static FILE *
stream_with_contents(const std::string &contents)
{
FILE *stream = tmpfile();
if (!stream)
return NULL;
if (fwrite(contents.data(), 1, contents.size(), stream) != contents.size() ||
fflush(stream) != 0 || fseek(stream, 0, SEEK_SET) != 0) {
fclose(stream);
return NULL;
}
return stream;
}
static std::string
read_stream(FILE *stream)
{
std::string contents;
char buffer[64];
if (fflush(stream) != 0 || fseek(stream, 0, SEEK_SET) != 0)
return contents;
size_t bytes_read = 0;
while ((bytes_read = fread(buffer, 1, sizeof(buffer), stream)) > 0)
contents.append(buffer, bytes_read);
return contents;
}
static void
test_request_round_trip()
{
FILE *requests = tmpfile();
expect(requests != NULL, "create request stream");
if (!requests)
return;
FacetizeWorkerRequest request;
request.operation = FacetizeWorkerOperation::TessellatePrimitive;
request.input_names.push_back("assembly/part\nwith spaces");
request.primitive.methods.push_back("NMG");
request.primitive.method_options.push_back("NMG max_time=30\ntol=0.01");
request.primitive.cache_directory = "cache path\nwith spaces";
request.primitive.point_limit = 12345;
FacetizeWorkerClient client;
client.reset(requests);
expect(client.send_request(request), "client sends a typed primitive request");
FacetizeWorkerRequest region_request;
region_request.operation = FacetizeWorkerOperation::EvaluateRegion;
region_request.input_names.push_back("assembly.r");
region_request.region.no_empty = true;
region_request.region.no_fixup = true;
region_request.region.tolerate_failures = true;
expect(client.send_request(region_request), "client sends a typed region request");
FacetizeWorkerRequest validation_request;
validation_request.operation = FacetizeWorkerOperation::ValidateCsg;
validation_request.input_names.push_back("assembly.r");
expect(client.send_request(validation_request),
"client sends a typed validation request");
FacetizeWorkerRequest nmg_request;
nmg_request.operation = FacetizeWorkerOperation::NmgBooleanToNmg;
nmg_request.input_names.push_back("first.r");
nmg_request.input_names.push_back("second.r");
nmg_request.output_name = "combined.nmg";
expect(client.send_request(nmg_request),
"client sends an NMG Boolean request");
expect(fflush(requests) == 0 && fseek(requests, 0, SEEK_SET) == 0,
"rewind request stream");
FacetizeWorkerServer server(requests, NULL);
FacetizeWorkerRequest received;
expect(server.receive_request(received) == FacetizeWorkerReadResult::Request,
"server accepts a complete request");
expect(received.operation == request.operation,
"request framing preserves the operation");
expect(received.input_names == request.input_names,
"request framing preserves object name bytes");
expect(received.primitive.methods == request.primitive.methods &&
received.primitive.method_options == request.primitive.method_options,
"request framing preserves tessellation settings");
expect(received.primitive.cache_directory ==
request.primitive.cache_directory &&
received.primitive.point_limit == request.primitive.point_limit,
"request framing preserves cache and point settings");
expect(server.receive_request(received) == FacetizeWorkerReadResult::Request,
"server accepts a region request");
expect(received.operation == FacetizeWorkerOperation::EvaluateRegion &&
received.input_names == region_request.input_names &&
received.region.no_empty && received.region.no_fixup &&
received.region.tolerate_failures,
"request framing preserves region settings");
expect(server.receive_request(received) == FacetizeWorkerReadResult::Request,
"server accepts a validation request");
expect(received.operation == FacetizeWorkerOperation::ValidateCsg &&
received.input_names == validation_request.input_names &&
received.primitive.empty() && received.region.empty(),
"validation request has no unrelated settings");
expect(server.receive_request(received) == FacetizeWorkerReadResult::Request,
"server accepts an NMG Boolean request");
expect(received.operation == FacetizeWorkerOperation::NmgBooleanToNmg &&
received.input_names == nmg_request.input_names &&
received.output_name == nmg_request.output_name,
"request framing preserves NMG Boolean inputs and output");
expect(server.receive_request(received) == FacetizeWorkerReadResult::End,
"clean request EOF ends the worker loop");
fclose(requests);
client.reset(NULL);
expect(!client.send_request(request),
"client rejects a missing request stream");
FILE *invalid_stream = tmpfile();
expect(invalid_stream != NULL, "create invalid request stream");
if (invalid_stream) {
client.reset(invalid_stream);
FacetizeWorkerRequest invalid;
expect(!client.send_request(invalid),
"client rejects a request without an input");
invalid.input_names.push_back("");
expect(!client.send_request(invalid),
"client rejects an empty input name");
invalid.input_names.front() = "part";
invalid.primitive.point_limit = -1;
expect(!client.send_request(invalid),
"client rejects a negative point limit");
invalid.primitive.point_limit = 0;
invalid.region.no_empty = true;
expect(!client.send_request(invalid),
"client rejects region settings on a primitive request");
invalid.operation = FacetizeWorkerOperation::ValidateCsg;
invalid.region = FacetizeRegionSettings();
invalid.primitive.methods.push_back("NMG");
expect(!client.send_request(invalid),
"client rejects tessellation settings on a validation request");
invalid.operation = FacetizeWorkerOperation::TessellatePrimitive;
invalid.primitive.methods.clear();
invalid.input_names.front().assign(PROTOCOL_OVERSIZED_FIELD_LENGTH, 'x');
expect(!client.send_request(invalid),
"client rejects an oversized field");
expect(ftell(invalid_stream) == 0,
"invalid requests do not partially modify the request stream");
invalid.input_names.front() = "part";
invalid.input_names.push_back("other");
expect(!client.send_request(invalid),
"client rejects multiple primitive inputs");
fclose(invalid_stream);
}
}
static void
test_malformed_requests()
{
const char *invalid_requests[] = {
"NOT_A_REQUEST 3 1 1 0 0 0 0 0 0\n",
"FACETIZE_REQUEST 2 1 1 0 0 0 0 0 0\n",
"FACETIZE_REQUEST 3 99 1 0 0 0 0 0 0\n",
"FACETIZE_REQUEST 3 1 0 0 0 0 0 0 0\n",
"FACETIZE_REQUEST 3 1 1 0 0 0 2 0 0\n",
"FACETIZE_REQUEST 3 1 1 0 0 0 0 0 0 trailing\n",
"FACETIZE_REQUEST 3 1 1 0 0 0 0 0 0\n0\n\n0\n\n5\npart\n",
"FACETIZE_REQUEST 3 1 1 0 0 0 0 0 0\n0\n\n0\n\n4\npart!"
};
for (const char *invalid_request : invalid_requests) {
FILE *stream = stream_with_contents(invalid_request);
expect(stream != NULL, "create malformed request stream");
if (!stream)
continue;
FacetizeWorkerServer server(stream, NULL);
FacetizeWorkerRequest decoded_request;
expect(server.receive_request(decoded_request) == FacetizeWorkerReadResult::Error,
"server rejects malformed request framing");
expect(decoded_request.input_names.empty(),
"malformed request does not expose partial inputs");
fclose(stream);
}
const size_t unterminated_header_size = 128;
std::string long_header(unterminated_header_size, 'x');
FILE *stream = stream_with_contents(long_header);
expect(stream != NULL, "create overlong header stream");
if (stream) {
FacetizeWorkerServer server(stream, NULL);
FacetizeWorkerRequest request;
expect(server.receive_request(request) == FacetizeWorkerReadResult::Error,
"server rejects a header without a terminator");
fclose(stream);
}
}
static void
test_commit_round_trip()
{
FILE *requests = tmpfile();
expect(requests != NULL, "create commit stream");
if (!requests)
return;
const char result_file[] = "cache path/worker\nresult.g";
const char object_name[] = "assembly/part with spaces";
const size_t payload_size = 1234567;
FacetizeWorkerClient client;
client.reset(requests);
expect(client.send_commit(result_file, object_name, payload_size),
"client sends a framed commit request");
expect(fflush(requests) == 0 && fseek(requests, 0, SEEK_SET) == 0,
"rewind commit stream");
FacetizeWorkerServer server(requests, NULL);
FacetizeCommitRequest request;
expect(server.receive_commit(request) == FacetizeWorkerReadResult::Request,
"server accepts a complete commit request");
expect(request.result_file == result_file,
"commit framing preserves result path bytes");
expect(request.object_name == object_name,
"commit framing preserves object name bytes");
expect(request.payload_size == payload_size,
"commit framing preserves the payload size");
expect(server.receive_commit(request) == FacetizeWorkerReadResult::End,
"clean commit EOF ends the writer loop");
fclose(requests);
client.reset(NULL);
expect(!client.send_commit("result.g", "part", 1),
"client rejects a commit without a request stream");
FILE *invalid_requests = tmpfile();
expect(invalid_requests != NULL, "create invalid commit stream");
if (invalid_requests) {
client.reset(invalid_requests);
expect(!client.send_commit(NULL, "part", 1),
"client rejects a null result path");
expect(!client.send_commit("", "part", 1),
"client rejects an empty result path");
expect(!client.send_commit("result.g", NULL, 1),
"client rejects a null object name");
expect(!client.send_commit("result.g", "", 1),
"client rejects an empty object name");
fclose(invalid_requests);
}
const char *malformed_commits[] = {
"NOT_A_COMMIT 8 4 12\nresult.g\npart\n",
"FACETIZE_COMMIT 0 4 12\n\npart\n",
"FACETIZE_COMMIT 8 4 12 trailing\nresult.g\npart\n",
"FACETIZE_COMMIT 9 4 12\nresult.g\npart\n",
"FACETIZE_COMMIT 8 5 12\nresult.g\npart\n",
"FACETIZE_COMMIT 8 4 12\nresult.g!part\n"
};
for (const char *commit : malformed_commits) {
FILE *malformed = stream_with_contents(commit);
expect(malformed != NULL, "create malformed commit stream");
if (!malformed)
continue;
FacetizeWorkerServer malformed_server(malformed, NULL);
expect(malformed_server.receive_commit(request) ==
FacetizeWorkerReadResult::Error,
"server rejects malformed commit framing");
expect(request.result_file.empty() && request.object_name.empty(),
"malformed commit does not expose partial fields");
fclose(malformed);
}
}
static void
test_write_handshake()
{
FILE *requests = tmpfile();
FILE *responses = tmpfile();
expect(requests != NULL && responses != NULL, "create handshake streams");
if (!requests || !responses) {
if (requests) fclose(requests);
if (responses) fclose(responses);
return;
}
FacetizeWorkerClient client;
client.reset(requests);
expect(client.send_write_proceed(), "client sends write acknowledgement");
expect(fflush(requests) == 0 && fseek(requests, 0, SEEK_SET) == 0,
"rewind write acknowledgement");
FacetizeWorkerServer server(requests, responses);
expect(server.receive_write_proceed(), "server accepts exact write acknowledgement");
const size_t announced_payload_size = 987654;
const size_t announced_resident_size = 456789;
expect(server.send_write_ready(announced_payload_size,
announced_resident_size), "server sends write size");
const int tolerated_failures = 3;
expect(server.send_region_write_ready(announced_payload_size,
announced_resident_size, tolerated_failures),
"server sends region write size and tolerated-failure count");
expect(server.send_write_started(), "server acknowledges write start");
expect(server.send_write_result(BRLCAD_OK, announced_resident_size),
"server sends write completion");
std::string output = read_stream(responses);
FacetizeWorkerStatus status;
std::vector<std::string> diagnostics;
const size_t fragment_size = 3;
for (size_t offset = 0; offset < output.size();) {
const size_t chunk_size = std::min(fragment_size, output.size() - offset);
client.consume_output(output.data() + offset, chunk_size, status, diagnostics);
offset += chunk_size;
}
expect(status.write_ready, "client recognizes fragmented write-ready message");
expect(status.payload_size == announced_payload_size,
"client preserves announced write size");
expect(status.resident_size == announced_resident_size,
"client preserves worker resident memory");
expect(status.tolerated_failures == tolerated_failures,
"client preserves the region's tolerated-failure count");
expect(status.write_started,
"client recognizes fragmented write-start acknowledgement");
expect(status.write_done, "client recognizes fragmented write completion");
expect(status.result_received && status.result == BRLCAD_OK,
"write completion result is retained");
expect(diagnostics.empty(), "valid protocol output emits no diagnostics");
fclose(requests);
fclose(responses);
client.reset(NULL);
FILE *failure_response = tmpfile();
expect(failure_response != NULL, "create tessellation result stream");
if (failure_response) {
FacetizeWorkerServer failure_server(NULL, failure_response);
expect(failure_server.send_tessellation_result(BRLCAD_ERROR,
announced_resident_size),
"server sends pre-write tessellation failure");
std::string failure_output = read_stream(failure_response);
FacetizeWorkerStatus failure_status;
diagnostics.clear();
client.consume_output(failure_output.data(), failure_output.size(),
failure_status, diagnostics);
expect(failure_status.result_received &&
failure_status.result == BRLCAD_ERROR && !failure_status.write_done,
"client distinguishes pre-write failure from write completion");
expect(failure_status.resident_size == announced_resident_size,
"pre-write result reports worker resident memory");
expect(diagnostics.empty(), "valid tessellation failure emits no diagnostics");
fclose(failure_response);
}
FILE *bad_ack = stream_with_contents("FACETIZE_WRITE_PROCEED trailing\n");
expect(bad_ack != NULL, "create invalid acknowledgement stream");
if (bad_ack) {
FacetizeWorkerServer bad_server(bad_ack, NULL);
expect(!bad_server.receive_write_proceed(),
"server rejects non-exact write acknowledgement");
fclose(bad_ack);
}
}
static void
test_broken_pipe(bool pending_sigpipe)
{
#if defined(HAVE_PTHREAD_H) && defined(HAVE_SIGNAL_H) && defined(HAVE_UNISTD_H) && defined(SIGPIPE)
int descriptors[2];
int ret = pipe(descriptors);
expect(ret == 0, "create pipe for worker write failure");
if (ret != 0)
return;
close(descriptors[0]);
FILE *stream = fdopen(descriptors[1], "w");
expect(stream != NULL, "open worker pipe stream");
if (!stream) {
close(descriptors[1]);
return;
}
if (setvbuf(stream, NULL, _IONBF, 0) != 0) {
expect(false, "disable buffering for worker pipe");
fclose(stream);
return;
}
sigset_t sigpipe_set, original_mask;
sigemptyset(&sigpipe_set);
sigaddset(&sigpipe_set, SIGPIPE);
ret = pthread_sigmask(pending_sigpipe ? SIG_BLOCK : SIG_UNBLOCK,
&sigpipe_set, &original_mask);
expect(ret == 0, "set initial SIGPIPE mask");
if (ret != 0) {
fclose(stream);
return;
}
struct sigaction action = {}, original_action;
sigemptyset(&action.sa_mask);
action.sa_handler = SIG_DFL;
ret = sigaction(SIGPIPE, &action, &original_action);
expect(ret == 0, "use default SIGPIPE disposition");
if (ret != 0) {
pthread_sigmask(SIG_SETMASK, &original_mask, NULL);
fclose(stream);
return;
}
if (pending_sigpipe)
expect(raise(SIGPIPE) == 0, "queue a pre-existing SIGPIPE");
FacetizeWorkerClient client;
client.reset(stream);
errno = 0;
expect(!client.send_write_proceed(), "worker write detects a closed pipe");
expect(errno == EPIPE, "worker write preserves the broken-pipe error");
sigset_t current_mask, pending_signals;
expect(pthread_sigmask(SIG_BLOCK, NULL, &current_mask) == 0 &&
sigismember(&current_mask, SIGPIPE) == (pending_sigpipe ? 1 : 0),
"worker write restores the SIGPIPE mask");
ret = sigpending(&pending_signals);
expect(ret == 0 &&
sigismember(&pending_signals, SIGPIPE) == (pending_sigpipe ? 1 : 0),
pending_sigpipe ? "worker write preserves pre-existing SIGPIPE" :
"worker write consumes generated SIGPIPE");
/* Some systems queue the raised and write-generated signals separately. */
while (ret == 0 && sigismember(&pending_signals, SIGPIPE) == 1) {
int signal_number = 0;
ret = sigwait(&sigpipe_set, &signal_number);
expect(ret == 0, "consume test SIGPIPE before restoring its mask");
if (ret != 0)
break;
ret = sigpending(&pending_signals);
}
expect(sigaction(SIGPIPE, &original_action, NULL) == 0,
"restore original SIGPIPE disposition");
expect(pthread_sigmask(SIG_SETMASK, &original_mask, NULL) == 0,
"restore original signal mask");
fclose(stream);
#else
(void)pending_sigpipe;
#endif
}
static void
test_csg_result()
{
FILE *responses = tmpfile();
expect(responses != NULL, "create CSG result stream");
if (!responses)
return;
const long crossings = 12345;
const double surface_area = 12.25;
const double volume = 42.5;
const size_t resident_size = 456789;
FacetizeWorkerServer server(NULL, responses);
expect(server.send_csg_result(BRLCAD_OK, crossings, surface_area, volume,
resident_size), "server sends CSG validation metrics");
std::string output = read_stream(responses);
FacetizeWorkerClient client;
FacetizeWorkerStatus status;
std::vector<std::string> diagnostics;
const size_t fragment_size = 3;
for (size_t offset = 0; offset < output.size();) {
const size_t chunk_size = std::min(fragment_size, output.size() - offset);
client.consume_output(output.data() + offset, chunk_size, status,
diagnostics);
offset += chunk_size;
}
expect(status.result_received && status.result == BRLCAD_OK,
"client recognizes a fragmented CSG result");
expect(status.csg_crossings == crossings,
"client preserves the CSG crossing count");
expect(std::fabs(status.csg_surface_area - surface_area) <
METRIC_COMPARISON_TOLERANCE,
"client preserves CSG surface area");
expect(std::fabs(status.csg_volume - volume) < METRIC_COMPARISON_TOLERANCE,
"client preserves CSG volume");
expect(status.resident_size == resident_size,
"CSG result reports worker resident memory");
expect(!status.write_ready && !status.write_started && !status.write_done,
"CSG result does not alter writer state");
expect(diagnostics.empty(), "valid CSG result emits no diagnostics");
fclose(responses);
FacetizeWorkerServer null_server(NULL, NULL);
expect(!null_server.send_csg_result(BRLCAD_OK, crossings, surface_area,
volume, resident_size),
"server cannot send CSG metrics without a response stream");
}
static void
test_client_diagnostics_and_reset()
{
FacetizeWorkerClient client;
FacetizeWorkerStatus status;
std::vector<std::string> diagnostics;
const char malformed_output[] =
"ordinary diagnostic\nFACETIZE_RESULT 0 trailing\n"
"FACETIZE_WRITE_STARTED trailing\n"
"FACETIZE_CSG_RESULT 0 10 1.0\n";
client.consume_output(malformed_output, sizeof(malformed_output) - 1,
status, diagnostics);
expect(!status.result_received, "malformed result is not accepted as protocol");
expect(diagnostics.size() == 4, "ordinary and malformed lines remain diagnostics");
diagnostics.clear();
const char partial_frame[] = "FACETIZE_WRITE_RE";
client.consume_output(partial_frame, sizeof(partial_frame) - 1,
status, diagnostics);
client.reset(NULL);
const char post_reset[] = "ADY 42\n";
client.consume_output(post_reset, sizeof(post_reset) - 1,
status, diagnostics);
expect(!status.write_ready, "reset discards a previous channel's partial frame");
expect(diagnostics.size() == 1 && diagnostics[0] == "ADY 42",
"post-reset bytes are reported independently");
FacetizeWorkerServer null_server(NULL, NULL);
FacetizeWorkerRequest request;
FacetizeCommitRequest commit_request;
expect(null_server.receive_request(request) == FacetizeWorkerReadResult::Error,
"server rejects a missing request stream");
expect(null_server.receive_commit(commit_request) ==
FacetizeWorkerReadResult::Error,
"writer rejects a missing request stream");
expect(!null_server.receive_write_proceed(),
"server cannot receive acknowledgement without a stream");
expect(!null_server.send_write_ready(1, 1),
"server cannot announce a write without a response stream");
expect(!null_server.send_write_started(),
"server cannot acknowledge a write without a response stream");
expect(!null_server.send_tessellation_result(BRLCAD_OK, 1),
"server cannot send a result without a response stream");
expect(!null_server.send_write_result(BRLCAD_OK, 1),
"server cannot send write completion without a response stream");
}
static void
test_worker_policy()
{
const size_t mib = (size_t)1024 * 1024;
const size_t gib = (size_t)1024 * mib;
FacetizeWorkerPolicy automatic(0, 20, 16, 3 * gib, 2560 * mib);
expect(automatic.worker_count() == 2,
"automatic policy conservatively permits two workers");
expect(automatic.threads_per_worker() == 8,
"automatic policy divides CPUs between workers");
expect(automatic.can_dispatch(1, 2 * gib, 512 * mib),
"automatic policy admits work while its memory reserve is intact");
expect(!automatic.can_dispatch(1, 1536 * mib, 512 * mib),
"automatic policy preserves system memory headroom");
expect(!automatic.can_dispatch(1, 2 * gib, 1280 * mib),
"observed worker memory increases the next-job reserve");
expect(!automatic.can_dispatch(1, 0, 0),
"missing current memory data pauses additional dispatches");
expect(automatic.can_dispatch(0, 0, 0),
"one job may make progress when current memory data is missing");
FacetizeWorkerPolicy serial(1, 20, 16, 3 * gib, 2560 * mib);
expect(serial.worker_count() == 1 && serial.threads_per_worker() == 16,
"one requested worker retains the full CPU budget");
expect(!serial.can_dispatch(1, 2 * gib, 0),
"serial policy does not admit a second active task");
FacetizeWorkerPolicy requested(8, 3, 12, 3 * gib, 2560 * mib);
expect(requested.worker_count() == 3,
"requested policy is capped by available work");
expect(requested.threads_per_worker() == 4,
"requested policy divides the CPU budget by effective workers");
FacetizeWorkerPolicy unknown_memory(0, 20, 16, 0, 0);
expect(unknown_memory.worker_count() == 1,
"unknown memory availability falls back to one worker");
FacetizeWorkerPolicy low_memory(4, 20, 16, 3 * gib, gib);
expect(low_memory.worker_count() == 1,
"low memory availability falls back to one worker");
}
int
main(int UNUSED(argc), const char **argv)
{
bu_setprogname(argv[0]);
test_request_round_trip();
test_malformed_requests();
test_commit_round_trip();
test_write_handshake();
test_broken_pipe(false);
test_broken_pipe(true);
test_csg_result();
test_client_diagnostics_and_reset();
test_worker_policy();
if (failures)
std::fprintf(stderr, "%d facetize worker protocol test(s) failed\n", failures);
return failures ? 1 : 0;
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
+88
View File
@@ -0,0 +1,88 @@
/* T R A N S F E R . C P P
* BRL-CAD
*
* Copyright (c) 2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library 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 this file; see the file named COPYING for more
* information.
*/
#include "common.h"
#include "raytrace.h"
#include "./transfer.h"
#include "./worker.h"
int
facetize_transfer_staged_object(struct db_i *target_dbip,
const char *result_file, const char *object_name,
int expected_object_type)
{
if (!target_dbip || !result_file || !object_name ||
expected_object_type <= ID_NULL ||
expected_object_type > ID_MAXIMUM)
return BRLCAD_ERROR;
struct db_i *result_dbip = db_open(result_file, DB_OPEN_READONLY);
if (!result_dbip)
return BRLCAD_ERROR;
if (db_dirbuild(result_dbip) < 0) {
db_close(result_dbip);
return BRLCAD_ERROR;
}
struct directory *result_dp = db_lookup(result_dbip,
FACETIZE_WORKER_RESULT_OBJECT, LOOKUP_QUIET);
struct rt_db_internal intern;
RT_DB_INTERNAL_INIT(&intern);
if (!result_dp || result_dp->d_major_type != DB5_MAJORTYPE_BRLCAD ||
result_dp->d_minor_type != expected_object_type ||
rt_db_get_internal(&intern, result_dp, result_dbip, NULL) < 0 ||
intern.idb_type != expected_object_type) {
if (intern.idb_ptr)
rt_db_free_internal(&intern);
db_close(result_dbip);
return BRLCAD_ERROR;
}
db_close(result_dbip);
struct directory *old_dp = db_lookup(target_dbip, object_name,
LOOKUP_QUIET);
if (old_dp && (db_delete(target_dbip, old_dp) != 0 ||
db_dirdelete(target_dbip, old_dp) != 0)) {
rt_db_free_internal(&intern);
return BRLCAD_ERROR;
}
struct directory *target_dp = db_diradd(target_dbip, object_name,
RT_DIR_PHONY_ADDR, 0, RT_DIR_SOLID, (void *)&intern.idb_type);
if (target_dp == RT_DIR_NULL) {
rt_db_free_internal(&intern);
return BRLCAD_ERROR;
}
if (rt_db_put_internal(target_dp, target_dbip, &intern) < 0)
return BRLCAD_ERROR;
return BRLCAD_OK;
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
+35
View File
@@ -0,0 +1,35 @@
/* T R A N S F E R . H
* BRL-CAD
*
* Copyright (c) 2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library 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 this file; see the file named COPYING for more
* information.
*/
#ifndef LIBGED_FACETIZE_TRANSFER_H
#define LIBGED_FACETIZE_TRANSFER_H
#include "rt/db_instance.h"
/**
* Move the worker's fixed-name staged result into @p target_dbip under
* @p object_name. The expected type is checked before the target changes.
*/
int
facetize_transfer_staged_object(struct db_i *target_dbip,
const char *result_file, const char *object_name,
int expected_object_type);
#endif /* LIBGED_FACETIZE_TRANSFER_H */
File diff suppressed because it is too large Load Diff
+33 -71
View File
@@ -25,7 +25,6 @@
#include "common.h"
#include <cmath>
#include <string.h>
#include <iostream>
@@ -35,12 +34,12 @@
#include "bu/path.h"
#include "bu/ptbl.h"
#include "rt/search.h"
#include "rt/calc.h"
#include "rt/db_instance.h"
#include "rt/primitives/bot.h"
#include "wdb.h"
#include "../ged_private.h"
#include "./ged_facetize.h"
#include "./validation.h"
static const size_t FACETIZE_TERMINAL_DETAIL_LIMIT = 10u;
static const char FACETIZE_LOG_EXTENSION[] = ".log";
@@ -284,72 +283,6 @@ _db_uniq_test(struct bu_vls *n, void *data)
return 0;
}
int
_ged_facetize_csg_bbox(struct db_i *dbip, const char *obj_name, point_t rpp_min, point_t rpp_max)
{
if (!dbip || !obj_name || !rpp_min || !rpp_max)
return BRLCAD_ERROR;
struct directory *dp = db_lookup(dbip, obj_name, LOOKUP_QUIET);
if (dp == RT_DIR_NULL)
return BRLCAD_ERROR;
if (rt_bound_internal(dbip, dp, rpp_min, rpp_max) != 0)
return BRLCAD_ERROR;
vect_t d;
VSUB2(d, rpp_max, rpp_min);
if (d[X] <= 0.0 || d[Y] <= 0.0 || d[Z] <= 0.0)
return BRLCAD_ERROR;
for (int i = 0; i < 3; i++) {
if (!std::isfinite(rpp_min[i]) || !std::isfinite(rpp_max[i]))
return BRLCAD_ERROR;
}
return BRLCAD_OK;
}
int
_ged_validate_objs_list(struct _ged_facetize_state *s, int argc, const char *argv[], int newobj_cnt)
{
int i;
struct ged *gedp = s->gedp;
if (s->in_place && newobj_cnt) {
bu_vls_printf(gedp->ged_result_str, "In place conversion specified, but object list includes objects that do not exist:\n");
for (i = argc - newobj_cnt; i < argc; i++) {
bu_vls_printf(gedp->ged_result_str, " %s\n", argv[i]);
}
bu_vls_printf(gedp->ged_result_str, "\nAborting. When performing an in-place facetization, a single pre-existing object must be specified.\n");
return BRLCAD_ERROR;
}
if (!s->in_place) {
if (newobj_cnt < 1) {
bu_vls_printf(gedp->ged_result_str, "all objects listed already exist, aborting. (Need new object name to write out results to.)\n");
return BRLCAD_ERROR;
}
if (newobj_cnt > 1) {
bu_vls_printf(gedp->ged_result_str, "More than one object listed does not exist:\n");
for (i = argc - newobj_cnt; i < argc; i++) {
bu_vls_printf(gedp->ged_result_str, " %s\n", argv[i]);
}
bu_vls_printf(gedp->ged_result_str, "\nAborting. Need to specify exactly one object name that does not exist to hold facetization output.\n");
return BRLCAD_ERROR;
}
if (argc - newobj_cnt == 0) {
bu_vls_printf(gedp->ged_result_str, "No existing objects specified, nothing to facetize. Aborting.\n");
return BRLCAD_ERROR;
}
}
return BRLCAD_OK;
}
int
_ged_facetize_write_bot(struct db_i *dbip, struct rt_bot_internal *bot, const char *name, int verbosity)
{
@@ -364,6 +297,21 @@ _ged_facetize_write_bot(struct db_i *dbip, struct rt_bot_internal *bot, const ch
bu_avs_init_empty(&intern.idb_avs);
(void)bu_avs_add(&intern.idb_avs, "facetized", "1");
/* In-memory databases do not have the file allocator used by
* rt_db_put_internal. Route them through their dedicated writer so
* isolated workers can finish evaluation before announcing a staged
* disk write to the parent. */
if (!dbip->dbi_filename) {
struct rt_wdb *wdbp = wdb_dbopen(dbip, RT_WDB_TYPE_DB_INMEM);
if (!wdbp || wdb_put_internal(wdbp, name, &intern, 1.0) < 0) {
if (verbosity >= 0)
bu_log("Failed to write %s to in-memory database\n", name);
rt_db_free_internal(&intern);
return BRLCAD_ERROR;
}
return BRLCAD_OK;
}
struct directory *dp = db_diradd(dbip, name, RT_DIR_PHONY_ADDR, 0, RT_DIR_SOLID, (void *)&intern.idb_type);
if (dp == RT_DIR_NULL) {
if (verbosity >= 0)
@@ -584,8 +532,20 @@ bot_fixup(struct _ged_facetize_state *s, struct db_i *wdbip, struct directory *b
// Have faces, test with raytracer
struct rt_i *rtip = rt_i_create(wdbip);
rt_gettree(rtip, bname);
rt_prep(rtip);
struct bu_hook_list saved_hooks = BU_HOOK_LIST_INIT_ZERO;
facetize_log_hooks_silence(&saved_hooks);
int prep_status = rt_gettree(rtip, bname);
if (prep_status == 0)
rt_prep(rtip);
facetize_log_hooks_restore(&saved_hooks);
if (prep_status != 0 || !rtip->stats.nsolids || !rtip->stats.nregions) {
facetize_log(s, 2, "\t%s: raytrace preparation failed; retaining original manifold result.\n", bname);
rt_i_destroy(rtip);
rt_db_free_internal(&bot_intern);
return NULL;
}
facetize_log(s, 2, "\t%s: raytrace preparation complete; scanning %zu faces...\n", bname, bot->num_faces);
struct bu_ptbl tfaces = BU_PTBL_INIT_ZERO;
int have_thin_faces = rt_bot_thin_check(&tfaces, bot, rtip, VUNITIZE_TOL, 0);
@@ -741,7 +701,7 @@ facetize_collect_primitive_summary(struct _ged_facetize_state *s)
for (m_it = method_sets.begin(); m_it != method_sets.end(); ++m_it) {
total += m_it->second.size();
if (m_it->first == std::string("FAIL")) fail_cnt += m_it->second.size();
if (m_it->first == std::string("REPAIR")) repair_cnt += m_it->second.size();
if (m_it->first == std::string("REPAIR") || m_it->first == std::string("REPAIR_OPENVDB")) repair_cnt += m_it->second.size();
if (m_it->first == std::string("PLATE")) plate_cnt += m_it->second.size();
}
bu_vls_printf(s->primitive_summary, " %-43s %8zu\n", "Total solids evaluated", total);
@@ -752,6 +712,8 @@ facetize_collect_primitive_summary(struct _ged_facetize_state *s)
for (m_it = method_sets.begin(); m_it != method_sets.end(); ++m_it) {
if (m_it->first == std::string("REPAIR")) {
bu_vls_printf(s->primitive_summary, " %-41s %8zu\n", "bot repair", m_it->second.size());
} else if (m_it->first == std::string("REPAIR_OPENVDB")) {
bu_vls_printf(s->primitive_summary, " %-41s %8zu\n", "OpenVDB level-set repair", m_it->second.size());
} else if (m_it->first == std::string("PLATE")) {
bu_vls_printf(s->primitive_summary, " %-41s %8zu\n", "plate extrusion", m_it->second.size());
} else if (m_it->first == std::string("FAIL")) {
+158
View File
@@ -0,0 +1,158 @@
/* V A L I D A T I O N . C P P
* BRL-CAD
*
* Copyright (c) 2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library 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.
*/
#include "common.h"
#include <cmath>
#include "bu/log.h"
#include "rt/calc.h"
#include "raytrace.h"
#include "./ged_facetize.h"
#include "./validation.h"
static int
facetize_discard_log(void *UNUSED(data), void *UNUSED(message))
{
return 0;
}
void
facetize_log_hooks_silence(struct bu_hook_list *saved_hooks)
{
if (!saved_hooks)
return;
bu_log_hook_save_all(saved_hooks);
bu_log_hook_delete_all();
bu_log_add_hook(facetize_discard_log, NULL);
}
void
facetize_log_hooks_restore(struct bu_hook_list *saved_hooks)
{
if (!saved_hooks)
return;
bu_log_hook_delete_all();
bu_log_hook_restore_all(saved_hooks);
bu_hook_delete_all(saved_hooks);
}
static int
facetize_bound_internal(struct db_i *dbip, struct directory *dp,
point_t bounds_min, point_t bounds_max)
{
/* A failed bound is an expected validation outcome for unbounded or
* otherwise unsampleable CSG. rt_bound_internal logs every failure,
* which floods large runs before facetize can report the aggregate. */
struct bu_hook_list saved_hooks = BU_HOOK_LIST_INIT_ZERO;
facetize_log_hooks_silence(&saved_hooks);
int ret = BRLCAD_ERROR;
if (!BU_SETJUMP) {
ret = rt_bound_internal(dbip, dp, bounds_min, bounds_max);
} else {
BU_UNSETJUMP;
facetize_log_hooks_restore(&saved_hooks);
return BRLCAD_ERROR;
}
BU_UNSETJUMP;
facetize_log_hooks_restore(&saved_hooks);
return ret;
}
int
_ged_facetize_csg_bbox(struct db_i *dbip, const char *object_name,
point_t bounds_min, point_t bounds_max)
{
if (!dbip || !object_name || !bounds_min || !bounds_max)
return BRLCAD_ERROR;
struct directory *dp = db_lookup(dbip, object_name, LOOKUP_QUIET);
if (dp == RT_DIR_NULL ||
facetize_bound_internal(dbip, dp, bounds_min, bounds_max) != 0)
return BRLCAD_ERROR;
vect_t dimensions;
VSUB2(dimensions, bounds_max, bounds_min);
if (dimensions[X] <= 0.0 || dimensions[Y] <= 0.0 ||
dimensions[Z] <= 0.0)
return BRLCAD_ERROR;
for (int i = 0; i < 3; i++) {
if (!std::isfinite(bounds_min[i]) || !std::isfinite(bounds_max[i]))
return BRLCAD_ERROR;
}
return BRLCAD_OK;
}
long
facetize_csg_metrics(struct db_i *dbip, const char *object_name,
double *surface_area, double *volume)
{
if (!dbip || !object_name || !object_name[0] || !surface_area || !volume)
return -1L;
*surface_area = -1.0;
*volume = -1.0;
point_t focus_min, focus_max;
if (_ged_facetize_csg_bbox(dbip, object_name, focus_min, focus_max) !=
BRLCAD_OK) {
/* Surface area and volume are not defined for an unbounded CSG result.
* A finite combination clipped by a halfspace still has valid bounds and
* proceeds; a standalone or otherwise unbounded halfspace stops here. */
return -1L;
}
struct rt_i *rtip = rt_i_create(dbip);
if (!rtip)
return -1L;
struct bu_hook_list saved_hooks = BU_HOOK_LIST_INIT_ZERO;
facetize_log_hooks_silence(&saved_hooks);
int prep_status = rt_gettree(rtip, object_name);
if (prep_status == 0)
rt_prep_parallel(rtip, 1);
facetize_log_hooks_restore(&saved_hooks);
if (prep_status != 0 || !rtip->stats.nsolids || !rtip->stats.nregions) {
rt_i_destroy(rtip);
return -1L;
}
struct rt_crofton_params parameters = {};
parameters.n_rays = 0;
parameters.stability_mm = 0.05;
parameters.time_ms = 2000.0;
int crossings = rt_crofton_shoot(surface_area, volume, NULL, NULL, NULL,
NULL, NULL, rtip, &parameters, focus_min, focus_max);
rt_i_destroy(rtip);
return (crossings >= 0) ? (long)crossings : -1L;
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
+28
View File
@@ -0,0 +1,28 @@
/* V A L I D A T I O N . H
* BRL-CAD
*
* Copyright (c) 2026 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*/
#ifndef LIBGED_FACETIZE_VALIDATION_H
#define LIBGED_FACETIZE_VALIDATION_H
#include "bu/hook.h"
#include "rt/db_instance.h"
void
facetize_log_hooks_silence(struct bu_hook_list *saved_hooks);
void
facetize_log_hooks_restore(struct bu_hook_list *saved_hooks);
long
facetize_csg_metrics(struct db_i *dbip, const char *object_name,
double *surface_area, double *volume);
#endif /* LIBGED_FACETIZE_VALIDATION_H */
+501 -39
View File
@@ -24,29 +24,230 @@
#include "common.h"
#include <algorithm>
#include <sstream>
#include <errno.h>
#if defined(HAVE_PTHREAD_H) && defined(HAVE_SIGNAL_H)
# include <pthread.h>
#endif
#include <string.h>
#include "bu/interrupt.h"
#include "bu/log.h"
#include "./worker.h"
const char FACETIZE_WORKER_RESULT_OBJECT[] = "facetize_worker_result";
static const char FACETIZE_REQUEST_MAGIC[] = "FACETIZE_REQUEST";
static const char FACETIZE_COMMIT_MAGIC[] = "FACETIZE_COMMIT";
static const char FACETIZE_RESULT_MAGIC[] = "FACETIZE_RESULT";
static const char FACETIZE_WRITE_READY_MAGIC[] = "FACETIZE_WRITE_READY";
static const char FACETIZE_REGION_WRITE_READY_MAGIC[] =
"FACETIZE_REGION_WRITE_READY";
static const char FACETIZE_WRITE_PROCEED_MAGIC[] = "FACETIZE_WRITE_PROCEED";
static const char FACETIZE_WRITE_STARTED_MAGIC[] = "FACETIZE_WRITE_STARTED";
static const char FACETIZE_WRITE_DONE_MAGIC[] = "FACETIZE_WRITE_DONE";
static const size_t FACETIZE_REQUEST_NAME_MAX = 1024u * 1024u;
static const size_t FACETIZE_PROTOCOL_HEADER_SIZE = 128u;
static const char FACETIZE_CSG_RESULT_MAGIC[] = "FACETIZE_CSG_RESULT";
static const unsigned int FACETIZE_PROTOCOL_VERSION = 3u;
static const size_t FACETIZE_PROTOCOL_FIELD_MAX = 1024u * 1024u;
static const size_t FACETIZE_PROTOCOL_LIST_MAX = 65536u;
static const size_t FACETIZE_PROTOCOL_HEADER_SIZE = 256u;
static const size_t FACETIZE_MIB = 1024u * 1024u;
static const size_t FACETIZE_MIN_MEMORY_HEADROOM = 1024u * FACETIZE_MIB;
static const size_t FACETIZE_MIN_WORKER_RESERVE = 512u * FACETIZE_MIB;
static const size_t FACETIZE_MEMORY_HEADROOM_DIVISOR = 4u;
static const size_t FACETIZE_AUTOMATIC_WORKER_LIMIT = 2u;
class FacetizePipeWriteGuard
{
public:
FacetizePipeWriteGuard()
{
#if defined(HAVE_PTHREAD_H) && defined(HAVE_SIGNAL_H) && defined(SIGPIPE)
sigemptyset(&blocked_signals);
sigaddset(&blocked_signals, SIGPIPE);
active = pthread_sigmask(SIG_BLOCK, &blocked_signals,
&original_mask) == 0;
sigset_t pending_signals;
if (active && sigpending(&pending_signals) == 0)
had_pending_sigpipe = sigismember(&pending_signals, SIGPIPE) == 1;
#endif
}
~FacetizePipeWriteGuard()
{
#if defined(HAVE_PTHREAD_H) && defined(HAVE_SIGNAL_H) && defined(SIGPIPE)
if (!active)
return;
int saved_errno = errno;
sigset_t pending_signals;
bool have_new_sigpipe = !had_pending_sigpipe &&
sigpending(&pending_signals) == 0 &&
sigismember(&pending_signals, SIGPIPE) == 1;
if (have_new_sigpipe) {
/* The write's SIGPIPE is blocked and already pending on this
* thread, so sigwait can consume it without waiting. */
int signal_number = 0;
while (sigwait(&blocked_signals, &signal_number) == EINTR)
;
}
(void)pthread_sigmask(SIG_SETMASK, &original_mask, NULL);
errno = saved_errno;
#endif
}
private:
#if defined(HAVE_PTHREAD_H) && defined(HAVE_SIGNAL_H) && defined(SIGPIPE)
sigset_t blocked_signals;
sigset_t original_mask;
bool active = false;
bool had_pending_sigpipe = false;
#endif
};
static bool
facetize_send_result(FILE *response_stream, const char *message_type, int result)
facetize_send_field(FILE *stream, const char *field, size_t field_length)
{
return stream && field &&
fwrite(field, 1, field_length, stream) == field_length &&
fputc('\n', stream) != EOF;
}
static bool
facetize_send_sized_field(FILE *stream, const std::string &field)
{
if (!stream || field.size() > FACETIZE_PROTOCOL_FIELD_MAX)
return false;
return fprintf(stream, "%zu\n", field.size()) >= 0 &&
facetize_send_field(stream, field.c_str(), field.size());
}
static FacetizeWorkerReadResult
facetize_read_header(FILE *stream, char *header, size_t header_size)
{
if (!stream || !header || header_size < 2)
return FacetizeWorkerReadResult::Error;
if (!bu_fgets(header, header_size, stream))
return feof(stream) ? FacetizeWorkerReadResult::End :
FacetizeWorkerReadResult::Error;
size_t header_length = strlen(header);
return (header_length && header[header_length - 1] == '\n') ?
FacetizeWorkerReadResult::Request : FacetizeWorkerReadResult::Error;
}
static bool
facetize_read_field(FILE *stream, size_t field_length, std::string &field)
{
field.assign(field_length, '\0');
if ((!field_length ||
fread(&field[0], 1, field_length, stream) == field_length) &&
fgetc(stream) == '\n')
return true;
field.clear();
return false;
}
static bool
facetize_read_sized_field(FILE *stream, std::string &field)
{
field.clear();
char header[FACETIZE_PROTOCOL_HEADER_SIZE];
if (facetize_read_header(stream, header, sizeof(header)) !=
FacetizeWorkerReadResult::Request)
return false;
size_t field_length = 0;
std::istringstream header_stream(header);
if (!(header_stream >> field_length) ||
!(header_stream >> std::ws).eof() ||
field_length > FACETIZE_PROTOCOL_FIELD_MAX)
return false;
return facetize_read_field(stream, field_length, field);
}
static bool
facetize_operation_valid(FacetizeWorkerOperation operation)
{
return operation == FacetizeWorkerOperation::TessellatePrimitive ||
operation == FacetizeWorkerOperation::ValidateCsg ||
operation == FacetizeWorkerOperation::EvaluateRegion ||
operation == FacetizeWorkerOperation::NmgBooleanToBot ||
operation == FacetizeWorkerOperation::NmgBooleanToNmg;
}
static bool
facetize_send_result(FILE *response_stream, const char *message_type, int result,
size_t resident_size)
{
if (!response_stream)
return false;
return fprintf(response_stream, "%s %d\n", message_type, result) >= 0 &&
fflush(response_stream) == 0;
return fprintf(response_stream, "%s %d %zu\n", message_type, result,
resident_size) >= 0 && fflush(response_stream) == 0;
}
FacetizeWorkerPolicy::FacetizeWorkerPolicy(size_t requested_workers,
size_t work_count, size_t available_cpus, size_t total_memory,
size_t available_memory)
{
available_cpus = std::max((size_t)1, available_cpus);
size_t worker_limit = requested_workers ? requested_workers :
FACETIZE_AUTOMATIC_WORKER_LIMIT;
worker_limit = std::min(worker_limit, available_cpus);
if (work_count)
worker_limit = std::min(worker_limit, work_count);
if (total_memory && available_memory) {
memory_headroom = std::max(FACETIZE_MIN_MEMORY_HEADROOM,
total_memory / FACETIZE_MEMORY_HEADROOM_DIVISOR);
if (available_memory > memory_headroom) {
size_t memory_workers = (available_memory - memory_headroom) /
FACETIZE_MIN_WORKER_RESERVE;
worker_limit = std::min(worker_limit,
std::max((size_t)1, memory_workers));
} else {
worker_limit = 1;
}
} else {
worker_limit = 1;
}
workers = std::max((size_t)1, worker_limit);
worker_threads = std::max((size_t)1, available_cpus / workers);
}
size_t
FacetizeWorkerPolicy::worker_count() const
{
return workers;
}
size_t
FacetizeWorkerPolicy::threads_per_worker() const
{
return worker_threads;
}
bool
FacetizeWorkerPolicy::can_dispatch(size_t active_workers,
size_t available_memory, size_t observed_worker_resident) const
{
if (!active_workers)
return true;
if (workers == 1 || !available_memory || !memory_headroom)
return false;
size_t worker_reserve = std::max(FACETIZE_MIN_WORKER_RESERVE,
observed_worker_resident);
if (worker_reserve > SIZE_MAX - memory_headroom)
return false;
return available_memory > memory_headroom + worker_reserve;
}
void
@@ -57,19 +258,116 @@ FacetizeWorkerClient::reset(FILE *stream)
}
bool
FacetizeWorkerClient::send_request(const char *object_name)
FacetizePrimitiveSettings::empty() const
{
if (!request_stream || !object_name || !object_name[0])
return methods.empty() && method_options.empty() &&
cache_directory.empty() && point_limit == 0;
}
bool
FacetizeRegionSettings::empty() const
{
return !no_empty && !no_fixup && !tolerate_failures;
}
bool
FacetizeWorkerRequest::valid() const
{
if (!facetize_operation_valid(operation) || input_names.empty() ||
input_names.size() > FACETIZE_PROTOCOL_LIST_MAX ||
primitive.methods.size() > FACETIZE_PROTOCOL_LIST_MAX ||
primitive.method_options.size() > FACETIZE_PROTOCOL_LIST_MAX ||
output_name.size() > FACETIZE_PROTOCOL_FIELD_MAX ||
primitive.cache_directory.size() > FACETIZE_PROTOCOL_FIELD_MAX ||
primitive.point_limit < 0)
return false;
for (const std::string &input_name : input_names)
if (input_name.empty() || input_name.size() > FACETIZE_PROTOCOL_FIELD_MAX)
return false;
for (const std::string &method : primitive.methods)
if (method.empty() || method.size() > FACETIZE_PROTOCOL_FIELD_MAX)
return false;
for (const std::string &options : primitive.method_options)
if (options.empty() || options.size() > FACETIZE_PROTOCOL_FIELD_MAX)
return false;
switch (operation) {
case FacetizeWorkerOperation::TessellatePrimitive:
return input_names.size() == 1 && output_name.empty() &&
region.empty();
case FacetizeWorkerOperation::ValidateCsg:
return input_names.size() == 1 && output_name.empty() &&
primitive.empty() && region.empty();
case FacetizeWorkerOperation::EvaluateRegion:
return input_names.size() == 1 && output_name.empty() &&
primitive.empty();
case FacetizeWorkerOperation::NmgBooleanToBot:
case FacetizeWorkerOperation::NmgBooleanToNmg:
return !output_name.empty() && primitive.empty() && region.empty();
}
return false;
}
std::string
FacetizeWorkerRequest::label() const
{
if (!output_name.empty())
return output_name;
return input_names.empty() ? "(unknown)" : input_names.front();
}
bool
FacetizeWorkerClient::send_request(const FacetizeWorkerRequest &request)
{
if (!request_stream || !request.valid())
return false;
FacetizePipeWriteGuard write_guard;
if (fprintf(request_stream, "%s %u %d %zu %zu %zu %d %d %d %d\n",
FACETIZE_REQUEST_MAGIC, FACETIZE_PROTOCOL_VERSION,
static_cast<int>(request.operation), request.input_names.size(),
request.primitive.methods.size(),
request.primitive.method_options.size(),
request.primitive.point_limit, request.region.no_empty ? 1 : 0,
request.region.no_fixup ? 1 : 0,
request.region.tolerate_failures ? 1 : 0) < 0 ||
!facetize_send_sized_field(request_stream,
request.primitive.cache_directory) ||
!facetize_send_sized_field(request_stream, request.output_name))
return false;
for (const std::string &input_name : request.input_names)
if (!facetize_send_sized_field(request_stream, input_name))
return false;
for (const std::string &method : request.primitive.methods)
if (!facetize_send_sized_field(request_stream, method))
return false;
for (const std::string &options : request.primitive.method_options)
if (!facetize_send_sized_field(request_stream, options))
return false;
return fflush(request_stream) == 0;
}
bool
FacetizeWorkerClient::send_commit(const char *result_file,
const char *object_name, size_t payload_size)
{
if (!request_stream || !result_file || !result_file[0] ||
!object_name || !object_name[0])
return false;
size_t file_length = strlen(result_file);
size_t name_length = strlen(object_name);
if (name_length > FACETIZE_REQUEST_NAME_MAX)
if (file_length > FACETIZE_PROTOCOL_FIELD_MAX ||
name_length > FACETIZE_PROTOCOL_FIELD_MAX)
return false;
return fprintf(request_stream, "%s %zu\n", FACETIZE_REQUEST_MAGIC,
name_length) >= 0 &&
fwrite(object_name, 1, name_length, request_stream) == name_length &&
fputc('\n', request_stream) != EOF && fflush(request_stream) == 0;
FacetizePipeWriteGuard write_guard;
return fprintf(request_stream, "%s %zu %zu %zu\n",
FACETIZE_COMMIT_MAGIC, file_length, name_length, payload_size) >= 0 &&
facetize_send_field(request_stream, result_file, file_length) &&
facetize_send_field(request_stream, object_name, name_length) &&
fflush(request_stream) == 0;
}
bool
@@ -78,6 +376,7 @@ FacetizeWorkerClient::send_write_proceed()
if (!request_stream)
return false;
FacetizePipeWriteGuard write_guard;
return fprintf(request_stream, "%s\n", FACETIZE_WRITE_PROCEED_MAGIC) >= 0 &&
fflush(request_stream) == 0;
}
@@ -100,26 +399,62 @@ FacetizeWorkerClient::consume_output(const char *data, size_t data_size,
std::string message_type;
int parsed_result = BRLCAD_ERROR;
size_t parsed_payload_size = 0;
size_t parsed_resident_size = 0;
long parsed_crossings = -1;
int parsed_tolerated_failures = 0;
double parsed_surface_area = -1.0;
double parsed_volume = -1.0;
line_stream >> message_type;
if (message_type == FACETIZE_WRITE_READY_MAGIC &&
(line_stream >> parsed_payload_size) &&
(line_stream >> parsed_payload_size >> parsed_resident_size) &&
(line_stream >> std::ws).eof()) {
status.write_ready = true;
status.payload_size = parsed_payload_size;
status.resident_size = parsed_resident_size;
continue;
}
if (message_type == FACETIZE_REGION_WRITE_READY_MAGIC &&
(line_stream >> parsed_payload_size >> parsed_resident_size >>
parsed_tolerated_failures) &&
(line_stream >> std::ws).eof() &&
parsed_tolerated_failures >= 0) {
status.write_ready = true;
status.payload_size = parsed_payload_size;
status.resident_size = parsed_resident_size;
status.tolerated_failures = parsed_tolerated_failures;
continue;
}
if (message_type == FACETIZE_WRITE_STARTED_MAGIC &&
(line_stream >> std::ws).eof()) {
status.write_started = true;
continue;
}
if (message_type == FACETIZE_WRITE_DONE_MAGIC &&
(line_stream >> parsed_result) &&
(line_stream >> parsed_result >> parsed_resident_size) &&
(line_stream >> std::ws).eof()) {
status.result = parsed_result;
status.resident_size = parsed_resident_size;
status.write_done = true;
status.result_received = true;
continue;
}
if (message_type == FACETIZE_RESULT_MAGIC &&
(line_stream >> parsed_result) &&
(line_stream >> parsed_result >> parsed_resident_size) &&
(line_stream >> std::ws).eof()) {
status.result = parsed_result;
status.resident_size = parsed_resident_size;
status.result_received = true;
continue;
}
if (message_type == FACETIZE_CSG_RESULT_MAGIC &&
(line_stream >> parsed_result >> parsed_crossings >>
parsed_surface_area >> parsed_volume >> parsed_resident_size) &&
(line_stream >> std::ws).eof()) {
status.result = parsed_result;
status.csg_crossings = parsed_crossings;
status.csg_surface_area = parsed_surface_area;
status.csg_volume = parsed_volume;
status.resident_size = parsed_resident_size;
status.result_received = true;
continue;
}
@@ -134,35 +469,124 @@ FacetizeWorkerServer::FacetizeWorkerServer(FILE *input, FILE *output) :
}
FacetizeWorkerReadResult
FacetizeWorkerServer::receive_request(std::string &object_name)
FacetizeWorkerServer::receive_request(FacetizeWorkerRequest &request)
{
object_name.clear();
request = FacetizeWorkerRequest();
if (!request_stream)
return FacetizeWorkerReadResult::Error;
char header[FACETIZE_PROTOCOL_HEADER_SIZE];
if (!bu_fgets(header, sizeof(header), request_stream))
return feof(request_stream) ? FacetizeWorkerReadResult::End :
FacetizeWorkerReadResult::Error;
FacetizeWorkerReadResult read_result = facetize_read_header(request_stream,
header, sizeof(header));
if (read_result != FacetizeWorkerReadResult::Request)
return read_result;
size_t header_length = strlen(header);
if (!header_length || header[header_length - 1] != '\n')
return FacetizeWorkerReadResult::Error;
size_t name_length = 0;
unsigned int protocol_version = 0;
int operation_value = 0;
size_t input_count = 0;
size_t method_count = 0;
size_t method_option_count = 0;
int point_limit = 0;
int no_empty = 0;
int no_fixup = 0;
int tolerate_failures = 0;
std::string message_type;
std::istringstream header_stream(header);
if (!(header_stream >> message_type) ||
message_type != FACETIZE_REQUEST_MAGIC ||
!(header_stream >> name_length) ||
!(header_stream >> std::ws).eof() || !name_length ||
name_length > FACETIZE_REQUEST_NAME_MAX)
!(header_stream >> protocol_version) ||
protocol_version != FACETIZE_PROTOCOL_VERSION ||
!(header_stream >> operation_value >> input_count >> method_count >>
method_option_count >> point_limit >> no_empty >> no_fixup >>
tolerate_failures) ||
!(header_stream >> std::ws).eof() || !input_count ||
input_count > FACETIZE_PROTOCOL_LIST_MAX ||
method_count > FACETIZE_PROTOCOL_LIST_MAX ||
method_option_count > FACETIZE_PROTOCOL_LIST_MAX || point_limit < 0 ||
(no_empty != 0 && no_empty != 1) ||
(no_fixup != 0 && no_fixup != 1) ||
(tolerate_failures != 0 && tolerate_failures != 1))
return FacetizeWorkerReadResult::Error;
object_name.assign(name_length, '\0');
if (fread(&object_name[0], 1, name_length, request_stream) != name_length ||
fgetc(request_stream) != '\n') {
object_name.clear();
request.operation = static_cast<FacetizeWorkerOperation>(operation_value);
request.primitive.point_limit = point_limit;
request.region.no_empty = no_empty != 0;
request.region.no_fixup = no_fixup != 0;
request.region.tolerate_failures = tolerate_failures != 0;
if (!facetize_read_sized_field(request_stream,
request.primitive.cache_directory) ||
!facetize_read_sized_field(request_stream, request.output_name)) {
request = FacetizeWorkerRequest();
return FacetizeWorkerReadResult::Error;
}
request.input_names.reserve(input_count);
for (size_t i = 0; i < input_count; i++) {
std::string input_name;
if (!facetize_read_sized_field(request_stream, input_name)) {
request = FacetizeWorkerRequest();
return FacetizeWorkerReadResult::Error;
}
request.input_names.push_back(input_name);
}
request.primitive.methods.reserve(method_count);
for (size_t i = 0; i < method_count; i++) {
std::string method;
if (!facetize_read_sized_field(request_stream, method)) {
request = FacetizeWorkerRequest();
return FacetizeWorkerReadResult::Error;
}
request.primitive.methods.push_back(method);
}
request.primitive.method_options.reserve(method_option_count);
for (size_t i = 0; i < method_option_count; i++) {
std::string options;
if (!facetize_read_sized_field(request_stream, options)) {
request = FacetizeWorkerRequest();
return FacetizeWorkerReadResult::Error;
}
request.primitive.method_options.push_back(options);
}
if (!request.valid()) {
request = FacetizeWorkerRequest();
return FacetizeWorkerReadResult::Error;
}
return FacetizeWorkerReadResult::Request;
}
FacetizeWorkerReadResult
FacetizeWorkerServer::receive_commit(FacetizeCommitRequest &request)
{
request = FacetizeCommitRequest();
if (!request_stream)
return FacetizeWorkerReadResult::Error;
char header[FACETIZE_PROTOCOL_HEADER_SIZE];
FacetizeWorkerReadResult read_result = facetize_read_header(request_stream,
header, sizeof(header));
if (read_result != FacetizeWorkerReadResult::Request)
return read_result;
size_t file_length = 0;
size_t name_length = 0;
std::string message_type;
std::istringstream header_stream(header);
if (!(header_stream >> message_type) ||
message_type != FACETIZE_COMMIT_MAGIC ||
!(header_stream >> file_length >> name_length >> request.payload_size) ||
!(header_stream >> std::ws).eof() || !file_length || !name_length ||
file_length > FACETIZE_PROTOCOL_FIELD_MAX ||
name_length > FACETIZE_PROTOCOL_FIELD_MAX)
return FacetizeWorkerReadResult::Error;
if (!facetize_read_field(request_stream, file_length,
request.result_file) ||
!facetize_read_field(request_stream, name_length,
request.object_name)) {
request = FacetizeCommitRequest();
return FacetizeWorkerReadResult::Error;
}
@@ -170,13 +594,27 @@ FacetizeWorkerServer::receive_request(std::string &object_name)
}
bool
FacetizeWorkerServer::send_write_ready(size_t payload_size)
FacetizeWorkerServer::send_write_ready(size_t payload_size,
size_t resident_size)
{
if (!response_stream)
return false;
return fprintf(response_stream, "%s %zu\n", FACETIZE_WRITE_READY_MAGIC,
payload_size) >= 0 && fflush(response_stream) == 0;
return fprintf(response_stream, "%s %zu %zu\n",
FACETIZE_WRITE_READY_MAGIC, payload_size, resident_size) >= 0 &&
fflush(response_stream) == 0;
}
bool
FacetizeWorkerServer::send_region_write_ready(size_t payload_size,
size_t resident_size, int tolerated_failures)
{
if (!response_stream || tolerated_failures < 0)
return false;
return fprintf(response_stream, "%s %zu %zu %d\n",
FACETIZE_REGION_WRITE_READY_MAGIC, payload_size, resident_size,
tolerated_failures) >= 0 && fflush(response_stream) == 0;
}
bool
@@ -194,16 +632,40 @@ FacetizeWorkerServer::receive_write_proceed()
}
bool
FacetizeWorkerServer::send_tessellation_result(int result)
FacetizeWorkerServer::send_write_started()
{
return facetize_send_result(response_stream, FACETIZE_RESULT_MAGIC, result);
if (!response_stream)
return false;
return fprintf(response_stream, "%s\n", FACETIZE_WRITE_STARTED_MAGIC) >= 0 &&
fflush(response_stream) == 0;
}
bool
FacetizeWorkerServer::send_write_result(int result)
FacetizeWorkerServer::send_tessellation_result(int result,
size_t resident_size)
{
return facetize_send_result(response_stream, FACETIZE_RESULT_MAGIC, result,
resident_size);
}
bool
FacetizeWorkerServer::send_write_result(int result, size_t resident_size)
{
return facetize_send_result(response_stream, FACETIZE_WRITE_DONE_MAGIC,
result);
result, resident_size);
}
bool
FacetizeWorkerServer::send_csg_result(int result, long crossings,
double surface_area, double volume, size_t resident_size)
{
if (!response_stream)
return false;
return fprintf(response_stream, "%s %d %ld %.17g %.17g %zu\n",
FACETIZE_CSG_RESULT_MAGIC, result, crossings, surface_area, volume,
resident_size) >= 0 && fflush(response_stream) == 0;
}
// Local Variables:
+89 -5
View File
@@ -19,12 +19,88 @@
#include "bu/defines.h"
extern const char FACETIZE_WORKER_RESULT_OBJECT[];
struct FacetizeWorkerStatus {
bool write_ready = false;
bool write_started = false;
bool write_done = false;
bool result_received = false;
int result = BRLCAD_ERROR;
size_t payload_size = 0;
size_t resident_size = 0;
long csg_crossings = -1;
double csg_surface_area = -1.0;
double csg_volume = -1.0;
int tolerated_failures = 0;
};
struct FacetizeCommitRequest {
std::string result_file;
std::string object_name;
size_t payload_size = 0;
};
enum class FacetizeWorkerOperation {
TessellatePrimitive = 1,
ValidateCsg = 2,
EvaluateRegion = 3,
NmgBooleanToBot = 4,
NmgBooleanToNmg = 5
};
struct FacetizePrimitiveSettings {
std::vector<std::string> methods;
std::vector<std::string> method_options;
std::string cache_directory;
int point_limit = 0;
bool empty() const;
};
struct FacetizeRegionSettings {
bool no_empty = false;
bool no_fixup = false;
bool tolerate_failures = false;
bool empty() const;
};
struct FacetizeWorkerRequest {
FacetizeWorkerOperation operation =
FacetizeWorkerOperation::TessellatePrimitive;
std::vector<std::string> input_names;
std::string output_name;
FacetizePrimitiveSettings primitive;
FacetizeRegionSettings region;
bool valid() const;
std::string label() const;
};
/**
* Resource limits for a pool of independent facetize workers.
*
* A zero requested_workers selects the conservative automatic limit. Memory
* values are current system-wide byte counts; zero means the platform could
* not supply that measurement. Unknown memory disables outer parallelism.
*/
class FacetizeWorkerPolicy
{
public:
FacetizeWorkerPolicy(size_t requested_workers, size_t work_count,
size_t available_cpus, size_t total_memory,
size_t available_memory);
size_t worker_count() const;
size_t threads_per_worker() const;
bool can_dispatch(size_t active_workers, size_t available_memory,
size_t observed_worker_resident) const;
private:
size_t workers = 1;
size_t worker_threads = 1;
size_t memory_headroom = 0;
};
/**
@@ -41,7 +117,9 @@ class FacetizeWorkerClient
FacetizeWorkerClient() = default;
void reset(FILE *request_stream);
bool send_request(const char *object_name);
bool send_request(const FacetizeWorkerRequest &request);
bool send_commit(const char *result_file, const char *object_name,
size_t payload_size);
bool send_write_proceed();
void consume_output(const char *data, size_t data_size,
FacetizeWorkerStatus &status,
@@ -69,11 +147,17 @@ class FacetizeWorkerServer
public:
FacetizeWorkerServer(FILE *request_stream, FILE *response_stream);
FacetizeWorkerReadResult receive_request(std::string &object_name);
bool send_write_ready(size_t payload_size);
FacetizeWorkerReadResult receive_request(FacetizeWorkerRequest &request);
FacetizeWorkerReadResult receive_commit(FacetizeCommitRequest &request);
bool send_write_ready(size_t payload_size, size_t resident_size);
bool send_region_write_ready(size_t payload_size, size_t resident_size,
int tolerated_failures);
bool receive_write_proceed();
bool send_tessellation_result(int result);
bool send_write_result(int result);
bool send_write_started();
bool send_tessellation_result(int result, size_t resident_size);
bool send_write_result(int result, size_t resident_size);
bool send_csg_result(int result, long crossings, double surface_area,
double volume, size_t resident_size);
private:
FILE *request_stream = NULL;
+29 -37
View File
@@ -483,19 +483,6 @@ _ged_pnts_tri_cmd_ballpivot(void *bs, int argc, const char **argv)
return wret;
}
/* custom bu_opt for size_t threads in spsr */
static int
_pnts_opt_size_t(struct bu_vls *UNUSED(msg), size_t UNUSED(argc), const char **argv, void *set_c)
{
size_t *t = (size_t *)set_c;
int tmp = 0;
const char *a = argv[0];
if (bu_opt_int(NULL, 1, &a, &tmp) < 0) return -1;
if (tmp < 0) return -1;
*t = (size_t)tmp;
return 1;
}
/* tri spsr */
static int
_ged_pnts_tri_cmd_spsr(void *bs, int argc, const char **argv)
@@ -508,29 +495,23 @@ _ged_pnts_tri_cmd_spsr(void *bs, int argc, const char **argv)
struct bg_3d_spsr_opts opts = BG_3D_SPSR_OPTS_DEFAULT;
int print_help = 0;
struct bu_opt_desc d[23];
BU_OPT(d[0], "h", "help", "", NULL, &print_help, "Print help and exit");
BU_OPT(d[1], "", "degree", "#", &bu_opt_int, &opts.degree, "Finite element degree");
BU_OPT(d[2], "", "btype", "#", &bu_opt_int, &opts.btype, "Boundary type (1:FREE, 2:NEUMANN, 3:DIRICHLET)");
BU_OPT(d[3], "", "depth", "#", &bu_opt_int, &opts.depth, "Max reconstruction depth");
BU_OPT(d[4], "", "kerneldepth", "#", &bu_opt_int, &opts.kerneldepth, "Kernel depth");
BU_OPT(d[5], "", "iterations", "#", &bu_opt_int, &opts.iterations, "Solver iterations");
BU_OPT(d[6], "", "full-depth", "#", &bu_opt_int, &opts.full_depth, "Full depth");
BU_OPT(d[7], "", "base-depth", "#", &bu_opt_int, &opts.base_depth, "Coarse MG depth");
BU_OPT(d[8], "", "base-vcycles", "#", &bu_opt_int, &opts.baseVcycles, "Coarse MG v-cycles");
BU_OPT(d[9], "", "max-mem", "#", &bu_opt_int, &opts.max_memory_GB, "Max memory (GB)");
BU_OPT(d[10], "", "threads", "#", _pnts_opt_size_t, &opts.threads, "Threads to use");
BU_OPT(d[11], "", "samples-per-node", "#", &bu_opt_fastf_t, &opts.samples_per_node,"Min samples per node");
BU_OPT(d[12], "", "scale", "#", &bu_opt_fastf_t, &opts.scale, "Scale factor");
BU_OPT(d[13], "", "width", "#", &bu_opt_fastf_t, &opts.width, "Voxel width");
BU_OPT(d[14], "", "confidence", "#", &bu_opt_fastf_t, &opts.confidence, "Normal confidence exponent");
BU_OPT(d[15], "", "confidence-bias", "#", &bu_opt_fastf_t, &opts.confidence_bias, "Normal confidence bias exponent");
BU_OPT(d[16], "", "cg-accuracy", "#", &bu_opt_fastf_t, &opts.cgsolver_accuracy,"CG solver accuracy");
BU_OPT(d[17], "", "point-weight", "#", &bu_opt_fastf_t, &opts.point_weight, "Interpolation weight");
BU_OPT(d[18], "", "nonmanifold", "#", &bu_opt_int, &opts.nonManifold, "NonManifold (0/1)");
BU_OPT(d[19], "", "linearfit", "#", &bu_opt_int, &opts.linearFit, "Linear Fit (0/1)");
BU_OPT(d[20], "", "exact", "#", &bu_opt_int, &opts.exact, "Exact interpolation (0/1)");
BU_OPT_NULL(d[21]);
struct bu_opt_desc d[16];
BU_OPT(d[0], "h", "help", "", NULL, &print_help, "Print help and exit");
BU_OPT(d[1], "", "depth", "#", &bu_opt_int, &opts.depth, "Max reconstruction depth");
BU_OPT(d[2], "", "kerneldepth", "#", &bu_opt_int, &opts.kerneldepth, "Kernel depth");
BU_OPT(d[3], "", "iterations", "#", &bu_opt_int, &opts.iterations, "Solver iterations");
BU_OPT(d[4], "", "full-depth", "#", &bu_opt_int, &opts.full_depth, "Full depth");
BU_OPT(d[5], "", "base-depth", "#", &bu_opt_int, &opts.base_depth, "Coarse MG depth");
BU_OPT(d[6], "", "base-vcycles", "#", &bu_opt_int, &opts.baseVcycles, "Coarse MG v-cycles");
BU_OPT(d[7], "", "samples-per-node", "#", &bu_opt_fastf_t, &opts.samples_per_node, "Min samples per node");
BU_OPT(d[8], "", "scale", "#", &bu_opt_fastf_t, &opts.scale, "Scale factor");
BU_OPT(d[9], "", "width", "#", &bu_opt_fastf_t, &opts.width, "Voxel width");
BU_OPT(d[10], "", "cg-accuracy", "#", &bu_opt_fastf_t, &opts.cgsolver_accuracy,"CG solver accuracy");
BU_OPT(d[11], "", "point-weight", "#", &bu_opt_fastf_t, &opts.point_weight, "Interpolation weight");
BU_OPT(d[12], "", "nonmanifold", "#", &bu_opt_int, &opts.nonManifold, "NonManifold (0/1)");
BU_OPT(d[13], "", "linearfit", "#", &bu_opt_int, &opts.linearFit, "Linear Fit (0/1)");
BU_OPT(d[14], "", "exact", "#", &bu_opt_int, &opts.exact, "Exact interpolation (0/1)");
BU_OPT_NULL(d[15]);
argc -= (argc>0); argv += (argc>0); // skip "spsr"
if (argc < 1) {
@@ -581,7 +562,18 @@ _ged_pnts_tri_cmd_spsr(void *bs, int argc, const char **argv)
point_t *overts = NULL;
int nverts = 0;
int sret = bg_3d_spsr(&faces, &nfaces, &overts, &nverts, (const point_t *)ipts, (const vect_t *)inrms, pcnt, &opts);
std::vector<struct bg_3d_spsr_sample> samples(
static_cast<size_t>(pcnt));
for (size_t i = 0; i < samples.size(); i++) {
VMOVE(samples[i].point, ipts[i]);
VMOVE(samples[i].normal, inrms[i]);
}
struct bg_3d_spsr_adaptive_opts adaptive_options =
BG_3D_SPSR_ADAPTIVE_OPTS_DEFAULT;
adaptive_options.solver = opts;
adaptive_options.max_refinement_passes = 0;
int sret = bg_3d_spsr_adaptive(&faces, &nfaces, &overts, &nverts,
samples.data(), samples.size(), &adaptive_options, NULL, NULL, NULL);
// free inputs
if (ipts)
+19 -1
View File
@@ -6,6 +6,21 @@ brlcad_find_package(OPENNURBS REQUIRED SYSPATTERN openNURBS)
brlcad_find_package(REGEX REQUIRED)
find_package_gte(REQUIRED)
set(LIBRT_OPENVDB_INCLUDE_DIRS)
set(LIBRT_OPENVDB_LIBS)
if(BRLCAD_ENABLE_OPENVDB)
set(LIBRT_OPENVDB_INCLUDE_DIRS ${OpenVDB_INCLUDE_DIRS} ${Tbb_INCLUDE_DIRS} ${IlmBase_INCLUDE_DIRS})
set(LIBRT_OPENVDB_LIBS ${OpenVDB_LIBRARIES} ${IlmBase_LIBRARIES} ${Tbb_LIBRARIES})
# Prevent warnings in OpenVDB/Boost headers and an LTO false positive
# involving OpenVDB's UINT64_MAX LeafManager sentinel.
set_source_files_properties(
primitives/bot/bot_openvdb.cpp
PROPERTIES
COMPILE_DEFINITIONS BRLCAD_OPENVDB
COMPILE_FLAGS "-w -fno-lto"
)
endif(BRLCAD_ENABLE_OPENVDB)
if(BRLCAD_ENABLE_OPENCL)
add_definitions(-DUSE_OPENCL)
endif(BRLCAD_ENABLE_OPENCL)
@@ -150,7 +165,6 @@ set(
prep.cpp
${LIBRT_PRIMEDIT_SOURCES}
primitives/annot/annot.c
primitives/annot/annot_render.cpp
primitives/arb8/arb8.c
primitives/arb8/arb8_brep.cpp
primitives/arb8/arb8_mirror.c
@@ -165,6 +179,7 @@ set(
primitives/bot/bot_edge.c
primitives/bot/bot_mirror.c
primitives/bot/bot_oriented_bbox.cpp
primitives/bot/bot_openvdb.cpp
primitives/bot/bot_plot.cpp
primitives/bot/btg.c
primitives/bot/btgf.c
@@ -436,6 +451,7 @@ set(
${RPCRT_LIB}
${STDCXX_LIBRARIES}
manifold::manifold
${LIBRT_OPENVDB_LIBS}
)
# Include directories needed by librt users
@@ -449,6 +465,7 @@ set(
${BRLCAD_SOURCE_DIR}/src/libbu
${BRLCAD_SOURCE_DIR}/src/libbg
${REGEX_INCLUDE_DIRS}
${LIBRT_OPENVDB_INCLUDE_DIRS}
)
# FIXME: needs materialX
# ${CMAKE_CURRENT_SOURCE_DIR}/../../../MaterialXSource/source
@@ -568,6 +585,7 @@ cmakefiles(
bot2nurbs.txt
brep_csg_boolean.txt
kigumi_todo.txt
primitives/bot/bot_openvdb.h
vds/README
vds/COPYING
vds/vds.h
+586 -47
View File
@@ -49,6 +49,7 @@
#include "nmg.h"
#include "rt/geom.h"
#include "rt/primitives/annot.h"
#include "rt/primitives/bot.h"
#include "raytrace.h"
#if defined(__GNUC__) && !defined(__clang__)
@@ -76,8 +77,46 @@
#define ANNOT_PRES_MAGIC 0x414e5032u /* "ANP2" */
#define ANNOT_PRES_VERSION 1u
/* Stored line widths are display-scale multipliers, not model distances.
* Primitive prep has no view pixel scale, so infer a stable model-space base
* width from the annotation content before applying that multiplier. */
#define ANNOT_TEXT_STROKE_RATIO (1.0 / 14.0)
#define ANNOT_GEOMETRY_STROKE_RATIO 0.01
#define ANNOT_MIN_WIDTH_TOL_FACTOR 4.0
struct annot_mesh {
point_t *vertices;
size_t vertex_count;
size_t vertex_capacity;
int *faces;
fastf_t *thickness;
size_t face_count;
size_t face_capacity;
};
C_DECL void rt_annot_ifree(struct rt_db_internal *ip);
/* Annotation prep uses BOT as a transient raytrace representation, as ARS
* does. These callbacks are internal to librt rather than public BOT APIs. */
C_DECL int rt_bot_prep(struct soltab *stp, struct rt_db_internal *ip,
struct rt_i *rtip);
C_DECL int rt_bot_shot(struct soltab *stp, struct xray *rp,
struct application *ap, struct seg *seghead);
C_DECL void rt_bot_print(const struct soltab *stp);
C_DECL void rt_bot_norm(struct hit *hitp, struct soltab *stp,
struct xray *rp);
C_DECL void rt_bot_curve(struct curvature *cvp, struct hit *hitp,
struct soltab *stp);
C_DECL void rt_bot_uv(struct application *ap, struct soltab *stp,
struct hit *hitp, struct uvcoord *uvp);
C_DECL void rt_bot_free(struct soltab *stp);
C_DECL void rt_bot_ifree(struct rt_db_internal *ip);
static int annot_to_bot(struct rt_bot_internal **result,
const struct rt_annot_internal *annot_ip,
const struct bg_tess_tol *ttol, const struct bn_tol *tol,
unsigned char bot_mode);
static uint32_t
annot_get_uint32(const unsigned char *cp)
{
@@ -434,9 +473,8 @@ rt_annot_validate(const struct rt_annot_internal *annot_ip,
annot_validation_message(messages, i, "fill has no compatible outline segments");
ret++;
} else {
size_t legacy_end = (size_t)fsg->legacy_start +
(size_t)fsg->legacy_count;
for (j = (size_t)fsg->legacy_start; j < legacy_end; ++j)
for (j = (size_t)fsg->legacy_start;
j < (size_t)(fsg->legacy_start + fsg->legacy_count); ++j)
if (!ant->segments[j] ||
*(uint32_t *)ant->segments[j] != CURVE_LSEG_MAGIC) {
annot_validation_message(messages, i,
@@ -503,25 +541,59 @@ rt_annot_validate(const struct rt_annot_internal *annot_ip,
C_DECL int
rt_annot_prep(struct soltab *stp, struct rt_db_internal *ip, struct rt_i *rtip)
{
struct bg_tess_tol default_ttol = BG_TESS_TOL_INIT_TOL;
struct bn_tol default_tol = BN_TOL_INIT_TOL;
const struct rt_annot_internal *annot_ip;
struct rt_bot_internal *bot = NULL;
struct rt_db_internal bot_intern;
const struct bg_tess_tol *ttol = &default_ttol;
const struct bn_tol *tol = &default_tol;
int ret;
if (!stp)
return -1;
RT_CK_SOLTAB(stp);
if (ip) RT_CK_DB_INTERNAL(ip);
if (rtip) RT_CK_RTI(rtip);
if (!ip)
return -1;
RT_CK_DB_INTERNAL(ip);
if (rtip) {
RT_CK_RTI(rtip);
ttol = &rtip->rti_ttol;
tol = &rtip->rti_tol;
}
if (ip && rt_annot_validate(
(const struct rt_annot_internal *)ip->idb_ptr, NULL))
annot_ip = (const struct rt_annot_internal *)ip->idb_ptr;
if (rt_annot_validate(annot_ip, NULL))
return -1;
/* View-space annotations need camera state, which primitive prep does not
* have. Leave them non-intersecting until a view-aware prep API exists. */
stp->st_specific = (void *)NULL;
return 0;
if (!(annot_ip->flags & RT_ANNOT_MODEL_SPACE))
return 0;
if (annot_to_bot(&bot, annot_ip, ttol, tol, RT_BOT_PLATE) || !bot)
return -1;
RT_DB_INTERNAL_INIT(&bot_intern);
bot_intern.idb_major_type = DB5_MAJORTYPE_BRLCAD;
bot_intern.idb_type = ID_BOT;
bot_intern.idb_meth = &OBJ[ID_BOT];
bot_intern.idb_ptr = bot;
ret = rt_bot_prep(stp, &bot_intern, rtip);
rt_bot_ifree(&bot_intern);
return ret;
}
C_DECL void
rt_annot_print(const struct soltab *stp)
{
if (stp) RT_CK_SOLTAB(stp);
if (!stp)
return;
RT_CK_SOLTAB(stp);
if (stp->st_specific)
rt_bot_print(stp);
}
@@ -543,25 +615,18 @@ rt_annot_shot(struct soltab *stp, struct xray *rp, struct application *ap, struc
RT_CK_RAY(rp);
RT_CK_APPLICATION(ap);
/* Annotation coverage is evaluated separately from solid partitions. */
return 0; /* MISS */
return stp->st_specific ? rt_bot_shot(stp, rp, ap, seghead) : 0;
}
/**
* Vectorized rt_annot_shot(): annotations do not create solid partitions, so
* every ray in the batch misses.
* Vectorized annotation shooting uses the scalar wrapper so view-space
* annotations without prepared geometry continue to miss safely.
*/
C_DECL void
rt_annot_vshot(struct soltab **stp, struct xray **UNUSED(rp), struct seg *segp, int n, struct application *ap)
rt_annot_vshot(struct soltab **stp, struct xray **rp, struct seg *segp, int n, struct application *ap)
{
int i;
if (ap) RT_CK_APPLICATION(ap);
for (i = 0; i < n; i++) {
if (stp[i] == 0) continue; /* skip this ray */
segp[i].seg_stp = (struct soltab *)0; /* always MISS */
}
rt_vshot_via_shot(rt_annot_shot, stp, rp, segp, n, ap);
}
@@ -578,6 +643,10 @@ rt_annot_norm(struct hit *hitp, struct soltab *stp, struct xray *rp)
if (stp) RT_CK_SOLTAB(stp);
RT_CK_RAY(rp);
if (stp && stp->st_specific) {
rt_bot_norm(hitp, stp, rp);
return;
}
VJOIN1(hitp->hit_point, rp->r_pt, hitp->hit_dist, rp->r_dir);
}
@@ -594,6 +663,10 @@ rt_annot_curve(struct curvature *cvp, struct hit *hitp, struct soltab *stp)
RT_CK_HIT(hitp);
if (stp) RT_CK_SOLTAB(stp);
if (stp && stp->st_specific) {
rt_bot_curve(cvp, hitp, stp);
return;
}
cvp->crv_c1 = cvp->crv_c2 = 0;
bn_vec_ortho(cvp->crv_pdir, hitp->hit_normal);
@@ -608,13 +681,19 @@ rt_annot_uv(struct application *ap, struct soltab *stp, struct hit *hitp, struct
if (hitp) RT_CK_HIT(hitp);
if (!uvp)
return;
if (stp && stp->st_specific)
rt_bot_uv(ap, stp, hitp, uvp);
}
C_DECL void
rt_annot_free(struct soltab *stp)
{
if (stp) RT_CK_SOLTAB(stp);
if (!stp)
return;
RT_CK_SOLTAB(stp);
if (stp->st_specific)
rt_bot_free(stp);
}
@@ -1526,29 +1605,6 @@ seg_to_vlist(struct bu_list *vlfree, struct bu_list *vhead, const struct bg_tess
}
int
rt_annot_segment_vlist(struct bu_list *vlfree, struct bu_list *vhead,
const struct bg_tess_tol *ttol,
const struct rt_annot_internal *annot_ip, size_t segment)
{
struct rt_annot_internal local;
point_t base = VINIT_ZERO;
if (!vlfree || !vhead || !ttol || !annot_ip ||
segment >= annot_ip->ant.count || !annot_ip->ant.segments ||
!annot_ip->ant.segments[segment])
return 1;
RT_ANNOT_CK_MAGIC(annot_ip);
local = *annot_ip;
local.flags = RT_ANNOT_SCREEN_SPACE;
VSETALL(local.V, 0.0);
return seg_to_vlist(vlfree, vhead, ttol, base, &local,
annot_ip->ant.segments[segment], annot_ip->styles ?
&annot_ip->styles[segment] : NULL);
}
static int
annot_is_fill_compatibility_outline(const struct rt_ant *ant, size_t seg_no)
{
@@ -1635,6 +1691,489 @@ ant_to_vlist(struct bu_list *vlfree, struct bu_list *vhead, const struct bg_tess
}
static void
annot_mesh_free(struct annot_mesh *mesh)
{
if (!mesh)
return;
if (mesh->vertices)
bu_free(mesh->vertices, "annotation mesh vertices");
if (mesh->faces)
bu_free(mesh->faces, "annotation mesh faces");
if (mesh->thickness)
bu_free(mesh->thickness, "annotation mesh thickness");
memset(mesh, 0, sizeof(*mesh));
}
static int
annot_mesh_reserve_vertices(struct annot_mesh *mesh, size_t additional)
{
size_t capacity;
size_t required;
if (additional > SIZE_MAX - mesh->vertex_count)
return 1;
required = mesh->vertex_count + additional;
if (required <= mesh->vertex_capacity)
return 0;
capacity = mesh->vertex_capacity ? mesh->vertex_capacity : 64;
while (capacity < required) {
if (capacity > SIZE_MAX / 2) {
capacity = required;
break;
}
capacity *= 2;
}
if (capacity > SIZE_MAX / sizeof(point_t))
return 1;
mesh->vertices = (point_t *)bu_realloc(mesh->vertices,
capacity * sizeof(point_t), "annotation mesh vertices");
mesh->vertex_capacity = capacity;
return 0;
}
static int
annot_mesh_reserve_faces(struct annot_mesh *mesh, size_t additional)
{
size_t capacity;
size_t required;
if (additional > SIZE_MAX - mesh->face_count)
return 1;
required = mesh->face_count + additional;
if (required <= mesh->face_capacity)
return 0;
capacity = mesh->face_capacity ? mesh->face_capacity : 96;
while (capacity < required) {
if (capacity > SIZE_MAX / 2) {
capacity = required;
break;
}
capacity *= 2;
}
if (capacity > SIZE_MAX / (3 * sizeof(int)) ||
capacity > SIZE_MAX / sizeof(fastf_t))
return 1;
mesh->faces = (int *)bu_realloc(mesh->faces,
capacity * 3 * sizeof(int), "annotation mesh faces");
mesh->thickness = (fastf_t *)bu_realloc(mesh->thickness,
capacity * sizeof(fastf_t), "annotation mesh thickness");
mesh->face_capacity = capacity;
return 0;
}
static int
annot_mesh_add_triangle(struct annot_mesh *mesh, const point_t a,
const point_t b, const point_t c, const vect_t normal, fastf_t thickness,
const struct bn_tol *tol)
{
point_t ordered[3];
vect_t ab, ac, bc, face_normal;
size_t base;
if (VINVALID(a) || VINVALID(b) || VINVALID(c)) {
bu_log("annotation mesh contains a non-finite triangle\n");
return 1;
}
VSUB2(ab, b, a);
VSUB2(ac, c, a);
VSUB2(bc, c, b);
VCROSS(face_normal, ab, ac);
if (INVALID(MAGSQ(ab)) || INVALID(MAGSQ(ac)) || INVALID(MAGSQ(bc)) ||
INVALID(MAGSQ(face_normal))) {
bu_log("annotation mesh triangle exceeds the numeric range\n");
return 1;
}
if (MAGNITUDE(face_normal) <= tol->dist_sq)
return 0;
VMOVE(ordered[0], a);
if (VDOT(face_normal, normal) >= 0.0) {
VMOVE(ordered[1], b);
VMOVE(ordered[2], c);
} else {
VMOVE(ordered[1], c);
VMOVE(ordered[2], b);
}
if (!mesh || mesh->vertex_count > (size_t)INT_MAX - 3 ||
annot_mesh_reserve_vertices(mesh, 3) ||
annot_mesh_reserve_faces(mesh, 1))
return 1;
base = mesh->vertex_count;
VMOVE(mesh->vertices[base], ordered[0]);
VMOVE(mesh->vertices[base + 1], ordered[1]);
VMOVE(mesh->vertices[base + 2], ordered[2]);
mesh->vertex_count += 3;
mesh->faces[3 * mesh->face_count] = (int)base;
mesh->faces[3 * mesh->face_count + 1] = (int)base + 1;
mesh->faces[3 * mesh->face_count + 2] = (int)base + 2;
mesh->thickness[mesh->face_count++] = thickness;
return 0;
}
static int
annot_mesh_add_stroke_span(struct annot_mesh *mesh, const point_t start,
const point_t end, const vect_t normal, fastf_t width,
const struct bn_tol *tol)
{
point_t corners[4];
point_t first, last;
vect_t direction, side;
fastf_t half_width;
fastf_t length;
VSUB2(direction, end, start);
length = MAGNITUDE(direction);
if (INVALID(length))
return 1;
if (length <= tol->dist)
return 0;
VSCALE(direction, direction, 1.0 / length);
VCROSS(side, normal, direction);
if (VINVALID(side))
return 1;
if (MAGNITUDE(side) <= SMALL_FASTF)
return 0;
VUNITIZE(side);
half_width = 0.5 * width;
VJOIN1(first, start, -half_width, direction);
VJOIN1(last, end, half_width, direction);
VJOIN1(corners[0], first, -half_width, side);
VJOIN1(corners[1], last, -half_width, side);
VJOIN1(corners[2], last, half_width, side);
VJOIN1(corners[3], first, half_width, side);
if (annot_mesh_add_triangle(mesh, corners[0], corners[1], corners[2],
normal, width, tol))
return 1;
return annot_mesh_add_triangle(mesh, corners[0], corners[2], corners[3],
normal, width, tol);
}
static void
annot_line_pattern(uint32_t pattern, const fastf_t **intervals,
size_t *interval_count)
{
/* Entries alternate mark and gap lengths in stroke-width units. */
static const fastf_t dashed[] = {8.0, 4.0};
static const fastf_t dotted[] = {1.0, 3.0};
static const fastf_t center[] = {8.0, 3.0, 2.0, 3.0};
static const fastf_t phantom[] = {8.0, 3.0, 2.0, 3.0, 2.0, 3.0};
*intervals = NULL;
*interval_count = 0;
switch (pattern) {
case RT_ANNOT_LINE_DASHED:
*intervals = dashed;
*interval_count = sizeof(dashed) / sizeof(dashed[0]);
break;
case RT_ANNOT_LINE_DOTTED:
*intervals = dotted;
*interval_count = sizeof(dotted) / sizeof(dotted[0]);
break;
case RT_ANNOT_LINE_CENTER:
*intervals = center;
*interval_count = sizeof(center) / sizeof(center[0]);
break;
case RT_ANNOT_LINE_PHANTOM:
*intervals = phantom;
*interval_count = sizeof(phantom) / sizeof(phantom[0]);
break;
default:
break;
}
}
static int
annot_mesh_add_stroke(struct annot_mesh *mesh, const point_t start,
const point_t end, const vect_t normal, fastf_t width, uint32_t pattern,
fastf_t *path_distance, const struct bn_tol *tol)
{
const fastf_t *intervals;
size_t interval_count;
vect_t delta;
fastf_t length;
fastf_t period = 0.0;
fastf_t position = 0.0;
fastf_t phase;
size_t interval = 0;
size_t i;
VSUB2(delta, end, start);
length = MAGNITUDE(delta);
if (INVALID(length))
return 1;
if (length <= tol->dist)
return 0;
annot_line_pattern(pattern, &intervals, &interval_count);
if (!interval_count) {
*path_distance += length;
return annot_mesh_add_stroke_span(mesh, start, end, normal, width, tol);
}
for (i = 0; i < interval_count; ++i)
period += intervals[i] * width;
phase = fmod(*path_distance, period);
while (phase >= intervals[interval] * width) {
phase -= intervals[interval] * width;
interval = (interval + 1) % interval_count;
}
while (position < length) {
fastf_t available = intervals[interval] * width - phase;
fastf_t run = available < length - position ? available : length - position;
if (!(interval & 1) && run > tol->dist) {
point_t run_start, run_end;
VJOIN1(run_start, start, position / length, delta);
VJOIN1(run_end, start, (position + run) / length, delta);
if (annot_mesh_add_stroke_span(mesh, run_start, run_end, normal,
width, tol))
return 1;
}
position += run;
phase = 0.0;
interval = (interval + 1) % interval_count;
}
*path_distance += length;
return 0;
}
static fastf_t
annot_default_width(const struct rt_annot_internal *annot_ip,
const struct bn_tol *tol)
{
fastf_t largest_text = 0.0;
fastf_t local_width = 0.0;
fastf_t plane_scale;
point2d_t minimum, maximum;
vect_t normal;
size_t i;
for (i = 0; i < annot_ip->ant.count; ++i) {
if (annot_ip->ant.segments[i] &&
*(uint32_t *)annot_ip->ant.segments[i] == ANN_TSEG_MAGIC) {
const struct txt_seg *text =
(const struct txt_seg *)annot_ip->ant.segments[i];
if (text->txt_size > largest_text)
largest_text = text->txt_size;
}
}
if (largest_text > 0.0) {
local_width = largest_text * ANNOT_TEXT_STROKE_RATIO;
} else if (annot_ip->vert_count) {
V2MOVE(minimum, annot_ip->verts[0]);
V2MOVE(maximum, annot_ip->verts[0]);
for (i = 1; i < annot_ip->vert_count; ++i) {
V_MIN(minimum[X], annot_ip->verts[i][X]);
V_MIN(minimum[Y], annot_ip->verts[i][Y]);
V_MAX(maximum[X], annot_ip->verts[i][X]);
V_MAX(maximum[Y], annot_ip->verts[i][Y]);
}
local_width = hypot(maximum[X] - minimum[X],
maximum[Y] - minimum[Y]) * ANNOT_GEOMETRY_STROKE_RATIO;
}
VCROSS(normal, annot_ip->u_vec, annot_ip->v_vec);
plane_scale = sqrt(MAGNITUDE(normal));
local_width *= plane_scale;
if (local_width < ANNOT_MIN_WIDTH_TOL_FACTOR * tol->dist)
local_width = ANNOT_MIN_WIDTH_TOL_FACTOR * tol->dist;
return local_width;
}
static int
annot_segment_mesh(struct annot_mesh *mesh,
const struct rt_annot_internal *annot_ip, size_t segment,
const struct bg_tess_tol *ttol, const struct bn_tol *tol,
const vect_t normal, fastf_t base_width)
{
struct bu_list vhead;
struct bu_list vlfree;
struct bv_vlist *vp;
const struct rt_annot_seg_style *style = annot_ip->styles ?
&annot_ip->styles[segment] : NULL;
uint32_t magic = *(uint32_t *)annot_ip->ant.segments[segment];
uint32_t pattern = style ? style->line_pattern : RT_ANNOT_LINE_CONTINUOUS;
fastf_t width = base_width;
point_t line_start = VINIT_ZERO;
point_t polygon[3];
fastf_t path_distance = 0.0;
size_t polygon_count = 0;
int have_line_start = 0;
int ret = 0;
if (style && (style->flags & RT_ANNOT_STYLE_WIDTH))
width *= style->line_width;
else if (style && magic == ANN_TSEG_MAGIC &&
(style->flags & RT_ANNOT_STYLE_BOLD))
width *= 2.0;
if (!isfinite(width) || width <= 0.0)
return 1;
BU_LIST_INIT(&vhead);
BU_LIST_INIT(&vlfree);
ret = seg_to_vlist(&vlfree, &vhead, ttol,
(fastf_t *)annot_ip->V, (struct rt_annot_internal *)annot_ip,
annot_ip->ant.segments[segment], style);
if (ret)
goto cleanup;
for (BU_LIST_FOR(vp, bv_vlist, &vhead)) {
size_t i;
for (i = 0; i < vp->nused; ++i) {
switch (vp->cmd[i]) {
case BV_VLIST_LINE_MOVE:
VMOVE(line_start, vp->pt[i]);
have_line_start = 1;
path_distance = 0.0;
break;
case BV_VLIST_LINE_DRAW:
if (have_line_start && annot_mesh_add_stroke(mesh,
line_start, vp->pt[i], normal, width, pattern,
&path_distance, tol)) {
ret = 1;
goto cleanup;
}
VMOVE(line_start, vp->pt[i]);
have_line_start = 1;
break;
case BV_VLIST_POLY_MOVE:
case BV_VLIST_TRI_MOVE:
VMOVE(polygon[0], vp->pt[i]);
polygon_count = 1;
break;
case BV_VLIST_POLY_DRAW:
case BV_VLIST_TRI_DRAW:
if (polygon_count < 3) {
VMOVE(polygon[polygon_count], vp->pt[i]);
polygon_count++;
}
break;
case BV_VLIST_POLY_END:
case BV_VLIST_TRI_END:
if (polygon_count == 3 && annot_mesh_add_triangle(mesh,
polygon[0], polygon[1], polygon[2], normal,
base_width, tol)) {
ret = 1;
goto cleanup;
}
polygon_count = 0;
break;
default:
break;
}
}
}
cleanup:
BV_FREE_VLIST(&vlfree, &vhead);
bv_vlist_cleanup(&vlfree);
return ret;
}
static int
annot_to_bot(struct rt_bot_internal **result,
const struct rt_annot_internal *annot_ip,
const struct bg_tess_tol *ttol, const struct bn_tol *tol,
unsigned char bot_mode)
{
struct annot_mesh mesh = {0};
struct rt_bot_internal *bot;
vect_t normal;
fastf_t base_width;
size_t i;
if (!result)
return 1;
*result = NULL;
if (!annot_ip || !ttol || !tol ||
(bot_mode != RT_BOT_PLATE && bot_mode != RT_BOT_SURFACE) ||
!(annot_ip->flags & RT_ANNOT_MODEL_SPACE))
return 1;
VCROSS(normal, annot_ip->u_vec, annot_ip->v_vec);
if (VINVALID(normal) || MAGNITUDE(normal) <= SMALL_FASTF)
return 1;
VUNITIZE(normal);
base_width = annot_default_width(annot_ip, tol);
if (!isfinite(base_width) || base_width <= 0.0)
return 1;
for (i = 0; i < annot_ip->ant.count; ++i) {
if (!annot_ip->ant.segments[i] ||
annot_is_fill_compatibility_outline(&annot_ip->ant, i))
continue;
if (annot_segment_mesh(&mesh, annot_ip, i, ttol, tol, normal,
base_width)) {
annot_mesh_free(&mesh);
return 1;
}
}
if (!mesh.vertex_count || !mesh.face_count) {
annot_mesh_free(&mesh);
return 1;
}
BU_ALLOC(bot, struct rt_bot_internal);
bot->magic = RT_BOT_INTERNAL_MAGIC;
bot->mode = bot_mode;
bot->orientation = RT_BOT_UNORIENTED;
bot->num_vertices = mesh.vertex_count;
bot->vertices = (fastf_t *)mesh.vertices;
bot->num_faces = mesh.face_count;
bot->faces = mesh.faces;
if (bot_mode == RT_BOT_PLATE)
bot->thickness = mesh.thickness;
else
bu_free(mesh.thickness, "annotation mesh thickness");
mesh.vertices = NULL;
mesh.faces = NULL;
mesh.thickness = NULL;
*result = bot;
return 0;
}
C_DECL int
rt_annot_tess(struct nmgregion **r, struct model *m,
struct rt_db_internal *ip, const struct bg_tess_tol *ttol,
const struct bn_tol *tol)
{
struct rt_bot_internal *bot = NULL;
struct rt_db_internal bot_intern;
const struct rt_annot_internal *annot_ip;
int ret;
if (!r || !m || !ip || !ttol || !tol)
return -1;
RT_CK_DB_INTERNAL(ip);
annot_ip = (const struct rt_annot_internal *)ip->idb_ptr;
if (rt_annot_validate(annot_ip, NULL) ||
annot_to_bot(&bot, annot_ip, ttol, tol, RT_BOT_SURFACE))
return -1;
RT_DB_INTERNAL_INIT(&bot_intern);
bot_intern.idb_major_type = DB5_MAJORTYPE_BRLCAD;
bot_intern.idb_type = ID_BOT;
bot_intern.idb_meth = &OBJ[ID_BOT];
bot_intern.idb_ptr = bot;
ret = rt_bot_tess(r, m, &bot_intern, ttol, tol);
rt_bot_ifree(&bot_intern);
return ret;
}
C_DECL int
rt_annot_plot(struct bu_list *vhead, struct rt_db_internal *ip, const struct bg_tess_tol *ttol, const struct bn_tol *UNUSED(tol), const struct bview *UNUSED(info))
{
@@ -3527,11 +4066,11 @@ rt_annot_adjust(struct bu_vls *logstr, struct rt_db_internal *intern, int argc,
fastf_t *new_vert;
vert_no = atol(argv[0] + 1);
if (vert_no < 0 || (size_t)vert_no >= annot_ip->vert_count) {
new_vert = annot_ip->verts[vert_no];
if (vert_no < 0 || (size_t)vert_no > annot_ip->vert_count) {
bu_vls_printf(logstr, "ERROR: Illegal vertex number\n");
return BRLCAD_ERROR;
}
new_vert = annot_ip->verts[vert_no];
array_len = 2;
if (_rt_tcl_list_to_fastf_array(argv[1], &new_vert, &array_len) != array_len) {
bu_vls_printf(logstr, "ERROR: Incorrect number of coordinates for vertex\n");

Some files were not shown because too many files have changed in this diff Show More