An AutoCAD graph clipping method based on two-stage grid index and local calculation, a computer device and a storage medium
Patent Information
- Application Number
- CN202611023152.2
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-10
- Publication Date
- 2026-10-30
AI Technical Summary
[0007]本发明的目的在于克服现有技术的不足,提供一种基于两阶段网格索引和局部计算的AutoCAD图形裁剪方法、计算机设备及存储介质,以解决现有网格类裁剪方法中网格粒度评价准则维度单一、不精确且多为各向同性,难以匹配狭长或复杂边界而造成网格过密或过疏的问题,以及网格索引一经建立即固定、与快速筛选及裁剪过程相互独立、缺乏运行时反馈,对图形对象空间分布不均的图纸适应性差、无法兼顾索引内存与剔除效率的问题
其一,显著提升性能:快速预筛选阶段可排除百分之七十至百分之九十的图形对象,极大减轻精确计算负担;通过网格索引将O(N×M)的全局求交复杂度降低为近乎O(NlogM)或更优的局部求交,在面对大量图形对象或复杂边界时性能提升尤为明显。
Smart Images

Figure CN123013198A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of computer-aided design technology, and in particular to a graphic clipping method, computer device and storage medium based on two-stage grid indexing and local calculation in the AutoCAD environment. Background Technology
[0002] In computer-aided design software such as AutoCAD, graphic clipping is a core editing function used to delete portions of a graphic outside a specified clipping boundary. Traditional graphic clipping methods employ an algorithm that finds the intersection of the boundary with each object one by one. Each candidate object needs to undergo precise geometric intersection with the complex clipping boundary, resulting in a computational complexity of O(N×M), where N is the number of graphic objects and M is the boundary complexity. This type of method suffers from low computational efficiency, high CPU and memory consumption, and difficulty in finding intersections with complex objects such as spline curves, ellipses, and filled patterns.
[0003] Existing general-purpose graphics clipping algorithms, such as the Cohen-Sutherland line clipping algorithm, Liang-Barsky algorithm, Sutherland-Hodgman algorithm, Weiler-Atherton algorithm, Greiner-Hormann algorithm, and Vatti algorithm, mostly employ global traversal, resulting in computational complexity that increases linearly or even quadratically with the number of graphic objects. Research shows that intersection calculations in polygon clipping often account for approximately 80% of the total runtime, and some algorithms struggle with degenerate intersections where vertices fall on edges. When dealing with the massive amounts of graphic data in AutoCAD, these algorithms fall short of performance requirements.
[0004] In all mesh-based methods, mesh granularity, i.e., the size of the mesh cells, has a decisive impact on performance: overly dense meshes waste memory and increase mesh enumeration overhead, while overly sparse meshes result in too many boundary segments within each mesh, leading to filtering failure. However, existing technologies determine mesh granularity in a rather coarse manner: First, many methods employ empirical rules based on a single variable, such as using the average side length of all edges as the mesh size, or requiring the mesh size to be no less than 1.5 times the maximum object size; second, a few methods use a cost function that minimizes numerical values, combining the minimum bounding rectangle size of the object, the query window size, and the mesh size to find the optimal mesh size, but this is a numerical search rather than a closed-form expression, and it uses isotropic square meshes, without incorporating physical quantities such as boundary complexity density, aspect ratio, and object density; third, a simpler approach is to directly choose between two fixed mesh sizes based on whether the graphic range exceeds a certain fixed threshold. Furthermore, once the aforementioned mesh is built based on the static properties of the clipping boundary, it is used in a fixed manner and is independent of the subsequent rapid filtering and clipping processes. It is impossible to provide feedback correction to the mesh granularity based on geometric statistics such as the actual rejection rate, average number of intersections, and mesh load distribution generated during runtime.
[0005] Therefore, the existing technology has at least the following drawbacks: First, the evaluation criteria for mesh granularity are singular and imprecise: existing methods for determining granularity mostly rely on single empirical variables or numerical searches, without integrating multiple physical quantities such as boundary complexity density, aspect ratio of graphics, and object density. Moreover, they mostly use isotropic square meshes, which are difficult to match narrow or complex clipping boundaries, easily leading to meshes that are too dense or too sparse. Secondly, the construction of the grid index is independent of the fast filtering and clipping process and lacks feedback: once the grid is established, it is used in a fixed way. It cannot adaptively adjust the grid granularity based on the rejection rate, the average number of boundary segments per object intersection, and the grid load distribution during runtime. It has poor adaptability to drawings with uneven spatial distribution of graphic objects and it is difficult to balance index memory and rejection efficiency at the same time. Third, classic clipping algorithms use global traversal, and the complexity increases with the number of objects. Intersection calculations account for a high proportion, and the grid methods of geographic information systems are geared towards raster or point cloud data, making it difficult to directly apply to the accurate clipping of various types of vector primitives in AutoCAD.
[0006] Therefore, it is necessary to develop a fast AutoCAD drawing clipping method that features adaptive grid granularity, coupled indexing and filtering clipping, and strong versatility. Summary of the Invention
[0007] The purpose of this invention is to overcome the shortcomings of the prior art and provide an AutoCAD graphic clipping method, computer device, and storage medium based on two-stage grid indexing and local calculation. This invention addresses the problems in existing grid-based clipping methods, such as the single-dimensional, inaccurate, and mostly isotropic grid granularity evaluation criteria, which makes it difficult to match narrow or complex boundaries, resulting in grids that are too dense or too sparse. It also addresses the problems that the grid index is fixed once established, is independent of the fast filtering and clipping process, lacks runtime feedback, has poor adaptability to drawings with uneven spatial distribution of graphic objects, and cannot balance index memory and clipping efficiency.
[0008] To achieve the above objectives, the present invention adopts the following technical solution.
[0009] An AutoCAD drawing clipping method based on two-stage grid indexing and local calculation includes the following steps: An AutoCAD graphic clipping method based on two-stage mesh indexing and local computation is proposed. The method involves obtaining a closed two-dimensional polyline from the AutoCAD database as the clipping boundary, discretizing the clipping boundary into boundary segments, and calculating the circumscribed rectangle of the clipping boundary. The mesh granularity is determined based on the number of graphic objects to be clipped and the geometric quantities of the boundary segments and the circumscribed rectangle. A two-dimensional mesh is established on the circumscribed rectangle using the specified mesh granularity, and a mesh index table is created to map mesh coordinates to boundary segments passing through the mesh. At least a portion of the graphic objects to be clipped undergo trial processing, and the mesh granularity is updated according to a preset feedback correction formula based on the geometric screening statistics obtained from the trial processing. The mesh index relationship table is rebuilt, and the update is repeated until the relative change of the mesh granularity is less than the convergence threshold or the number of iterations reaches the upper limit, so that the determination of the mesh granularity and the selection and clipping of the graphic objects form a closed loop coupling; the graphic objects to be clipped are traversed, and for each graphic object, the set of meshes covered by its bounding box is compared with the mesh coordinate range of the circumscribed rectangle, or the mesh index relationship table is queried to determine and delete graphic objects located outside the clipping boundary; for graphic objects that are not deleted, the mesh index relationship table is queried to obtain the subset of boundary line segments related to the mesh they occupy, and the precise geometric intersection and clipping operation with the graphic object is performed only on the subset of boundary line segments.
[0010] Preferably, the formula for determining the grid granularity is:
[0011] In the formula, g base As the reference granularity, A box The area of the circumscribed rectangle and satisfying W box With H box The width and height of the circumscribed rectangle are respectively, Lb n is the total length of all the boundary segments. seg N represents the total number of all the aforementioned boundary segments. obj The number of graphic objects to be clipped is κ, which is a tuning coefficient ranging from 0.6 to 1.4. The reference granularity is decomposed into x-direction granularity Δ based on the aspect ratio of the circumscribed rectangle using the following formula. x granularity Δ in the y direction y :
[0012]
[0013] This decomposition maintains the area of the mesh cells equal to the square of the reference granularity and makes the number of meshes in the row and column directions comparable, thereby significantly reducing empty meshes under narrow boundaries; subsequently, Δ x With Δ y Round each element down to the preset granularity lower limit g. min With the upper limit of particle size g max between.
[0014] Preferably, the feedback correction formula is:
[0015] In the formula, g base (t) The value of the t-th iteration of the baseline granularity. The value of the baseline granularity in the (t+1)th iteration is used, and both are updated according to the above formula, m avg η rej D load These represent the average number of boundary segments per object intersection, the rejection rate, and the variance of the hit grid load, respectively, obtained from the t-th iteration. tar η tar D tar These are their target values, and γ is the feedback gain coefficient; iteration stops when the following equation is satisfied:
[0016] In the formula, ε conv The convergence threshold is defined as follows: the target value of the rejection rate is 0.80 to 0.90; the target value of the average number of boundary segments intersected per object is 8 to 16; γ is 0.2 to 0.5; the convergence threshold is 0.02 to 0.05; and the upper limit of the number of iterations is 2 to 3.
[0017] Preferably, the graphic object includes a fill pattern, and the precise geometric intersection and clipping operation for the fill pattern further includes: extracting at least one boundary loop of the fill pattern; treating each boundary loop as a closed two-dimensional polyline, recursively applying the boundary discretization, grid index construction, and precise intersection clipping processing method of the present invention to clip it, obtaining at least one new boundary loop after clipping; and regenerating a new fill pattern object using all the new boundary loops obtained after clipping, and setting the same style attributes as the fill pattern.
[0018] Preferably, the recursive application of the boundary discretization, grid indexing construction, and precise intersection clipping method to clip each boundary loop as a closed two-dimensional polyline is specifically a bidirectional sequential clipping method, including: a first clipping step, performing clipping with the boundary loop as the clipping object and the clipping boundary as the clipping boundary; a second clipping step, performing clipping with the clipping boundary as the clipping object and the boundary loop as the clipping boundary; and a loop synthesis step, merging all boundary segments obtained from the two clipping steps to form a new clipped boundary loop.
[0019] Preferably, before calculating the circumscribed rectangle, a primitive standardization step is included: converting the three-dimensional polyline objects and two-dimensional polyline objects in the AutoCAD database into lightweight polyline objects to unify the data format for subsequent intersection calculations.
[0020] Preferably, when determining graphic objects located outside the clipping boundary, multiple graphic objects to be clipped are simultaneously subjected to mesh coverage judgment and filtering through parallel computing.
[0021] Preferably, establishing the grid index relationship table includes calculating all grids traversed by each of the boundary segments using the ray stepping method, and the grid index relationship table maps grid coordinates to a set of indices of boundary segments that traverse the grid.
[0022] Preferably, determining and deleting graphic objects located outside the clipping boundary includes: when the maximum row coordinate of the grid set covered by the graphic object is less than the minimum row coordinate of the circumscribed rectangle, or the minimum row coordinate is greater than the maximum row coordinate of the circumscribed rectangle, or the maximum column coordinate is less than the minimum column coordinate of the circumscribed rectangle, or the minimum column coordinate is greater than the maximum column coordinate of the circumscribed rectangle, the graphic object is determined to be outside the clipping boundary and deleted; when the above conditions are not met, the grid index relationship table is further queried, and if the grid set has no intersection with any grid with the recorded boundary line segments, the graphic object is determined to be outside the clipping boundary and deleted.
[0023] Preferably, the precise geometric intersection and clipping operation includes: calculating the intersection points of the graphic object and the subset of boundary line segments; removing duplicates from the intersection points; deleting one of the intersection points when the distance between two intersection points is less than a tolerance threshold; segmenting the graphic object based on the deduplicated intersection points to obtain segmented sub-objects; and calculating the midpoint of the sub-objects, and determining whether to retain or delete the sub-objects by judging the positional relationship between the midpoint and the clipping boundary.
[0024] Preferably, the graphic object further includes at least one of the following: circle, arc, spline curve, ellipse, text, and block.
[0025] Preferably, when establishing the grid index relationship table, a sorted index dictionary is also established. The key of the sorted index dictionary is the grid row coordinate, and the value is the starting search position of the row coordinate in the grid index relationship table, which is used to accelerate grid queries.
[0026] The present invention also provides a computer device, including a memory, a processor, and a computer program stored in the memory and capable of running on the processor, wherein the processor executes the computer program to implement the steps of any of the methods described above.
[0027] The present invention also provides a computer-readable storage medium having a computer program stored thereon, wherein the computer program, when executed by a processor, implements the steps of any of the methods described above.
[0028] The beneficial effects of this invention are as follows: Firstly, it significantly improves performance: the rapid pre-screening stage can eliminate 70% to 90% of graphic objects, greatly reducing the burden of precise calculation; the grid index reduces the global intersection complexity of O(N×M) to nearly O(NlogM) or better local intersection, and the performance improvement is particularly obvious when facing a large number of graphic objects or complex boundaries.
[0029] Secondly, it has strong universality: the method does not depend on a specific graphic type and can handle various AutoCAD elements such as lines, curves, text, and fills, and has wide applicability.
[0030] Third, high accuracy: the rapid screening stage is only used to exclude objects that are obviously located on the outside, and the precise cropping stage still uses a strict geometric algorithm to ensure the accuracy of the cropping results.
[0031] Fourth, it is resource-friendly: it reduces a lot of unnecessary complex calculations, lowers the peak consumption of CPU and memory, reduces memory usage by more than 60%, and significantly reduces the peak CPU utilization.
[0032] Fifth, the mesh granularity is adaptive and anisotropic: the mesh granularity formula integrates the area of the circumscribed rectangle, the total number and length of the boundary line segments, and the number of objects, and incorporates the aspect ratio through anisotropic decomposition, outputting anisotropic meshes with a comparable number of meshes in the row and column directions. Compared with the existing granularity determination methods of single-variable empirical rules, numerical search cost functions, and isotropic meshes, it is more accurate and can significantly reduce empty meshes.
[0033] Sixth, closed-loop self-tuning: Based on the rejection rate during runtime, the average number of boundary segments intersecting per object, and the variance of the hit grid load, the baseline granularity is corrected in reverse and the index is rebuilt. It can self-tune any drawing without manually setting the grid size.
[0034] It is particularly important to point out that the overall technical effect produced by the coupling of the grid granularity formula and the closed-loop feedback adjustment step surpasses the simple sum of the effects of implementing them individually. When the grid granularity formula is used alone, it only calculates the granularity based on the static properties of the bounding rectangle and the boundary, as well as the total number of objects. It cannot perceive the actual spatial distribution of the graphic objects to be clipped relative to the clipping boundary, and often under-screens or over-screens unevenly distributed drawings. When the closed-loop feedback is used alone and adjusted from any initial value, such as a fixed empirical threshold, each iteration requires a complete index reconstruction and trial processing, and it is prone to oscillation and slow convergence when the variance of the hit grid load is large. After the two are coupled, the grid granularity formula provides the feedback loop with a near-optimal initial value that has captured the static structure of the drawing, namely the sheet size, boundary complexity, and object size. The feedback loop only needs to correct the object distribution residuals that the formula cannot observe, so it usually converges within one or two iterations and simultaneously achieves the dual-optimal state of minimum index memory and highest rejection rate, that is, obtaining a grid index that can be self-tuned for any drawing without manual grid setting. This synergistic effect of near-optimal initial value plus a small amount of feedback correction is something that cannot be obtained by implementing the grid granularity formula alone or implementing the closed-loop feedback alone. Attached Figure Description
[0035] Figure 1 This is a flowchart illustrating the overall process of the method of the present invention. Figure 2 A schematic diagram for constructing the clipping boundary mesh index; Figure 3 A schematic diagram illustrating the construction of a grid index for graphic objects to be clipped and a method for quick filtering; Figure 4 A diagram illustrating how to quickly filter graphic objects using a grid; Figure 5 This is a flowchart for trimming the fill pattern; Figure 6 This is a signal flow diagram of the grid granularity formula and the closed-loop feedback adjustment step; Figure 7This is a schematic diagram comparing the isotropic mesh with the anisotropic mesh of the present invention. Detailed Implementation
[0036] The present invention will now be described in detail with reference to the accompanying drawings and embodiments. It should be understood that the specific embodiments described herein are merely illustrative of the invention and are not intended to limit the invention.
[0037] like Figure 1 , Figure 6 As shown, this invention provides an AutoCAD drawing clipping method based on two-stage grid indexing and local calculation. The method includes: obtaining a closed two-dimensional polyline from the AutoCAD database as the clipping boundary; discretizing the clipping boundary into boundary segments and calculating the circumscribed rectangle of the clipping boundary; determining the grid granularity based on the number of drawing objects to be clipped and the geometric quantities of the boundary segments and the circumscribed rectangle; establishing a two-dimensional grid on the circumscribed rectangle using the grid granularity; and establishing a grid index relationship table that maps grid coordinates to boundary segments passing through the grid; performing trial processing on at least a portion of the drawing objects to be clipped; and correcting the results according to a preset feedback based on the geometric screening statistics obtained from the trial processing. The formula updates the mesh granularity and rebuilds the mesh index table, repeating the update until the relative change in mesh granularity is less than the convergence threshold or the number of iterations reaches the upper limit, thus forming a closed-loop coupling between the determination of mesh granularity and the selection and clipping of graphic objects. It iterates through the graphic objects to be clipped, comparing the set of meshes covered by its bounding box with the mesh coordinate range of its circumscribed rectangle, or querying the mesh index table to determine and delete graphic objects located outside the clipping boundary. For graphic objects that are not deleted, the mesh index table is queried to obtain the subset of boundary segments related to the mesh they occupy, and precise geometric intersection and clipping operations are performed only on the subset of boundary segments with respect to the graphic object.
[0038] The formula for determining the mesh granularity is:
[0039] In the formula, g base As the reference granularity, A box The area of the circumscribed rectangle and satisfying W box With H box These are the width and height of the circumscribed rectangle, respectively, L b n is the total length of all boundary segments. seg N represents the total number of boundary segments. obj The number of graphic objects to be clipped is κ, which is an adjustment coefficient ranging from 0.6 to 1.4. The baseline granularity is decomposed into x-direction granularity Δ based on the aspect ratio of the circumscribed rectangle using the following formula. x granularity Δ in the y direction y :
[0040]
[0041] This decomposition maintains the area of the mesh cells equal to the square of the reference granularity and makes the number of meshes in the row and column directions of the 2D mesh comparable, thus significantly reducing empty meshes under narrow boundaries; subsequently, Δ x With Δ y Round each element down to the preset granularity lower limit g. min With the upper limit of particle size g max between.
[0042] The feedback correction formula is:
[0043] In the formula, g base (t) The value of the t-th iteration of the baseline granularity. The value of the baseline granularity in the (t+1)th iteration is used, and both are updated according to the above formula, m avg η rej D load These represent the average number of boundary segments per object intersection, the rejection rate, and the variance of the hit grid load, respectively, obtained from the t-th iteration. tar η tar D tar These are their target values, γ is the feedback gain coefficient; the hit grid refers to the grid with boundary line segments recorded in the grid index table, the load of a hit grid is the number of boundary line segments recorded in that grid, and the variance of the hit grid load is the variance of the load of all hit grids in this trial processing; the target value D of the hit grid load variance. tar The benchmark used to perform dimensionless transformation of the load variance is taken as the hit grid load variance obtained from the first trial processing statistics, that is, let D be the load variance of the hit grid obtained from the first iteration. load / D tar The expression is set to 1; iteration stops when the following expression is satisfied:
[0044] In the formula, ε conv The convergence threshold is defined as follows: the target value of the rejection rate is 0.80 to 0.90, the target value of the average number of boundary segments per object is 8 to 16, γ is 0.2 to 0.5, the convergence threshold is 0.02 to 0.05, and the upper limit of the number of iterations is 2 to 3.
[0045] The graphic object includes a fill pattern. The precise geometric intersection and clipping operation for the fill pattern further includes: extracting at least one boundary loop of the fill pattern; treating each boundary loop as a closed two-dimensional polyline, recursively applying the method of the present invention to clip it to obtain at least one new boundary loop after clipping; and regenerating a new fill pattern object using all the new boundary loops obtained after clipping, and setting the same style attributes as the fill pattern.
[0046] The method of the present invention is applied recursively for trimming, specifically a bidirectional sequential trimming method, including: a first trimming step, performing trimming with the boundary ring as the trimming object and the trimming boundary as the trimming boundary; a second trimming step, performing trimming with the trimming boundary as the trimming object and the boundary ring as the trimming boundary; and a ring synthesis step, merging all boundary segments obtained from the two trimmings to form a new trimmed boundary ring.
[0047] Before calculating the circumscribed rectangle, a primitive standardization step is also included: converting the 3D and 2D polyline objects in the AutoCAD database into lightweight polyline objects to unify the data format for subsequent intersection calculations.
[0048] When determining graphic objects located outside the clipping boundary, multiple graphic objects to be clipped are simultaneously evaluated and filtered for mesh coverage through parallel computing.
[0049] The precise geometric intersection and clipping operation includes: calculating the intersection points of the graphic object and the subset of boundary line segments; removing duplicate intersection points; deleting one of the intersection points when the distance between two intersection points is less than the tolerance threshold; segmenting the graphic object based on the deduplicated intersection points to obtain the segmented sub-objects; and calculating the midpoint of the sub-objects and determining whether to retain or delete the sub-objects by judging the positional relationship between the midpoint and the clipping boundary.
[0050] Graphical objects also include at least one of the following: circle, arc, spline curve, ellipse, text, and block.
[0051] When creating the grid index relationship table, a sorted index dictionary is also created. The key of the sorted index dictionary is the grid row coordinate, and the value is the starting search position of that row coordinate in the grid index relationship table, which is used to speed up grid queries.
[0052] refer to Figure 1 The overall implementation process of this invention includes four stages: boundary preprocessing, mesh index construction, closed-loop feedback adjustment, and graphic object processing. The derivation basis of the mesh granularity formula will be explained first, followed by specific embodiments.
[0053] Derivation of the mesh grain size formula: In a uniform mesh, let the reference grain size be g. base Then the total number of grid cells and the area A of the circumscribed rectangle are... box Proportional to gbase The cost is inversely proportional to the square of the number of grid cells; the finer the grid, the greater the cost of grid enumeration and index storage, denoted as the cost of excessive fineness being proportional to the number of grid cells; on the other hand, the number of boundary segments within each grid cell is approximately proportional to the total number of boundary segments n. seg With g base The product is then divided by the total boundary length L. b N for cutting obj When finding the intersection of each object locally, a sparser mesh results in more boundary segments for each object and renders filtering ineffective. Let the cost of this excessive sparseness be proportional to N. obj The product of g and the number of boundary segments within the cell. The cost of excessive fineness is denoted as g. base Terms inversely proportional to the square and excessively sparse costs are denoted as g. base Terms that are directly proportional, the sum of the two terms with respect to g base Taking the derivative and setting it to zero, we find that the optimal granularity is proportional to the cube root of the ratio of the two types of cost coefficients mentioned above. After simplification, we get the aforementioned grid granularity formula, where κ is the tuning coefficient that absorbs the above proportionality constant.
[0054] To match the mesh resolution with the boundary shape, the baseline granularity is decomposed into Δ based on the aspect ratio of the circumscribed rectangle. x With Δ y When the width of the circumscribed rectangle is greater than its height, Δ x Greater than Δ y This makes the number of rows and columns approximately equal. (Reference) Figure 7 For narrow and elongated boundaries, isotropic square meshes will produce a large number of empty meshes along the long side and insufficient resolution in the short side direction; while the anisotropic mesh of the present invention makes the number of rows and columns comparable while keeping the unit area unchanged, and significantly reduces empty meshes.
[0055] Example 1
[0056] This embodiment uses a large-format AutoCAD drawing as an example to illustrate the basic trimming process and the adaptive determination and closed-loop feedback process of the mesh granularity.
[0057] S1, the user starts the program using a CAD command such as CAIJIAN_DLL and selects a closed 2D polyline as the clipping boundary. The program checks its closure and removes adjacent duplicate vertices, discretizes it into end-to-end boundary segments, calculates its circumscribed rectangle, and establishes the clipping boundary mesh index as follows: Figure 2 As shown, the width W is obtained. box For 12000, high H box The total number of boundary segments is 8000, and the total number of boundary segments is n. seg The value is 400, and the total length of the boundary is L. b The number is 48000; N is the number of graphic objects to be clipped in the current database. objThe value is 10000. When preprocessing the boundary polyline, check its closure and whether it contains arc segments. If arc segments exist, fitting processing is required first. Remove adjacent duplicate vertices to simplify the boundary geometry data. Calculate the bounding box of the boundary polyline.
[0058] S2, with κ set to 1.0, calculate the reference particle size g according to the grid particle size formula. base Approximately 105; the particle size Δ in the x-direction is obtained by decomposing according to the aspect ratio. x Approximately 129, y-axis particle size Δ y The number of grid cells is approximately 86, corresponding to approximately 93 in both rows and columns, with a relatively even number of grid cells in both directions. Subsequently, a ray-stepping method, a variant of the Bresenham algorithm, is used to calculate all grid cells traversed by each boundary line segment, establishing a grid index table and a sorted index dictionary with row coordinates as keys to accelerate lookups. Furthermore, different methods are used to calculate the grid cells traversed by different types of graphic objects: for line segments, the ray-stepping method is used to traverse the grid cells they pass through; for circles, arcs, spline curves, and ellipses, their outer envelope rectangle is first calculated, then all grid cells covered by this rectangle are obtained as candidate grid cells, and finally, precise selection is performed by calculating the minimum distance between the grid cells and the graphic.
[0059] S2′, Reference Figure 3 The grid index of the graphic objects shown was used to process approximately 10% of the graphic objects, and the rejection rate η was statistically obtained. rej Approximately 0.78, average number of boundary segments per object intersecting (m) avg Approximately 20, hit grid load variance D load The load variance obtained from this statistical analysis is used as the benchmark D. tar , making D load / D tar Set the value to 1. Take the target value m. tar For 12, η tar With a value of 0.85 and γ of 0.35, the formula is calculated according to the feedback correction formula. Therefore, the reference particle size g base The index was reduced from approximately 105 to approximately 80, then decomposed and reconstructed; the second trial yielded η. rej Approximately 0.86, m avg The rejection rate is approximately 13. At this point, the rejection rate is close to the target value, and the feedback correction term within the parentheses is close to zero. According to the feedback correction formula... The baseline granularity has been updated to approximately 77, with a relative change of approximately If the value is less than the convergence threshold of 0.05, the iteration terminates. It can be seen that after two iterations, the grid granularity converges from the static initial value to a value that balances memory usage and the culling rate.
[0060] S3, the program retrieves all editable graphic objects from the database and can process them in parallel. Its fast filtering process is as follows: Figure 4 As shown. For each object, first calculate the set of grids covered by its bounding box and compare it with the grid coordinate range of the circumscribed rectangle. If its maximum row coordinate is less than the minimum row coordinate of the boundary, or the minimum row coordinate is greater than the maximum row coordinate of the boundary, or the maximum column coordinate is less than the minimum column coordinate of the boundary, or the minimum column coordinate is greater than the maximum column coordinate of the boundary, then it is directly deleted; otherwise, query the grid index relationship table. If its grid set has no intersection with the grid with the record of the boundary line segment, it is also directly deleted; for objects that are not deleted, only take the subset of boundary line segments related to the grid it occupies and find the intersection. After obtaining the intersection point, remove duplicates from the intersection point. Divide the object according to the deduplicated intersection point. Take the midpoint of each sub-object and use the ray method to determine whether it is inside the clipping boundary. If it is inside, it is retained; otherwise, it is deleted.
[0061] Taking a straight line as an example: obtain the grid that the line passes through; query the grid index and iIndexMap to find the relevant boundary segments; perform intersection calculation (IntersectWith) on the line only with this small part of the boundary segments to obtain a list of intersection points; divide the line according to the intersection points (GetSplitCurves) to generate multiple sub-segments; take the midpoint of each sub-segment, and use the ray method to determine whether the midpoint is inside the clipping boundary. If it is inside, keep it; otherwise, discard it.
[0062] Specifically, the range of grid coordinates corresponding to the bounding rectangle is calculated, including the minimum grid coordinates ( , ) and maximum grid coordinates ( , For each graphic object, obtain the minimum grid coordinates of its bounding box covering grid set. , ) and maximum grid coordinates ( , If one of the following conditions is met: < (The object is completely to the left of the boundary), or > (Right side), or < (below), or > If the object is located (above), it is determined that the object is completely outside the clipping boundary and is directly deleted without any geometric calculations.
[0063] In this embodiment, the grid index relationship table uses the data structure GridSegment to represent the mapping between grid coordinates and boundary segment indices, and the intersection points and their positions on the segments are represented by the data structure PointBXYDis; the baseline granularity can be adaptively determined according to the aforementioned grid granularity formula. The above data structure definitions and core code framework are as follows (illustrated using C#): / / Key data structure definitions public class GridSegment { public int I { get; set;} / / Grid row coordinates public int J { get; set;} / / Grid column coordinates public int SegmentIndex { get; set;} / / Boundary segment index public LineSegment2d Segment { get; set;} / / Line segment geometry data } public class PointBXYDis { public int SegmentIndex { get; set;} / / Index of the boundary segment public double X { get; set;} / / X coordinates of the intersection point public double Y { get; set;} / / Y-coordinate of the intersection point public double Distance { get; set;} / / Distance on the line segment } public void CAIJIAN_DLL() { / / S1 Boundary Preprocessing Polyline pline = GetClipBoundary(); RemoveAdjacentDuplicateVertices(pline); Extents3d bbox = pline.Bounds.Value; List <linesegment2d>segs = GetPolylineSegments(pline); / / S2 Adaptive Anisotropic Mesh Granularity int Nobj = GetAllEditableObjects().Count; (double dx, double dy) = CalcAnisotropicGrid(bbox, segs, Nobj,kappa: 1.0); GridIndex index = BuildGridIndex(segs, dx, dy); Dictionary<int,int> iIndexMap = BuildIndexMap(index); / / S2' Closed-loop feedback adjustment for (int t = 0; t < Tmax; t++) { var st = TrialFilterClip(index, sampleRatio: 0.1); / / Trial processing statistics double g2 = FeedbackTune(index.GBase, st.RejRate, st.MAvg,st.DLoad); if (Math.Abs(g2 - index.GBase) / index.GBase < epsConv)break; (dx, dy) = SplitByAspect(g2, bbox); index = BuildGridIndex(segs, dx, dy); / / Rebuild the index to close the loop. iIndexMap = BuildIndexMap(index); } / / S3 object processing Parallel.ForEach(GetAllEditableObjects(), objId => { if (IsEntityOutside(pline, objId, index)) objId.Erase(); else PreciseClipping(pline, objId, index, iIndexMap); }); } Example 2
[0064] This embodiment illustrates the cutting of filled patterns and the two-way sequential cutting method. The cutting process of the filled pattern is as follows: Figure 5 As shown. For the fill pattern, first extract all its boundary rings, including the outer boundary ring and the inner island ring; for each boundary ring, obtain the mesh using the same mesh granularity formula and closed-loop feedback as in Example 1, and apply the clipping method of this invention. To simulate Boolean intersection, a bidirectional sequential clipping method is adopted: the first clipping step uses the boundary ring as the clipping object and the user-specified clipping boundary as the clipping boundary to perform clipping, obtaining the boundary segment located within the clipping boundary; the second clipping step reverses this, using the clipping boundary as the clipping object and the boundary ring as the clipping boundary to perform clipping, obtaining the boundary segment located within the boundary ring; the ring synthesis step connects, sorts, and combines all the boundary segments obtained from the two clipping steps to form a new set of closed boundary rings, matches the endpoint coordinates of each boundary segment from beginning to end, and connects the boundary segments with shared endpoints in sequence until one or more boundary rings with closed beginning and end are formed, obtaining a new set of closed boundary rings; finally, the fill pattern object is regenerated based on this and the original style attributes are maintained. The key code framework of this process is as follows (illustrated using C#): / / Special processing of fill pattern void ProcessHatch(Hatch hatch, Polyline pline, GridIndex index) { List <List <point2d>> outerBoundaries = new List<List <point2d>>(); List<List <point2d>> innerBoundaries = new List<List <point2d>>(); if (GetHatchBoundaries(hatch, ref outerBoundaries, refinnerBoundaries)) { List <polyline>newOuterBounds = new List <polyline>(); List <polyline>newInnerBounds = new List <polyline>(); / / Boundary loop clipping ClipBoundaryRings(outerBoundaries, pline, index,newOuterBounds); ClipBoundaryRings(innerBoundaries, pline, index,newInnerBounds); / / Reconstructing fill Hatch newHatch = RecreateHatch(hatch, newOuterBounds,newInnerBounds); hatch.Erase(); } } Example 3
[0065] This embodiment is a large-scale drawing clipping test. On an AutoCAD drawing containing 10,000 graphic objects (including lines, circles, polylines, and complex fill patterns), clipping was performed using both the traditional global clipping method and the method of this invention. The traditional method took approximately 45 seconds, during which the CPU usage remained above 90%. The method of this invention took approximately 3 seconds, with the rapid filtering phase completing the removal of approximately 85% of objects far from the boundary within 1 second, greatly reducing the pressure on subsequent precise calculations. The test results show that the method of this invention can bring orders of magnitude performance improvement when processing massive amounts of graphic data.
[0066] To further illustrate the synergistic effect of the mesh granularity formula and closed-loop feedback coupling, a comparison was made on the same drawing between using a fixed mesh granularity (choosing between a threshold value based on the graphic range) and using the adaptive granularity plus closed-loop feedback of this invention. With the fixed mesh granularity, the rejection rate was approximately 70%, but index memory usage was high. With the adaptive granularity plus closed-loop feedback of this invention, the rejection rate increased to approximately 88%, memory usage decreased by approximately 60%, and convergence was achieved in no more than two iterations. This comparison shows that relying solely on fixed granularity makes it difficult to simultaneously achieve a high rejection rate and low memory usage. This invention, however, provides near-optimal initial values through the formula and corrects the object distribution residuals through feedback, achieving optimal memory usage and rejection rate simultaneously. This demonstrates that the overall effect of the coupling surpasses the effect of using either feature alone.
[0067] Example 4
[0068] This embodiment illustrates the adaptability of anisotropic meshes to narrow boundaries. Let the width of the circumscribed rectangle of the clipped boundary be W. box For 20000, high H box The value is 1000, the aspect ratio is 20, and the total number of boundary line segments is n. seg The value is 200, and the total length of the boundary is L. b The number of objects to be clipped is 42000, N. obj The value is 5000, and κ is set to 1.0.
[0069] Calculate the reference particle size (g) using the grid particle size formula. base Approximately 94, the particle size Δ in the x-direction is obtained by decomposing according to the aspect ratio. x Approximately 422, y-axis particle size Δ y The resolution is approximately 21, corresponding to approximately 47 rows and columns, with a relatively even number of grid cells in both directions. If an isotropic square grid (approximately 94 square meters on each side) is used, the number of grid cells in the column direction becomes approximately 212, while the number in the row direction becomes only approximately 11. The resolution in the shorter side direction is clearly insufficient, and a large number of empty grid cells are generated along the longer side. It is evident that anisotropic decomposition matches the grid resolution to the narrow boundary, achieving a more balanced filtering capability with a similar total number of grid cells.
[0070] For other complex objects such as polylines, circles, and filled patterns, the clipping logic is similar, but their unique geometric characteristics need to be addressed, such as vertex reconstruction of polylines, arc segmentation, and extraction and reconstruction of filled boundaries. The core idea is also to use grid indexing to narrow down the intersection range. For curved objects such as arcs, ellipses, and splines, they can first be discretized into several straight line segments according to a preset arc length or chord height tolerance, or their parametric equations can be directly intersected with the selected boundary line segment subset. After obtaining the intersection points, the same methods of deduplication, segmentation, and midpoint position discrimination are used to determine whether to retain or delete them, thus incorporating them into a unified grid indexing local clipping framework.
[0071] Example 5
[0072] This embodiment provides a computer device for implementing the AutoCAD drawing clipping method described in any of the above embodiments. The computer device includes a memory, a processor, and a computer program stored in the memory and capable of running on the processor. The memory and the processor are connected via a bus or other means. The processor can be a central processing unit (CPU), or other general-purpose processors, digital signal processors, application-specific integrated circuits (ASICs), field-programmable gate arrays (FPGAs), or other programmable logic devices. The memory can include at least one of read-only memory (ROM), random access memory (RAM), flash memory, hard disk, or solid-state drive (SSD), and may also include combinations of these types of memory. When the processor executes the computer program, it implements all the steps of the method described in the foregoing embodiments, including boundary preprocessing, adaptive determination and closed-loop feedback adjustment of mesh granularity, establishment of a mesh index relationship table, and rapid filtering and precise clipping of graphic objects. The computer device can be a desktop computer, a laptop computer, a server, or a workstation running AutoCAD and its secondary development programs. This invention does not limit the specific form of the computer device.
[0073] Example 6
[0074] This embodiment provides a computer-readable storage medium storing a computer program thereon. When executed by a processor, the computer program implements all the steps of the AutoCAD drawing clipping method described in any of the above embodiments. The computer-readable storage medium can be a non-volatile storage medium capable of storing computer program code, such as a read-only memory, random access memory, flash memory, magnetic disk, optical disk, USB flash drive, or solid-state drive, or a combination of the above media. The computer program can be divided into one or more modules, which are stored in the storage medium and executed by a processor to complete the present invention. Those skilled in the art will understand that all or part of the processes of the above method embodiments can be implemented by hardware related to computer program instructions, and the computer program, when executed, can include the processes of the above method embodiments. When the computer program product runs on a computer device, it enables the computer device to implement the steps of the methods described in the foregoing embodiments.
[0075] The contents not described in detail in this specification are existing technologies known to those skilled in the art.< / polyline> < / polyline> < / polyline> < / polyline>
Claims
1. An AutoCAD drawing clipping method based on two-stage grid indexing and local calculation, characterized in that... Obtain a closed two-dimensional polyline from the AutoCAD database as the clipping boundary, discretize the clipping boundary into boundary segments, and calculate the bounding rectangle of the clipping boundary. The mesh granularity is determined based on the number of graphic objects to be clipped and the geometry of the boundary line segments and the circumscribed rectangle. A two-dimensional mesh is then established on the circumscribed rectangle with the mesh granularity, and a mesh index relationship table is established to map the mesh coordinates to the boundary line segments that pass through the mesh. At least a portion of the graphic objects to be clipped is subjected to trial processing. Based on the geometric screening statistics obtained from the trial processing, the grid granularity is updated according to a preset feedback correction formula, and the grid index relationship table is rebuilt. The update is repeated until the relative change of the grid granularity is less than the convergence threshold or the number of iterations reaches the upper limit, so that the determination of the grid granularity and the screening and clipping of the graphic objects form a closed loop coupling. Iterate through the graphic objects to be clipped. For each graphic object, compare the set of grids covered by its bounding box with the grid coordinate range of the outer rectangle, or query the grid index relationship table to determine and delete graphic objects located outside the clipping boundary. For graphic objects that have not been deleted, query the grid index relationship table to obtain the subset of boundary line segments related to the grid they occupy, and perform precise geometric intersection and clipping operations with the graphic object only on the subset of boundary line segments.
2. The AutoCAD drawing clipping method based on two-stage grid indexing and local calculation according to claim 1, characterized in that, The formula for determining the mesh granularity is: ,in g base For the reference granularity, A box Let L be the area of the circumscribed rectangle. b n is the total length of all the boundary segments. seg N represents the total number of all the aforementioned boundary segments. obj The number of graphic objects to be clipped, κ is an adjustment coefficient with a value ranging from 0.6 to 1.4; the reference granularity is based on... and Decomposed into granularity Δ in the x-direction x granularity Δ in the y direction y W box With H box The width and height of the circumscribed rectangle are respectively defined; and the granularity in the x-direction and the granularity in the y-direction are rounded and restricted to between a preset lower limit and an upper limit.
3. The AutoCAD drawing clipping method based on two-stage grid indexing and local calculation according to claim 1, characterized in that, The feedback correction formula is: , where g base (t) The value of the t-th iteration of the baseline granularity. The value of the baseline granularity in the (t+1)th iteration is used, and both are updated according to the above formula, m avg η rej D load These represent the average number of boundary segments per object intersection, the rejection rate, and the variance of the hit grid load, respectively, obtained from the t-th iteration. tar η tar D tar Here, γ represents the target values for the average number of boundary segments intersected per object, the culling rate, and the variance of the hit grid load, respectively; and γ is the feedback gain coefficient. The update satisfies the convergence criterion. The iteration stops when ε is reached. conv The convergence threshold is defined as follows: the target value of the rejection rate is 0.80 to 0.90; the target value of the average number of boundary segments intersected per object is 8 to 16; γ is 0.2 to 0.5; the convergence threshold is 0.02 to 0.05; and the upper limit of the number of iterations is 2 to 3.
4. The AutoCAD drawing clipping method based on two-stage grid indexing and local calculation according to claim 1, characterized in that, The graphic object includes a fill pattern. The precise geometric intersection and clipping operation for the fill pattern further includes: extracting at least one boundary loop of the fill pattern; treating each boundary loop as a closed two-dimensional polyline, recursively applying the boundary discretization, grid indexing construction, and precise intersection clipping processing method to clip it, obtaining at least one new boundary loop after clipping; and regenerating a new fill pattern object using all the new boundary loops obtained after clipping, and setting the same style attributes as the fill pattern.
5. The AutoCAD drawing clipping method based on two-stage grid indexing and local calculation according to claim 4, characterized in that, The method of recursively applying the boundary discretization, grid indexing construction, and precise intersection clipping processing method to clip each boundary loop as a closed two-dimensional polyline is specifically a bidirectional sequential clipping method, including: a first clipping step, performing clipping with the boundary loop as the clipping object and the clipping boundary as the clipping boundary; a second clipping step, performing clipping with the clipping boundary as the clipping object and the boundary loop as the clipping boundary; and a loop synthesis step, merging all boundary segments obtained from the two clipping steps to form a new clipped boundary loop.
6. The AutoCAD drawing clipping method based on two-stage grid indexing and local calculation according to claim 1, characterized in that, Before calculating the bounding rectangle, a primitive standardization step is included, which converts the three-dimensional polyline objects and two-dimensional polyline objects in the AutoCAD database into lightweight polyline objects to unify the data format for subsequent intersection calculations; and when determining graphic objects located outside the clipping boundary, multiple graphic objects to be clipped are simultaneously subjected to mesh coverage judgment and filtering through parallel computing.
7. The AutoCAD drawing clipping method based on two-stage grid indexing and local calculation according to claim 1, characterized in that, The establishment of the grid index relationship table includes calculating all grids traversed by each boundary line segment using the ray stepping method. The grid index relationship table maps grid coordinates to a set of indices of boundary line segments that traverse the grid. The determination and deletion of graphic objects located outside the clipping boundary includes: when the maximum row coordinate of the grid set covered by the graphic object is less than the minimum row coordinate of the circumscribed rectangle, or the minimum row coordinate is greater than the maximum row coordinate of the circumscribed rectangle, or the maximum column coordinate is less than the minimum column coordinate of the circumscribed rectangle, or the minimum column coordinate is greater than the maximum column coordinate of the circumscribed rectangle, the graphic object is determined to be outside the clipping boundary and deleted; when the above conditions are not met, the grid index relationship table is further queried, and if the grid set has no intersection with any grid containing boundary line segments, the graphic object is determined to be outside the clipping boundary and deleted; the precise geometric intersection and clipping operation includes: calculating the intersection points of the graphic object and the subset of boundary line segments, deduplicating the intersection points, and deleting one of the intersection points when the distance between two intersection points is less than the tolerance threshold; segmenting the graphic object according to the deduplicated intersection points to obtain segmented sub-objects; and calculating the midpoint of the sub-objects, and determining whether to retain or delete the sub-objects by judging the positional relationship between the midpoint and the clipping boundary.
8. The AutoCAD drawing clipping method based on two-stage grid indexing and local calculation according to claim 1, characterized in that, The graphic object also includes at least one of circle, arc, spline curve, ellipse, text, and block; and, when establishing the grid index relationship table, a sorted index dictionary is also established, the key of which is the grid row coordinate and the value is the starting search position of the row coordinate in the grid index relationship table, which is used to accelerate grid query.
9. A computer device comprising a memory, a processor, and a computer program stored in the memory and capable of running on the processor, characterized in that, When the processor executes the computer program, it implements the steps of the AutoCAD drawing clipping method based on two-stage grid indexing and local calculation as described in any one of claims 1 to 8.
10. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the computer program is executed by the processor, it implements the steps of the AutoCAD drawing clipping method based on two-stage grid indexing and local calculation as described in any one of claims 1 to 8.
