Merge branch 'openNURBS'

This commit is contained in:
Daniele Bariletti
2023-10-23 14:45:58 +02:00
174 changed files with 153790 additions and 0 deletions
File diff suppressed because it is too large Load Diff
+976
View File
@@ -0,0 +1,976 @@
//+--------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Abstract:
// DirectX Typography Services public API definitions.
//
//----------------------------------------------------------------------------
#ifndef DWRITE_2_H_INCLUDED
#define DWRITE_2_H_INCLUDED
#pragma once
//#include <DWrite_1.h>
#include "C:\EgtDev\Extern\opennurbs\Include\dwrite_1_x32.h"
interface IDWriteFontFallback;
/// <summary>
/// How to align glyphs to the margin.
/// </summary>
enum DWRITE_OPTICAL_ALIGNMENT
{
/// <summary>
/// Align to the default metrics of the glyph.
/// </summary>
DWRITE_OPTICAL_ALIGNMENT_NONE,
/// <summary>
/// Align glyphs to the margins. Without this, some small whitespace
/// may be present between the text and the margin from the glyph's side
/// bearing values. Note that glyphs may still overhang outside the
/// margin, such as flourishes or italic slants.
/// </summary>
DWRITE_OPTICAL_ALIGNMENT_NO_SIDE_BEARINGS,
};
/// <summary>
/// Whether to enable grid-fitting of glyph outlines (a.k.a. hinting).
/// </summary>
enum DWRITE_GRID_FIT_MODE
{
/// <summary>
/// Choose grid fitting base on the font's gasp table information.
/// </summary>
DWRITE_GRID_FIT_MODE_DEFAULT,
/// <summary>
/// Always disable grid fitting, using the ideal glyph outlines.
/// </summary>
DWRITE_GRID_FIT_MODE_DISABLED,
/// <summary>
/// Enable grid fitting, adjusting glyph outlines for device pixel display.
/// </summary>
DWRITE_GRID_FIT_MODE_ENABLED
};
/// <summary>
/// Overall metrics associated with text after layout.
/// All coordinates are in device independent pixels (DIPs).
/// </summary>
struct DWRITE_TEXT_METRICS1 : DWRITE_TEXT_METRICS
{
/// <summary>
/// The height of the formatted text taking into account the
/// trailing whitespace at the end of each line, which will
/// matter for vertical reading directions.
/// </summary>
FLOAT heightIncludingTrailingWhitespace;
};
/// <summary>
/// The text renderer interface represents a set of application-defined
/// callbacks that perform rendering of text, inline objects, and decorations
/// such as underlines.
/// </summary>
interface DWRITE_DECLARE_INTERFACE("D3E0E934-22A0-427E-AAE4-7D9574B59DB1") IDWriteTextRenderer1 : public IDWriteTextRenderer
{
/// <summary>
/// IDWriteTextLayout::Draw calls this function to instruct the client to
/// render a run of glyphs.
/// </summary>
/// <param name="clientDrawingContext">The context passed to
/// IDWriteTextLayout::Draw.</param>
/// <param name="baselineOriginX">X-coordinate of the baseline.</param>
/// <param name="baselineOriginY">Y-coordinate of the baseline.</param>
/// <param name="orientationAngle">Orientation of the glyph run.</param>
/// <param name="measuringMode">Specifies measuring method for glyphs in
/// the run. Renderer implementations may choose different rendering
/// modes for given measuring methods, but best results are seen when
/// the rendering mode matches the corresponding measuring mode:
/// DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL for DWRITE_MEASURING_MODE_NATURAL
/// DWRITE_RENDERING_MODE_CLEARTYPE_GDI_CLASSIC for DWRITE_MEASURING_MODE_GDI_CLASSIC
/// DWRITE_RENDERING_MODE_CLEARTYPE_GDI_NATURAL for DWRITE_MEASURING_MODE_GDI_NATURAL
/// </param>
/// <param name="glyphRun">The glyph run to draw.</param>
/// <param name="glyphRunDescription">Properties of the characters
/// associated with this run.</param>
/// <param name="clientDrawingEffect">The drawing effect set in
/// IDWriteTextLayout::SetDrawingEffect.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
/// <remarks>
/// If a non-identity orientation is passed, the glyph run should be
/// rotated around the given baseline x and y coordinates. The function
/// IDWriteAnalyzer2::GetGlyphOrientationTransform will return the
/// necessary transform for you, which can be combined with any existing
/// world transform on the drawing context.
/// </remarks>
STDMETHOD(DrawGlyphRun)(
_In_opt_ void* clientDrawingContext,
FLOAT baselineOriginX,
FLOAT baselineOriginY,
DWRITE_GLYPH_ORIENTATION_ANGLE orientationAngle,
DWRITE_MEASURING_MODE measuringMode,
_In_ DWRITE_GLYPH_RUN const* glyphRun,
_In_ DWRITE_GLYPH_RUN_DESCRIPTION const* glyphRunDescription,
_In_opt_ IUnknown* clientDrawingEffect
) PURE;
/// <summary>
/// IDWriteTextLayout::Draw calls this function to instruct the client to draw
/// an underline.
/// </summary>
/// <param name="clientDrawingContext">The context passed to
/// IDWriteTextLayout::Draw.</param>
/// <param name="baselineOriginX">X-coordinate of the baseline.</param>
/// <param name="baselineOriginY">Y-coordinate of the baseline.</param>
/// <param name="orientationAngle">Orientation of the underline.</param>
/// <param name="underline">Underline logical information.</param>
/// <param name="clientDrawingEffect">The drawing effect set in
/// IDWriteTextLayout::SetDrawingEffect.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
/// <remarks>
/// A single underline can be broken into multiple calls, depending on
/// how the formatting changes attributes. If font sizes/styles change
/// within an underline, the thickness and offset will be averaged
/// weighted according to characters.
///
/// To get the correct top coordinate of the underline rect, add
/// underline::offset to the baseline's Y. Otherwise the underline will
/// be immediately under the text. The x coordinate will always be passed
/// as the left side, regardless of text directionality. This simplifies
/// drawing and reduces the problem of round-off that could potentially
/// cause gaps or a double stamped alpha blend. To avoid alpha overlap,
/// round the end points to the nearest device pixel.
/// </remarks>
STDMETHOD(DrawUnderline)(
_In_opt_ void* clientDrawingContext,
FLOAT baselineOriginX,
FLOAT baselineOriginY,
DWRITE_GLYPH_ORIENTATION_ANGLE orientationAngle,
_In_ DWRITE_UNDERLINE const* underline,
_In_opt_ IUnknown* clientDrawingEffect
) PURE;
/// <summary>
/// IDWriteTextLayout::Draw calls this function to instruct the client to draw
/// a strikethrough.
/// </summary>
/// <param name="clientDrawingContext">The context passed to
/// IDWriteTextLayout::Draw.</param>
/// <param name="baselineOriginX">X-coordinate of the baseline.</param>
/// <param name="baselineOriginY">Y-coordinate of the baseline.</param>
/// <param name="orientationAngle">Orientation of the strikethrough.</param>
/// <param name="strikethrough">Strikethrough logical information.</param>
/// <param name="clientDrawingEffect">The drawing effect set in
/// IDWriteTextLayout::SetDrawingEffect.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
/// <remarks>
/// A single strikethrough can be broken into multiple calls, depending on
/// how the formatting changes attributes. Strikethrough is not averaged
/// across font sizes/styles changes.
/// To get the correct top coordinate of the strikethrough rect,
/// add strikethrough::offset to the baseline's Y.
/// Like underlines, the x coordinate will always be passed as the left side,
/// regardless of text directionality.
/// </remarks>
STDMETHOD(DrawStrikethrough)(
_In_opt_ void* clientDrawingContext,
FLOAT baselineOriginX,
FLOAT baselineOriginY,
DWRITE_GLYPH_ORIENTATION_ANGLE orientationAngle,
_In_ DWRITE_STRIKETHROUGH const* strikethrough,
_In_opt_ IUnknown* clientDrawingEffect
) PURE;
/// <summary>
/// IDWriteTextLayout::Draw calls this application callback when it needs to
/// draw an inline object.
/// </summary>
/// <param name="clientDrawingContext">The context passed to
/// IDWriteTextLayout::Draw.</param>
/// <param name="originX">X-coordinate at the top-left corner of the
/// inline object.</param>
/// <param name="originY">Y-coordinate at the top-left corner of the
/// inline object.</param>
/// <param name="orientationAngle">Orientation of the inline object.</param>
/// <param name="inlineObject">The object set using IDWriteTextLayout::SetInlineObject.</param>
/// <param name="isSideways">The object should be drawn on its side.</param>
/// <param name="isRightToLeft">The object is in an right-to-left context
/// and should be drawn flipped.</param>
/// <param name="clientDrawingEffect">The drawing effect set in
/// IDWriteTextLayout::SetDrawingEffect.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
/// <remarks>
/// The right-to-left flag is a hint to draw the appropriate visual for
/// that reading direction. For example, it would look strange to draw an
/// arrow pointing to the right to indicate a submenu. The sideways flag
/// similarly hints that the object is drawn in a different orientation.
/// If a non-identity orientation is passed, the top left of the inline
/// object should be rotated around the given x and y coordinates.
/// IDWriteAnalyzer2::GetGlyphOrientationTransform returns the necessary
/// transform for this.
/// </remarks>
STDMETHOD(DrawInlineObject)(
_In_opt_ void* clientDrawingContext,
FLOAT originX,
FLOAT originY,
DWRITE_GLYPH_ORIENTATION_ANGLE orientationAngle,
_In_ IDWriteInlineObject* inlineObject,
BOOL isSideways,
BOOL isRightToLeft,
_In_opt_ IUnknown* clientDrawingEffect
) PURE;
using IDWriteTextRenderer::DrawGlyphRun;
using IDWriteTextRenderer::DrawUnderline;
using IDWriteTextRenderer::DrawStrikethrough;
using IDWriteTextRenderer::DrawInlineObject;
};
/// <summary>
/// The format of text used for text layout.
/// </summary>
/// <remarks>
/// This object may not be thread-safe and it may carry the state of text format change.
/// </remarks>
interface DWRITE_DECLARE_INTERFACE("5F174B49-0D8B-4CFB-8BCA-F1CCE9D06C67") IDWriteTextFormat1 : public IDWriteTextFormat
{
/// <summary>
/// Set the preferred orientation of glyphs when using a vertical reading direction.
/// </summary>
/// <param name="glyphOrientation">Preferred glyph orientation.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
STDMETHOD(SetVerticalGlyphOrientation)(
DWRITE_VERTICAL_GLYPH_ORIENTATION glyphOrientation
) PURE;
/// <summary>
/// Get the preferred orientation of glyphs when using a vertical reading
/// direction.
/// </summary>
STDMETHOD_(DWRITE_VERTICAL_GLYPH_ORIENTATION, GetVerticalGlyphOrientation)() PURE;
/// <summary>
/// Set whether or not the last word on the last line is wrapped.
/// </summary>
/// <param name="isLastLineWrappingEnabled">Line wrapping option.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
STDMETHOD(SetLastLineWrapping)(
BOOL isLastLineWrappingEnabled
) PURE;
/// <summary>
/// Get whether or not the last word on the last line is wrapped.
/// </summary>
STDMETHOD_(BOOL, GetLastLineWrapping)() PURE;
/// <summary>
/// Set how the glyphs align to the edges the margin. Default behavior is
/// to align glyphs using their default glyphs metrics which include side
/// bearings.
/// </summary>
/// <param name="opticalAlignment">Optical alignment option.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
STDMETHOD(SetOpticalAlignment)(
DWRITE_OPTICAL_ALIGNMENT opticalAlignment
) PURE;
/// <summary>
/// Get how the glyphs align to the edges the margin.
/// </summary>
STDMETHOD_(DWRITE_OPTICAL_ALIGNMENT, GetOpticalAlignment)() PURE;
/// <summary>
/// Apply a custom font fallback onto layout. If none is specified,
/// layout uses the system fallback list.
/// </summary>
/// <param name="fontFallback">Custom font fallback created from
/// IDWriteFontFallbackBuilder::CreateFontFallback or from
/// IDWriteFactory2::GetSystemFontFallback.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
STDMETHOD(SetFontFallback)(
IDWriteFontFallback* fontFallback
) PURE;
/// <summary>
/// Get the current font fallback object.
/// </summary>
STDMETHOD(GetFontFallback)(
__out IDWriteFontFallback** fontFallback
) PURE;
};
/// <summary>
/// The text layout interface represents a block of text after it has
/// been fully analyzed and formatted.
///
/// All coordinates are in device independent pixels (DIPs).
/// </summary>
interface DWRITE_DECLARE_INTERFACE("1093C18F-8D5E-43F0-B064-0917311B525E") IDWriteTextLayout2 : public IDWriteTextLayout1
{
/// <summary>
/// GetMetrics retrieves overall metrics for the formatted string.
/// </summary>
/// <param name="textMetrics">The returned metrics.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
/// <remarks>
/// Drawing effects like underline and strikethrough do not contribute
/// to the text size, which is essentially the sum of advance widths and
/// line heights. Additionally, visible swashes and other graphic
/// adornments may extend outside the returned width and height.
/// </remarks>
STDMETHOD(GetMetrics)(
_Out_ DWRITE_TEXT_METRICS1* textMetrics
) PURE;
using IDWriteTextLayout::GetMetrics;
/// <summary>
/// Set the preferred orientation of glyphs when using a vertical reading direction.
/// </summary>
/// <param name="glyphOrientation">Preferred glyph orientation.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
STDMETHOD(SetVerticalGlyphOrientation)(
DWRITE_VERTICAL_GLYPH_ORIENTATION glyphOrientation
) PURE;
/// <summary>
/// Get the preferred orientation of glyphs when using a vertical reading
/// direction.
/// </summary>
STDMETHOD_(DWRITE_VERTICAL_GLYPH_ORIENTATION, GetVerticalGlyphOrientation)() PURE;
/// <summary>
/// Set whether or not the last word on the last line is wrapped.
/// </summary>
/// <param name="isLastLineWrappingEnabled">Line wrapping option.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
STDMETHOD(SetLastLineWrapping)(
BOOL isLastLineWrappingEnabled
) PURE;
/// <summary>
/// Get whether or not the last word on the last line is wrapped.
/// </summary>
STDMETHOD_(BOOL, GetLastLineWrapping)() PURE;
/// <summary>
/// Set how the glyphs align to the edges the margin. Default behavior is
/// to align glyphs using their default glyphs metrics which include side
/// bearings.
/// </summary>
/// <param name="opticalAlignment">Optical alignment option.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
STDMETHOD(SetOpticalAlignment)(
DWRITE_OPTICAL_ALIGNMENT opticalAlignment
) PURE;
/// <summary>
/// Get how the glyphs align to the edges the margin.
/// </summary>
STDMETHOD_(DWRITE_OPTICAL_ALIGNMENT, GetOpticalAlignment)() PURE;
/// <summary>
/// Apply a custom font fallback onto layout. If none is specified,
/// layout uses the system fallback list.
/// </summary>
/// <param name="fontFallback">Custom font fallback created from
/// IDWriteFontFallbackBuilder::CreateFontFallback or
/// IDWriteFactory2::GetSystemFontFallback.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
STDMETHOD(SetFontFallback)(
IDWriteFontFallback* fontFallback
) PURE;
/// <summary>
/// Get the current font fallback object.
/// </summary>
STDMETHOD(GetFontFallback)(
__out IDWriteFontFallback** fontFallback
) PURE;
};
/// <summary>
/// The text analyzer interface represents a set of application-defined
/// callbacks that perform rendering of text, inline objects, and decorations
/// such as underlines.
/// </summary>
interface DWRITE_DECLARE_INTERFACE("553A9FF3-5693-4DF7-B52B-74806F7F2EB9") IDWriteTextAnalyzer2 : public IDWriteTextAnalyzer1
{
/// <summary>
/// Returns 2x3 transform matrix for the respective angle to draw the
/// glyph run or other object.
/// </summary>
/// <param name="glyphOrientationAngle">The angle reported to one of the application callbacks,
/// including IDWriteTextAnalysisSink1::SetGlyphOrientation and IDWriteTextRenderer1::Draw*.</param>
/// <param name="isSideways">Whether the run's glyphs are sideways or not.</param>
/// <param name="originX">X origin of the element, be it a glyph run or underline or other.</param>
/// <param name="originY">Y origin of the element, be it a glyph run or underline or other.</param>
/// <param name="transform">Returned transform.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
/// <remarks>
/// This rotates around the given origin x and y, returning a translation component
/// such that the glyph run, text decoration, or inline object is drawn with the
/// right orientation at the expected coordinate.
/// </remarks>
STDMETHOD(GetGlyphOrientationTransform)(
DWRITE_GLYPH_ORIENTATION_ANGLE glyphOrientationAngle,
BOOL isSideways,
FLOAT originX,
FLOAT originY,
_Out_ DWRITE_MATRIX* transform
) PURE;
/// <summary>
/// Returns a list of typographic feature tags for the given script and language.
/// </summary>
/// <param name="fontFace">The font face to get features from.</param>
/// <param name="scriptAnalysis">Script analysis result from AnalyzeScript.</param>
/// <param name="localeName">The locale to use when selecting the feature,
/// such en-us or ja-jp.</param>
/// <param name="maxTagCount">Maximum tag count.</param>
/// <param name="actualTagCount">Actual tag count. If greater than
/// maxTagCount, E_NOT_SUFFICIENT_BUFFER is returned, and the call
/// should be retried with a larger buffer.</param>
/// <param name="tags">Feature tag list.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
STDMETHOD(GetTypographicFeatures)(
IDWriteFontFace* fontFace,
DWRITE_SCRIPT_ANALYSIS scriptAnalysis,
_In_opt_z_ WCHAR const* localeName,
UINT32 maxTagCount,
_Out_ UINT32* actualTagCount,
_Out_writes_(maxTagCount) DWRITE_FONT_FEATURE_TAG* tags
) PURE;
/// <summary>
/// Returns an array of which glyphs are affected by a given feature.
/// </summary>
/// <param name="fontFace">The font face to read glyph information from.</param>
/// <param name="scriptAnalysis">Script analysis result from AnalyzeScript.</param>
/// <param name="localeName">The locale to use when selecting the feature,
/// such en-us or ja-jp.</param>
/// <param name="featureTag">OpenType feature name to use, which may be one
/// of the DWRITE_FONT_FEATURE_TAG values or a custom feature using
/// DWRITE_MAKE_OPENTYPE_TAG.</param>
/// <param name="glyphCount">Number of glyph indices to check.</param>
/// <param name="glyphIndices">Glyph indices to check for feature application.</param>
/// <param name="featureApplies">Output of which glyphs are affected by the
/// feature, where for each glyph affected, the respective array index
/// will be 1. The result is returned per-glyph without regard to
/// neighboring context of adjacent glyphs.</param>
/// </remarks>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
STDMETHOD(CheckTypographicFeature)(
IDWriteFontFace* fontFace,
DWRITE_SCRIPT_ANALYSIS scriptAnalysis,
_In_opt_z_ WCHAR const* localeName,
DWRITE_FONT_FEATURE_TAG featureTag,
UINT32 glyphCount,
_In_reads_(glyphCount) UINT16 const* glyphIndices,
_Out_writes_(glyphCount) UINT8* featureApplies
) PURE;
using IDWriteTextAnalyzer1::GetGlyphOrientationTransform;
};
/// <summary>
/// A font fallback definition used for mapping characters to fonts capable of
/// supporting them.
/// </summary>
interface DWRITE_DECLARE_INTERFACE("EFA008F9-F7A1-48BF-B05C-F224713CC0FF") IDWriteFontFallback : public IUnknown
{
/// <summary>
/// Determines an appropriate font to use to render the range of text.
/// </summary>
/// <param name="source">The text source implementation holds the text and
/// locale.</param>
/// <param name="textLength">Length of the text to analyze.</param>
/// <param name="baseFontCollection">Default font collection to use.</param>
/// <param name="baseFamilyName">Family name of the base font. If you pass
/// null, no matching will be done against the family.</param>
/// <param name="baseWeight">Desired weight.</param>
/// <param name="baseStyle">Desired style.</param>
/// <param name="baseStretch">Desired stretch.</param>
/// <param name="mappedLength">Length of text mapped to the mapped font.
/// This will always be less or equal to the input text length and
/// greater than zero (if the text length is non-zero) so that the
/// caller advances at least one character each call.</param>
/// <param name="mappedFont">The font that should be used to render the
/// first mappedLength characters of the text. If it returns NULL,
/// then no known font can render the text, and mappedLength is the
/// number of unsupported characters to skip.</param>
/// <param name="scale">Scale factor to multiply the em size of the
/// returned font by.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
STDMETHOD(MapCharacters)(
IDWriteTextAnalysisSource* analysisSource,
UINT32 textPosition,
UINT32 textLength,
_In_opt_ IDWriteFontCollection* baseFontCollection,
_In_opt_z_ wchar_t const* baseFamilyName,
DWRITE_FONT_WEIGHT baseWeight,
DWRITE_FONT_STYLE baseStyle,
DWRITE_FONT_STRETCH baseStretch,
_Out_range_(0, textLength) UINT32* mappedLength,
_COM_Outptr_result_maybenull_ IDWriteFont** mappedFont,
_Out_ FLOAT* scale
) PURE;
};
/// <summary>
/// Builder used to create a font fallback definition by appending a series of
/// fallback mappings, followed by a creation call.
/// </summary>
/// <remarks>
/// This object may not be thread-safe.
/// </remarks>
interface DWRITE_DECLARE_INTERFACE("FD882D06-8ABA-4FB8-B849-8BE8B73E14DE") IDWriteFontFallbackBuilder : public IUnknown
{
/// <summary>
/// Appends a single mapping to the list. Call this once for each additional mapping.
/// </summary>
/// <param name="ranges">Unicode ranges that apply to this mapping.</param>
/// <param name="rangesCount">Number of Unicode ranges.</param>
/// <param name="localeName">Locale of the context (e.g. document locale).</param>
/// <param name="baseFamilyName">Base family name to match against, if applicable.</param>
/// <param name="fontCollection">Explicit font collection for this mapping (optional).</param>
/// <param name="targetFamilyNames">List of target family name strings.</param>
/// <param name="targetFamilyNamesCount">Number of target family names.</param>
/// <param name="scale">Scale factor to multiply the result target font by.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
STDMETHOD(AddMapping)(
_In_reads_(rangesCount) DWRITE_UNICODE_RANGE const* ranges,
UINT32 rangesCount,
_In_reads_(targetFamilyNamesCount) WCHAR const** targetFamilyNames,
UINT32 targetFamilyNamesCount,
_In_opt_ IDWriteFontCollection* fontCollection = NULL,
_In_opt_z_ WCHAR const* localeName = NULL,
_In_opt_z_ WCHAR const* baseFamilyName = NULL,
FLOAT scale = 1.0f
) PURE;
/// <summary>
/// Appends all the mappings from an existing font fallback object.
/// </summary>
/// <param name="fontFallback">Font fallback to read mappings from.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
STDMETHOD(AddMappings)(
IDWriteFontFallback* fontFallback
) PURE;
/// <summary>
/// Creates the finalized fallback object from the mappings added.
/// </summary>
/// <param name="fontFallback">Created fallback list.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
STDMETHOD(CreateFontFallback)(
_COM_Outptr_ IDWriteFontFallback** fontFallback
) PURE;
};
/// <summary>
/// DWRITE_COLOR_F
/// </summary>
#ifndef D3DCOLORVALUE_DEFINED
typedef struct _D3DCOLORVALUE {
union {
FLOAT r;
FLOAT dvR;
};
union {
FLOAT g;
FLOAT dvG;
};
union {
FLOAT b;
FLOAT dvB;
};
union {
FLOAT a;
FLOAT dvA;
};
} D3DCOLORVALUE;
#define D3DCOLORVALUE_DEFINED
#endif // D3DCOLORVALUE_DEFINED
typedef D3DCOLORVALUE DWRITE_COLOR_F;
/// <summary>
/// The IDWriteFont interface represents a physical font in a font collection.
/// </summary>
interface DWRITE_DECLARE_INTERFACE("29748ed6-8c9c-4a6a-be0b-d912e8538944") IDWriteFont2 : public IDWriteFont1
{
/// <summary>
/// Returns TRUE if the font contains tables that can provide color information
/// (including COLR, CPAL, SVG, CBDT, sbix tables), or FALSE if not. Note that
/// TRUE is returned even in the case when the font tables contain only grayscale
/// images.
/// </summary>
STDMETHOD_(BOOL, IsColorFont)() PURE;
};
/// <summary>
/// The interface that represents an absolute reference to a font face.
/// It contains font face type, appropriate file references and face identification data.
/// Various font data such as metrics, names and glyph outlines is obtained from IDWriteFontFace.
/// </summary>
interface DWRITE_DECLARE_INTERFACE("d8b768ff-64bc-4e66-982b-ec8e87f693f7") IDWriteFontFace2 : public IDWriteFontFace1
{
/// <summary>
/// Returns TRUE if the font contains tables that can provide color information
/// (including COLR, CPAL, SVG, CBDT, sbix tables), or FALSE if not. Note that
/// TRUE is returned even in the case when the font tables contain only grayscale
/// images.
/// </summary>
STDMETHOD_(BOOL, IsColorFont)() PURE;
/// <summary>
/// Returns the number of color palettes defined by the font. The return
/// value is zero if the font has no color information. Color fonts must
/// have at least one palette, with palette index zero being the default.
/// </summary>
STDMETHOD_(UINT32, GetColorPaletteCount)() PURE;
/// <summary>
/// Returns the number of entries in each color palette. All color palettes
/// in a font have the same number of palette entries. The return value is
/// zero if the font has no color information.
/// </summary>
STDMETHOD_(UINT32, GetPaletteEntryCount)() PURE;
/// <summary>
/// Reads color values from the font's color palette.
/// </summary>
/// <param name="colorPaletteIndex">Zero-based index of the color palette. If the
/// font does not have a palette with the specified index, the method returns
/// DWRITE_E_NOCOLOR.<param>
/// <param name="firstEntryIndex">Zero-based index of the first palette entry
/// to read.</param>
/// <param name="entryCount">Number of palette entries to read.</param>
/// <param name="paletteEntries">Array that receives the color values.<param>
/// <returns>
/// Standard HRESULT error code.
/// The return value is E_INVALIDARG if firstEntryIndex + entryCount is greater
/// than the actual number of palette entries as returned by GetPaletteEntryCount.
/// The return value is DWRITE_E_NOCOLOR if the font does not have a palette
/// with the specified palette index.
/// </returns>
STDMETHOD(GetPaletteEntries)(
UINT32 colorPaletteIndex,
UINT32 firstEntryIndex,
UINT32 entryCount,
_Out_writes_(entryCount) DWRITE_COLOR_F* paletteEntries
) PURE;
/// <summary>
/// Determines the recommended text rendering and grid-fit mode to be used based on the
/// font, size, world transform, and measuring mode.
/// </summary>
/// <param name="fontEmSize">Logical font size in DIPs.</param>
/// <param name="dpiX">Number of pixels per logical inch in the horizontal direction.</param>
/// <param name="dpiY">Number of pixels per logical inch in the vertical direction.</param>
/// <param name="transform">Specifies the world transform.</param>
/// <param name="outlineThreshold">Specifies the quality of the graphics system's outline rendering,
/// affects the size threshold above which outline rendering is used.</param>
/// <param name="measuringMode">Specifies the method used to measure during text layout. For proper
/// glyph spacing, the function returns a rendering mode that is compatible with the specified
/// measuring mode.</param>
/// <param name="renderingParams">Rendering parameters object. This parameter is necessary in case the rendering parameters
/// object overrides the rendering mode.</param>
/// <param name="renderingMode">Receives the recommended rendering mode.</param>
/// <param name="gridFitMode">Receives the recommended grid-fit mode.</param>
/// <remarks>
/// This method should be used to determine the actual rendering mode in cases where the rendering
/// mode of the rendering params object is DWRITE_RENDERING_MODE_DEFAULT, and the actual grid-fit
/// mode when the rendering params object is DWRITE_GRID_FIT_MODE_DEFAULT.
/// </remarks>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
STDMETHOD(GetRecommendedRenderingMode)(
FLOAT fontEmSize,
FLOAT dpiX,
FLOAT dpiY,
_In_opt_ DWRITE_MATRIX const* transform,
BOOL isSideways,
DWRITE_OUTLINE_THRESHOLD outlineThreshold,
DWRITE_MEASURING_MODE measuringMode,
_In_opt_ IDWriteRenderingParams* renderingParams,
_Out_ DWRITE_RENDERING_MODE* renderingMode,
_Out_ DWRITE_GRID_FIT_MODE* gridFitMode
) PURE;
using IDWriteFontFace1::GetRecommendedRenderingMode;
};
/// <summary>
/// Represents a color glyph run. The IDWriteFactory2::TranslateColorGlyphRun
/// method returns an ordered collection of color glyph runs, which can be
/// layered on top of each other to produce a color representation of the
/// given base glyph run.
/// </summary>
struct DWRITE_COLOR_GLYPH_RUN
{
/// <summary>
/// Glyph run to render.
/// </summary>
DWRITE_GLYPH_RUN glyphRun;
/// <summary>
/// Optional glyph run description.
/// </summary>
_Maybenull_ DWRITE_GLYPH_RUN_DESCRIPTION* glyphRunDescription;
/// <summary>
/// Location at which to draw this glyph run.
/// </summary>
FLOAT baselineOriginX;
FLOAT baselineOriginY;
/// <summary>
/// Color to use for this layer, if any. This is the same color that
/// IDWriteFontFace2::GetPaletteEntries would return for the current
/// palette index if the paletteIndex member is less than 0xFFFF. If
/// the paletteIndex member is 0xFFFF then there is no associated
/// palette entry, this member is set to { 0, 0, 0, 0 }, and the client
/// should use the current foreground brush.
/// </summary>
DWRITE_COLOR_F runColor;
/// <summary>
/// Zero-based index of this layer's color entry in the current color
/// palette, or 0xFFFF if this layer is to be rendered using
/// the current foreground brush.
/// </summary>
UINT16 paletteIndex;
};
/// <summary>
/// Enumerator for an ordered collection of color glyph runs.
/// </summary>
interface DWRITE_DECLARE_INTERFACE("d31fbe17-f157-41a2-8d24-cb779e0560e8") IDWriteColorGlyphRunEnumerator : public IUnknown
{
/// <summary>
/// Advances to the first or next color run. The runs are enumerated
/// in order from back to front.
/// </summary>
/// <param name="hasRun">Receives TRUE if there is a current run or
/// FALSE if the end of the sequence has been reached.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
STDMETHOD(MoveNext)(
_Out_ BOOL* hasRun
) PURE;
/// <summary>
/// Gets the current color glyph run.
/// </summary>
/// <param name="colorGlyphRun">Receives a pointer to the color
/// glyph run. The pointer remains valid until the next call to
/// MoveNext or until the interface is released.</param>
/// <returns>
/// Standard HRESULT error code. An error is returned if there is
/// no current glyph run, i.e., if MoveNext has not yet been called
/// or if the end of the sequence has been reached.
/// </returns>
STDMETHOD(GetCurrentRun)(
_Outptr_ DWRITE_COLOR_GLYPH_RUN const** colorGlyphRun
) PURE;
};
/// <summary>
/// The interface that represents text rendering settings for glyph rasterization and filtering.
/// </summary>
interface DWRITE_DECLARE_INTERFACE("F9D711C3-9777-40AE-87E8-3E5AF9BF0948") IDWriteRenderingParams2 : public IDWriteRenderingParams1
{
/// <summary>
/// Gets the grid fitting mode.
/// </summary>
STDMETHOD_(DWRITE_GRID_FIT_MODE, GetGridFitMode)() PURE;
};
/// <summary>
/// The root factory interface for all DWrite objects.
/// </summary>
interface DWRITE_DECLARE_INTERFACE("0439fc60-ca44-4994-8dee-3a9af7b732ec") IDWriteFactory2 : public IDWriteFactory1
{
/// <summary>
/// Get the system-appropriate font fallback mapping list.
/// </summary>
/// <param name="fontFallback">The system fallback list.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
STDMETHOD(GetSystemFontFallback)(
_COM_Outptr_ IDWriteFontFallback** fontFallback
) PURE;
/// <summary>
/// Create a custom font fallback builder.
/// </summary>
/// <param name="fontFallbackBuilder">Empty font fallback builder.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
STDMETHOD(CreateFontFallbackBuilder)(
_COM_Outptr_ IDWriteFontFallbackBuilder** fontFallbackBuilder
) PURE;
/// <summary>
/// Translates a glyph run to a sequence of color glyph runs, which can be
/// rendered to produce a color representation of the original "base" run.
/// </summary>
/// <param name="baselineOriginX">Horizontal origin of the base glyph run in
/// pre-transform coordinates.</param>
/// <param name="baselineOriginY">Vertical origin of the base glyph run in
/// pre-transform coordinates.</param>
/// <param name="glyphRun">Pointer to the original "base" glyph run.</param>
/// <param name="glyphRunDescription">Optional glyph run description.</param>
/// <param name="measuringMode">Measuring mode, needed to compute the origins
/// of each glyph.</param>
/// <param name="worldToDeviceTransform">Matrix converting from the client's
/// coordinate space to device coordinates (pixels), i.e., the world transform
/// multiplied by any DPI scaling.</param>
/// <param name="colorPaletteIndex">Zero-based index of the color palette to use.
/// Valid indices are less than the number of palettes in the font, as returned
/// by IDWriteFontFace2::GetColorPaletteCount.</param>
/// <param name="colorLayers">If the function succeeds, receives a pointer
/// to an enumerator object that can be used to obtain the color glyph runs.
/// If the base run has no color glyphs, then the output pointer is NULL
/// and the method returns DWRITE_E_NOCOLOR.</param>
/// <returns>
/// Returns DWRITE_E_NOCOLOR if the font has no color information, the base
/// glyph run does not contain any color glyphs, or the specified color palette
/// index is out of range. In this case, the client should render the base glyph
/// run. Otherwise, returns a standard HRESULT error code.
/// </returns>
STDMETHOD(TranslateColorGlyphRun)(
FLOAT baselineOriginX,
FLOAT baselineOriginY,
_In_ DWRITE_GLYPH_RUN const* glyphRun,
_In_opt_ DWRITE_GLYPH_RUN_DESCRIPTION const* glyphRunDescription,
DWRITE_MEASURING_MODE measuringMode,
_In_opt_ DWRITE_MATRIX const* worldToDeviceTransform,
UINT32 colorPaletteIndex,
_COM_Outptr_ IDWriteColorGlyphRunEnumerator** colorLayers
) PURE;
/// <summary>
/// Creates a rendering parameters object with the specified properties.
/// </summary>
/// <param name="gamma">The gamma value used for gamma correction, which must be greater than zero and cannot exceed 256.</param>
/// <param name="enhancedContrast">The amount of contrast enhancement, zero or greater.</param>
/// <param name="clearTypeLevel">The degree of ClearType level, from 0.0f (no ClearType) to 1.0f (full ClearType).</param>
/// <param name="pixelGeometry">The geometry of a device pixel.</param>
/// <param name="renderingMode">Method of rendering glyphs. In most cases, this should be DWRITE_RENDERING_MODE_DEFAULT to automatically use an appropriate mode.</param>
/// <param name="gridFitMode">How to grid fit glyph outlines. In most cases, this should be DWRITE_GRID_FIT_DEFAULT to automatically choose an appropriate mode.</param>
/// <param name="renderingParams">Holds the newly created rendering parameters object, or NULL in case of failure.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
STDMETHOD(CreateCustomRenderingParams)(
FLOAT gamma,
FLOAT enhancedContrast,
FLOAT grayscaleEnhancedContrast,
FLOAT clearTypeLevel,
DWRITE_PIXEL_GEOMETRY pixelGeometry,
DWRITE_RENDERING_MODE renderingMode,
DWRITE_GRID_FIT_MODE gridFitMode,
_COM_Outptr_ IDWriteRenderingParams2** renderingParams
) PURE;
using IDWriteFactory::CreateCustomRenderingParams;
using IDWriteFactory1::CreateCustomRenderingParams;
/// <summary>
/// Creates a glyph run analysis object, which encapsulates information
/// used to render a glyph run.
/// </summary>
/// <param name="glyphRun">Structure specifying the properties of the glyph run.</param>
/// <param name="transform">Optional transform applied to the glyphs and their positions. This transform is applied after the
/// scaling specified by the emSize and pixelsPerDip.</param>
/// <param name="renderingMode">Specifies the rendering mode, which must be one of the raster rendering modes (i.e., not default
/// and not outline).</param>
/// <param name="measuringMode">Specifies the method to measure glyphs.</param>
/// <param name="gridFitMode">How to grid-fit glyph outlines. This must be non-default.</param>
/// <param name="baselineOriginX">Horizontal position of the baseline origin, in DIPs.</param>
/// <param name="baselineOriginY">Vertical position of the baseline origin, in DIPs.</param>
/// <param name="glyphRunAnalysis">Receives a pointer to the newly created object.</param>
/// <returns>
/// Standard HRESULT error code.
/// </returns>
STDMETHOD(CreateGlyphRunAnalysis)(
_In_ DWRITE_GLYPH_RUN const* glyphRun,
_In_opt_ DWRITE_MATRIX const* transform,
DWRITE_RENDERING_MODE renderingMode,
DWRITE_MEASURING_MODE measuringMode,
DWRITE_GRID_FIT_MODE gridFitMode,
DWRITE_TEXT_ANTIALIAS_MODE antialiasMode,
FLOAT baselineOriginX,
FLOAT baselineOriginY,
_COM_Outptr_ IDWriteGlyphRunAnalysis** glyphRunAnalysis
) PURE;
using IDWriteFactory::CreateGlyphRunAnalysis;
};
#endif /* DWRITE_2_H_INCLUDED */
File diff suppressed because it is too large Load Diff
+180
View File
@@ -0,0 +1,180 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2016 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
////////////////////////////////////////////////////////////////
//
// Includes all openNURBS toolkit headers required to use the
// openNURBS toolkit library. See readme.txt for details.
//
////////////////////////////////////////////////////////////////
#pragma warning (disable:4189)
#if !defined(OPENNURBS_INC_)
#define OPENNURBS_INC_
#define OPENNURBS_INC_IN_PROGRESS
#include "opennurbs_system.h" /* system headers used by openNURBS code */
#include "opennurbs_wip.h" /* works in progress defines that control availability */
#include "opennurbs_3dm.h" /* 3DM typecode (TCODE) definitions */
#include "opennurbs_defines.h" /* openNURBS defines and enums */
#include "opennurbs_error.h" /* error handling */
#include "opennurbs_memory.h" /* memory managment (onmalloc(), onrealloc(), onfree(), ...) */
#include "opennurbs_rand.h" /* random number generator */
#include "opennurbs_crc.h" /* cyclic redundancy check tool */
#include "opennurbs_uuid.h" /* universally unique identifiers (UUID, a.k.a, GUID) */
#include "opennurbs_unicode.h" /* unicode string conversion */
#if defined(ON_CPLUSPLUS)
#include "opennurbs_sleeplock.h"
#include "opennurbs_topology.h"
#include "opennurbs_cpp_base.h" // for safe use of STL classes as private data members
#include "opennurbs_locale.h"
#include "opennurbs_date.h"
#include "opennurbs_version_number.h"
#include "opennurbs_compstat.h"
#include "opennurbs_progress_reporter.h" // ON_ProgressReporter class
#include "opennurbs_terminator.h" // ON_Terminator class
#include "opennurbs_lock.h" // simple atomic operation lock setter
#include "opennurbs_fsp.h" // fixed size memory pool
#include "opennurbs_function_list.h" /* list of functions to run */
#include "opennurbs_std_string.h" // std::string utilities
#include "opennurbs_md5.h"
#include "opennurbs_sha1.h"
#include "opennurbs_string.h" // dynamic string classes (single and double byte)
#include "opennurbs_hash_table.h"
#include "opennurbs_file_utilities.h"
#include "opennurbs_array.h" // dynamic array templates
#include "opennurbs_compress.h"
#include "opennurbs_base64.h" // base64 encodeing and decoding
#include "opennurbs_color.h" // R G B color
#include "opennurbs_linestyle.h" // line pattern, scale, and width
#include "opennurbs_point.h" // double precision 2d, 3d, 4d points and 2d, 3d vectors
#include "opennurbs_fpoint.h" // float precision 2d, 3d, 4d points and 2d, 3d vectors
#include "opennurbs_ipoint.h" // 2d integer point, rectangle and size
#include "opennurbs_base32.h" // base32 encodeing and decoding
#include "opennurbs_pluginlist.h"
#include "opennurbs_bounding_box.h" // simple 3d axis aligned bounding box
#include "opennurbs_matrix.h" // general m X n matrix
#include "opennurbs_xform.h" // 4 X 4 transformation matrix
#include "opennurbs_quaternion.h"
#include "opennurbs_workspace.h" // workspace memory allocation
#include "opennurbs_plane.h" // simple 3d plane
#include "opennurbs_circle.h" // simple 3d circle
#include "opennurbs_ellipse.h" // simple 3d ellipse
#include "opennurbs_parse.h" // number, length unit, length, angle, point parsing
#include "opennurbs_string_value.h" // Robust length, angle and scale value information for UI
#include "opennurbs_line.h" // simple line
#include "opennurbs_symmetry.h"
#include "opennurbs_polyline.h" // simple polyline
#include "opennurbs_cylinder.h" // simple 3d elliptical cylinder
#include "opennurbs_cone.h" // simple 3d right circular cone
#include "opennurbs_sphere.h" // simple 3d sphere
#include "opennurbs_box.h" // simple 3d box
#include "opennurbs_torus.h" // simple 3d torus
#include "opennurbs_convex_poly.h" // simple 3d simplex and 3d convex polyhedra
#include "opennurbs_bezier.h" // simple bezier and polynomial curves and surfaces
#include "opennurbs_math.h" // utilities for performing simple calculations
#include "opennurbs_intersect.h" // utilities for performing simple intersections
#include "opennurbs_optimize.h" // utilities for finding extrema and zeros
#include "opennurbs_knot.h" // utilities for working with NURBS knot vectors
#include "opennurbs_evaluate_nurbs.h" // utilities for evaluating Beziers and NURBS
#include "opennurbs_textlog.h" // text log for dumps, error logs, etc.
#include "opennurbs_rtree.h" // ON_RTree spatial search utility.
#include "opennurbs_mapchan.h"
#include "opennurbs_rendering.h"
#include "opennurbs_object.h" // virtual base class for all openNURBS objects
#include "opennurbs_model_component.h"
#include "opennurbs_archive.h" // binary arcive objects for serialization to file, memory blocks, etc.
#include "opennurbs_model_geometry.h"
#include "opennurbs_arc.h" // simple 3d circular arc
#include "opennurbs_userdata.h" // class for attaching persistent user information to openNURBS objects
#include "opennurbs_geometry.h" // virtual base class for geometric objects
#include "opennurbs_curve.h" // virtual parametric curve
#include "opennurbs_surface.h" // virtual parametric surface
#include "opennurbs_viewport.h" // simple renering projection
#include "opennurbs_texture_mapping.h" // texture coordinate evaluation
#include "opennurbs_texture.h" // texture definition
#include "opennurbs_material.h" // simple rendering material
#include "opennurbs_layer.h" // layer definition
#include "opennurbs_linetype.h" // linetype definition
#include "opennurbs_group.h" // group name and index
#include "opennurbs_light.h" // light
#include "opennurbs_pointgeometry.h" // single point
#include "opennurbs_pointcloud.h" // point set
#include "opennurbs_curveproxy.h" // proxy curve provides a way to use an existing curve
#include "opennurbs_surfaceproxy.h" // proxy surface provides a way to use another surface
#include "opennurbs_mesh.h" // mesh object
#include "opennurbs_pointgrid.h" // point grid object
#include "opennurbs_linecurve.h" // line as a paramtric curve object
#include "opennurbs_arccurve.h" // arc/circle as a paramtric curve object
#include "opennurbs_polylinecurve.h" // polyline as a paramtric curve object
#include "opennurbs_nurbscurve.h" // NURBS curve
#include "opennurbs_polycurve.h" // polycurve (composite curve)
#include "opennurbs_curveonsurface.h" // curve on surface (other kind of composite curve)
#include "opennurbs_nurbssurface.h" // NURBS surface
#include "opennurbs_planesurface.h" // plane surface
#include "opennurbs_revsurface.h" // surface of revolution
#include "opennurbs_sumsurface.h" // sum surface
#include "opennurbs_brep.h" // boundary rep
#include "opennurbs_beam.h" // lightweight extrusion object
#include "opennurbs_subd.h" // subdivison surface object
#include "opennurbs_bitmap.h" // Windows and OpenGL bitmaps
#include "opennurbs_instance.h" // instance definitions and references
#include "opennurbs_3dm_properties.h"
#include "opennurbs_3dm_settings.h"
#include "opennurbs_3dm_attributes.h"
#include "opennurbs_textglyph.h"
#include "opennurbs_textcontext.h"
#include "opennurbs_textrun.h"
#include "opennurbs_font.h" // font
#include "opennurbs_text_style.h"
#include "opennurbs_dimensionstyle.h" // dimension style
#include "opennurbs_text.h"
#include "opennurbs_hatch.h" // hatch geometry definitions
#include "opennurbs_hatch.h" // hatch geometry definitions
#include "opennurbs_linetype.h" // linetype pattern definitions
#include "opennurbs_objref.h" // ON_ObjRef definition
#include "opennurbs_offsetsurface.h" // ON_OffsetSurface definition
#include "opennurbs_detail.h" // ON_Detail definition
#include "opennurbs_lookup.h" // ON_SerialNumberTable
#include "opennurbs_object_history.h"
#include "opennurbs_annotationbase.h" // Base class for text, leaders and dimensions
#include "opennurbs_textobject.h"
#include "opennurbs_leader.h"
#include "opennurbs_dimension.h"
#include "opennurbs_dimensionformat.h" // Formatting dimension measurements to strings
#include "opennurbs_photogrammetry.h"
#include "opennurbs_extensions.h"
#include "opennurbs_freetype.h"
#endif
#undef OPENNURBS_INC_IN_PROGRESS
#endif
+532
View File
@@ -0,0 +1,532 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_THREEDM_INC_)
#define OPENNURBS_THREEDM_INC_
/* 3dm defines, structs and typedefs */
/* Typecode format 4 bytes long
x xxxxxxxxxxxxxxx,x xxx xxxx xxxx x x xx
| | | | | | |
| | | |
| | | | +--- "stuff" bit
| | | |
| | | +-- specific codes
| | |
| | +-- RESERVED - DO NOT USE (should be 0) (will be used to control CRC on/off)
| |
| +-- category:_000 0000 0000 0001 Legacy geometry TCODE_LEGACY_GEOMETRY
| _000 0000 0000 0010 openNURBS object TCODE_OPENNURBS_OBJECT
| _000 0000 0000 0100 -- RESERVED - DO NOT USE (should be 0 in any typecode) --
| _000 0000 0000 1000 -- RESERVED - DO NOT USE (should be 0 in any typecode) --
| _000 0000 0001 0000 Geometry TCODE_GEOMETRY
| _000 0000 0010 0000 Annotation
| _000 0000 0100 0000 Display Attributes TCODE_DISPLAY
| _000 0000 1000 0000 Rendering TCODE_RENDER
| _000 0001 0000 0000
| _000 0010 0000 0000 Interface TCODE_INTERFACE
| _000 0100 0000 0000 -- RESERVED - DO NOT USE (should be 0 in any typecode) --
| _000 1000 0000 0000 Tolerances TCODE_TOLERANCE
| _001 0000 0000 0000 Tables TCODE_TABLE
| _010 0000 0000 0000 Table record TCODE_TABLEREC
| _100 0000 0000 0000 User information TCODE_USER
|
+-- format: 0 - data size in header - data block follows TCODE_SHORT
1 - data in header - no data block follows
*/
/*
// The TCODE_COMMENTBLOCK is the first chunk in the file, starts 32 bytes into
// the file, and contains text information terminated with a ^Z. This ^Z and
// contents of this chunk were expanded in February 2000. Files written with
// code released earlier than this will not have the ^Z.
//
// The TCODE_ENDOFFILE is the last chunk in the file and the first 4 bytes
// of information in this chunk is an integer that contains the file length.
// This chunk was added in February 2000 and files written with code released
// earlier than this will not have this termination block.
*/
#define TCODE_COMMENTBLOCK 0x00000001
#define TCODE_ENDOFFILE 0x00007FFF
#define TCODE_ENDOFFILE_GOO 0x00007FFE /*
// this typecode is returned when
// a rogue eof marker is found
// Some v1 3dm file writers put
// these markers in a "goo".
// Simply skip these chunks and continue.
*/
#define TCODE_LEGACY_GEOMETRY 0x00010000
#define TCODE_OPENNURBS_OBJECT 0x00020000
#define TCODE_GEOMETRY 0x00100000
#define TCODE_ANNOTATION 0x00200000
#define TCODE_DISPLAY 0x00400000
#define TCODE_RENDER 0x00800000
#define TCODE_INTERFACE 0x02000000
#define TCODE_TOLERANCE 0x08000000
#define TCODE_TABLE 0x10000000
#define TCODE_TABLEREC 0x20000000
#define TCODE_USER 0x40000000
#define TCODE_SHORT 0x80000000
#define TCODE_CRC 0x8000
#define TCODE_ANONYMOUS_CHUNK (TCODE_USER | TCODE_CRC | 0x0000 )
#define TCODE_UTF8_STRING_CHUNK (TCODE_USER | TCODE_CRC | 0x0001 )
#define TCODE_MODEL_ATTRIBUTES_CHUNK (TCODE_USER | TCODE_CRC | 0x0002 )
#define TCODE_DICTIONARY (TCODE_USER | TCODE_CRC | 0x0010)
#define TCODE_DICTIONARY_ID (TCODE_USER | TCODE_CRC | 0x0011)
#define TCODE_DICTIONARY_ENTRY (TCODE_USER | TCODE_CRC | 0x0012)
#define TCODE_DICTIONARY_END (TCODE_USER | TCODE_SHORT | 0x0013)
#define TCODE_XDATA (TCODE_USER | 0x0001)
/* The openNURBS toolkit allows users to write all openNURBS classed that are
// derived from ON_Object using using TCODE_OPENNURBS_CLASS chunks.
// In the .3dm file these TCODE_OPENNURBS_CLASS chunks are always have the
// following format.
*/
/* tables added 17 February 2000 */
#define TCODE_MATERIAL_TABLE (TCODE_TABLE | 0x0010) /* rendering materials */
#define TCODE_LAYER_TABLE (TCODE_TABLE | 0x0011) /* layers */
#define TCODE_LIGHT_TABLE (TCODE_TABLE | 0x0012) /* rendering lights */
#define TCODE_OBJECT_TABLE (TCODE_TABLE | 0x0013) /* geometry and annotation */
#define TCODE_PROPERTIES_TABLE (TCODE_TABLE | 0x0014) /* model properties:
// revision history
// notes
// preview image
*/
#define TCODE_SETTINGS_TABLE (TCODE_TABLE | 0x0015) /* file properties including,
// units, tolerancess,
// annotation defaults,
// render mesh defaults,
// current layer,
// current material,
// current color,
// named construction planes,
// named viewports,
// current viewports,
*/
#define TCODE_BITMAP_TABLE (TCODE_TABLE | 0x0016) /* embedded bitmaps */
#define TCODE_USER_TABLE (TCODE_TABLE | 0x0017) /* user table */
#define TCODE_GROUP_TABLE (TCODE_TABLE | 0x0018) /* group table */
#define TCODE_FONT_TABLE (TCODE_TABLE | 0x0019) /* annotation font table */
#define TCODE_DIMSTYLE_TABLE (TCODE_TABLE | 0x0020) /* annotation dimension style table */
#define TCODE_INSTANCE_DEFINITION_TABLE (TCODE_TABLE | 0x0021) /* instance definition table */
#define TCODE_HATCHPATTERN_TABLE (TCODE_TABLE | 0x0022) /* hatch pattern table */
#define TCODE_LINETYPE_TABLE (TCODE_TABLE | 0x0023) /* linetype table */
#define TCODE_OBSOLETE_LAYERSET_TABLE (TCODE_TABLE | 0x0024) /* obsolete layer set table */
#define TCODE_TEXTURE_MAPPING_TABLE (TCODE_TABLE | 0x0025) /* texture mappings */
#define TCODE_HISTORYRECORD_TABLE (TCODE_TABLE | 0x0026) /* history records */
#define TCODE_ENDOFTABLE 0xFFFFFFFF
/* records in properties table */
#define TCODE_PROPERTIES_REVISIONHISTORY (TCODE_TABLEREC | TCODE_CRC | 0x0021)
#define TCODE_PROPERTIES_NOTES (TCODE_TABLEREC | TCODE_CRC | 0x0022)
#define TCODE_PROPERTIES_PREVIEWIMAGE (TCODE_TABLEREC | TCODE_CRC | 0x0023)
#define TCODE_PROPERTIES_APPLICATION (TCODE_TABLEREC | TCODE_CRC | 0x0024)
#define TCODE_PROPERTIES_COMPRESSED_PREVIEWIMAGE (TCODE_TABLEREC | TCODE_CRC | 0x0025)
#define TCODE_PROPERTIES_OPENNURBS_VERSION (TCODE_TABLEREC | TCODE_SHORT | 0x0026)
#define TCODE_PROPERTIES_AS_FILE_NAME (TCODE_TABLEREC | TCODE_CRC | 0x0027 )
/* records in settings table */
#define TCODE_SETTINGS_PLUGINLIST (TCODE_TABLEREC | TCODE_CRC | 0x0135)
#define TCODE_SETTINGS_UNITSANDTOLS (TCODE_TABLEREC | TCODE_CRC | 0x0031)
#define TCODE_SETTINGS_RENDERMESH (TCODE_TABLEREC | TCODE_CRC | 0x0032)
#define TCODE_SETTINGS_ANALYSISMESH (TCODE_TABLEREC | TCODE_CRC | 0x0033)
#define TCODE_SETTINGS_ANNOTATION (TCODE_TABLEREC | TCODE_CRC | 0x0034)
#define TCODE_SETTINGS_NAMED_CPLANE_LIST (TCODE_TABLEREC | TCODE_CRC | 0x0035)
#define TCODE_SETTINGS_NAMED_VIEW_LIST (TCODE_TABLEREC | TCODE_CRC | 0x0036)
#define TCODE_SETTINGS_VIEW_LIST (TCODE_TABLEREC | TCODE_CRC | 0x0037)
#define TCODE_SETTINGS_CURRENT_LAYER_INDEX (TCODE_TABLEREC | TCODE_SHORT | 0x0038)
#define TCODE_SETTINGS_CURRENT_MATERIAL_INDEX (TCODE_TABLEREC | TCODE_CRC | 0x0039)
#define TCODE_SETTINGS_CURRENT_COLOR (TCODE_TABLEREC | TCODE_CRC | 0x003A)
#define TCODE_SETTINGS__NEVER__USE__THIS (TCODE_TABLEREC | TCODE_CRC | 0x003E)
#define TCODE_SETTINGS_CURRENT_WIRE_DENSITY (TCODE_TABLEREC | TCODE_SHORT | 0x003C)
#define TCODE_SETTINGS_RENDER (TCODE_TABLEREC | TCODE_CRC | 0x003D)
#define TCODE_SETTINGS_GRID_DEFAULTS (TCODE_TABLEREC | TCODE_CRC | 0x003F)
#define TCODE_SETTINGS_MODEL_URL (TCODE_TABLEREC | TCODE_CRC | 0x0131)
#define TCODE_SETTINGS_CURRENT_FONT_INDEX (TCODE_TABLEREC | TCODE_SHORT | 0x0132)
#define TCODE_SETTINGS_CURRENT_DIMSTYLE_INDEX (TCODE_TABLEREC | TCODE_SHORT | 0x0133)
/* added 29 October 2002 as a chunk to hold new and future ON_3dmSettings information */
#define TCODE_SETTINGS_ATTRIBUTES (TCODE_TABLEREC | TCODE_CRC | 0x0134)
/* 2016-Nov-28 RH-33298 ON_3dmRenderSettings user data in ON_3dmSettings.m_RenderSettings */
#define TCODE_SETTINGS_RENDER_USERDATA (TCODE_TABLEREC | TCODE_CRC | 0x0136)
/* views are subrecords in the settings table */
#define TCODE_VIEW_RECORD (TCODE_TABLEREC | TCODE_CRC | 0x003B)
/* subrecords if view record */
#define TCODE_VIEW_CPLANE (TCODE_TABLEREC | TCODE_CRC | 0x013B)
#define TCODE_VIEW_VIEWPORT (TCODE_TABLEREC | TCODE_CRC | 0x023B)
#define TCODE_VIEW_SHOWCONGRID (TCODE_TABLEREC | TCODE_SHORT | 0x033B)
#define TCODE_VIEW_SHOWCONAXES (TCODE_TABLEREC | TCODE_SHORT | 0x043B)
#define TCODE_VIEW_SHOWWORLDAXES (TCODE_TABLEREC | TCODE_SHORT | 0x053B)
#define TCODE_VIEW_TRACEIMAGE (TCODE_TABLEREC | TCODE_CRC | 0x063B)
#define TCODE_VIEW_WALLPAPER (TCODE_TABLEREC | TCODE_CRC | 0x073B)
#define TCODE_VIEW_WALLPAPER_V3 (TCODE_TABLEREC | TCODE_CRC | 0x074B)
#define TCODE_VIEW_TARGET (TCODE_TABLEREC | TCODE_CRC | 0x083B)
#define TCODE_VIEW_V3_DISPLAYMODE (TCODE_TABLEREC | TCODE_SHORT | 0x093B)
#define TCODE_VIEW_NAME (TCODE_TABLEREC | TCODE_CRC | 0x0A3B)
#define TCODE_VIEW_POSITION (TCODE_TABLEREC | TCODE_CRC | 0x0B3B)
/* added 29 October 2002 as a chunk to hold new and future ON_3dmView information */
#define TCODE_VIEW_ATTRIBUTES (TCODE_TABLEREC | TCODE_CRC | 0x0C3B)
/* added 27 June 2008 as a chunk to hold userdata on ON_Viewports saved in named view list */
#define TCODE_VIEW_VIEWPORT_USERDATA (TCODE_TABLEREC | TCODE_CRC | 0x0D3B)
/* records in bitmap table */
#define TCODE_BITMAP_RECORD (TCODE_TABLEREC | TCODE_CRC | 0x0090) /* bitmap table record derived from ON_Bitmap */
/* records in material table */
#define TCODE_MATERIAL_RECORD (TCODE_TABLEREC | TCODE_CRC | 0x0040) /* material table record derived from ON_Material */
/* records in layer table */
#define TCODE_LAYER_RECORD (TCODE_TABLEREC | TCODE_CRC | 0x0050) /* layer table record derived from ON_Layer */
/* records in light table */
#define TCODE_LIGHT_RECORD (TCODE_TABLEREC | TCODE_CRC | 0x0060) /* light table record derived from ON_Light */
#define TCODE_LIGHT_RECORD_ATTRIBUTES (TCODE_INTERFACE | TCODE_CRC | 0x0061) /* ON_3dmObjectAttributes chunk */
#define TCODE_LIGHT_RECORD_ATTRIBUTES_USERDATA (TCODE_INTERFACE | 0x0062) /* ON_3dmObjectAttributes userdata chunk */
#define TCODE_LIGHT_RECORD_END (TCODE_INTERFACE | TCODE_SHORT | 0x006F)
/* records in user table
Each user table entery has two top level chunks, a TCODE_USER_TABLE_UUID chunk
and a TCODE_USER_RECORD chunk.
*/
/* The TCODE_USER_TABLE_UUID chunk
contains the plug-in id and, if the archive is V5 or later
and was written by an opennurbs with version >= 200910190,
a TCODE_USER_TABLE_RECORD_HEADER chunk.
*/
#define TCODE_USER_TABLE_UUID (TCODE_TABLEREC | TCODE_CRC | 0x0080)
/* the user record header was added in 200910190 and is inside the TCODE_USER_TABLE_UUID chunk */
#define TCODE_USER_TABLE_RECORD_HEADER (TCODE_TABLEREC | TCODE_CRC | 0x0082)
/* information saved by the plug-in is in a TCODE_USER_RECORD chunk */
#define TCODE_USER_RECORD (TCODE_TABLEREC | 0x0081)
/* records in group table */
#define TCODE_GROUP_RECORD (TCODE_TABLEREC | TCODE_CRC | 0x0073)
/* records in font table */
#define TCODE_FONT_RECORD (TCODE_TABLEREC | TCODE_CRC | 0x0074)
/* records in dimension style table */
#define TCODE_DIMSTYLE_RECORD (TCODE_TABLEREC | TCODE_CRC | 0x0075)
/* records in instance definition table */
#define TCODE_INSTANCE_DEFINITION_RECORD (TCODE_TABLEREC | TCODE_CRC | 0x0076)
/* records in hatch pattern table */
#define TCODE_HATCHPATTERN_RECORD (TCODE_TABLEREC | TCODE_CRC | 0x0077)
/* records in linetye pattern table */
#define TCODE_LINETYPE_RECORD (TCODE_TABLEREC | TCODE_CRC | 0x0078)
/* OBSOLETE records in layer set table */
#define TCODE_OBSOLETE_LAYERSET_RECORD (TCODE_TABLEREC | TCODE_CRC | 0x0079)
/* records in linetye pattern table */
#define TCODE_TEXTURE_MAPPING_RECORD (TCODE_TABLEREC | TCODE_CRC | 0x007A)
/* records in history record pattern table */
#define TCODE_HISTORYRECORD_RECORD (TCODE_TABLEREC | TCODE_CRC | 0x007B)
/* records in object table */
#define TCODE_OBJECT_RECORD (TCODE_TABLEREC | TCODE_CRC | 0x0070)
#define TCODE_OBJECT_RECORD_TYPE (TCODE_INTERFACE | TCODE_SHORT | 0x0071) /* ON::object_type value */
#define TCODE_OBJECT_RECORD_ATTRIBUTES (TCODE_INTERFACE | TCODE_CRC | 0x0072) /* ON_3dmObjectAttributes chunk */
#define TCODE_OBJECT_RECORD_ATTRIBUTES_USERDATA (TCODE_INTERFACE | 0x0073) /* ON_3dmObjectAttributes userdata chunk */
#define TCODE_OBJECT_RECORD_HISTORY (TCODE_INTERFACE | TCODE_CRC | 0x0074) /* construction history */
#define TCODE_OBJECT_RECORD_HISTORY_HEADER (TCODE_INTERFACE | TCODE_CRC | 0x0075) /* construction history header*/
#define TCODE_OBJECT_RECORD_HISTORY_DATA (TCODE_INTERFACE | TCODE_CRC | 0x0076) /* construction history data */
#define TCODE_OBJECT_RECORD_END (TCODE_INTERFACE | TCODE_SHORT | 0x007F)
/*
/////////////////////////////////////////////////////////////////////////////////////
//
// TCODE_OBJECT_RECORD
// 4 byte length of entire object record
//
// TCODE_OBJECT_RECORD_TYPE required - used to quickly filter and skip unwanted objects
// 4 byte ON::object_type
//
// TCODE_OPENNURBS_CLASS
// 4 byte length
// TCODE_OPENNURBS_CLASS_UUID
// 4 byte length = 20
// value of ON_ClassId::m_uuid for this class
// 4 byte CRC
// TCODE_OPENNURBS_CLASS_DATA
// 4 byte length
// class specific data for geometry or annotation object
// 4 byte CRC
// TCODE_OPENNURBS_CLASS_USERDATA (1 chunk per piece of user data)
// 4 byte length
// 2 byte chunk version 2.1
// TCODE_OPENNURBS_CLASS_USERDATA_HEADER
// 4 byte length
// 16 byte value of ON_ClassId::m_uuid for this child class of ON_UserData
// 16 byte value of ON_UserData::m_userdata_uuid
// 4 byte value of ON_UserData::m_userdata_copycount
// 128 byte value of ON_UserData::m_userdata_xform
// 16 byte value of ON_UserData::m_application_uuid (in ver 2.1 chunks)
// TCODE_ANONYMOUS_CHUNK
// 4 byte length
// specific user data
// TCODE_OPENNURBS_CLASS_END
//
// TCODE_OBJECT_RECORD_ATTRIBUTES (optional)
// 4 byte length
// ON_3dmObjectAttributes information
// 4 byte crc
//
// TCODE_OBJECT_RECORD_ATTRIBUTES_USERDATA (optional)
// 4 byte length
// TCODE_OPENNURBS_CLASS_USERDATA (1 chunk per piece of user data)
// 4 byte length
// 2 byte chunk version 2.1
// TCODE_OPENNURBS_CLASS_USERDATA_HEADER
// 4 byte length
// 16 byte value of ON_ClassId::m_uuid for this child class of ON_UserData
// 16 byte value of ON_UserData::m_userdata_uuid
// 4 byte value of ON_UserData::m_userdata_copycount
// 128 byte value of ON_UserData::m_userdata_xform
// 16 byte value of ON_UserData::m_application_uuid (in ver 2.1 chunks)
// TCODE_ANONYMOUS_CHUNK
// 4 byte length
// specific user data
//
// TCODE_OBJECT_RECORD_HISTORY (optional) construction history
// 4 byte length
// 2 byte chunk version
// TCODE_OBJECT_RECORD_HISTORY_HEADER
// 4 byte length
// 2 byte chunk version
// ...
// 4 byte crc
// TCODE_OBJECT_RECORD_HISTORY_DATA
// 4 byte length
// 2 byte chunk version
// ...
// 4 byte crc
//
// TCODE_OBJECT_RECORD_END required - marks end of object record
//
/////////////////////////////////////////////////////////////////////////////////////
*/
#define TCODE_OPENNURBS_CLASS (TCODE_OPENNURBS_OBJECT | 0x7FFA)
#define TCODE_OPENNURBS_CLASS_UUID (TCODE_OPENNURBS_OBJECT | TCODE_CRC | 0x7FFB)
#define TCODE_OPENNURBS_CLASS_DATA (TCODE_OPENNURBS_OBJECT | TCODE_CRC | 0x7FFC)
#define TCODE_OPENNURBS_CLASS_USERDATA (TCODE_OPENNURBS_OBJECT | 0x7FFD)
#define TCODE_OPENNURBS_CLASS_USERDATA_HEADER (TCODE_OPENNURBS_OBJECT | TCODE_CRC | 0x7FF9)
#define TCODE_OPENNURBS_CLASS_END (TCODE_OPENNURBS_OBJECT | TCODE_SHORT | 0x7FFF)
/*
/////////////////////////////////////////////////////////////////////////////////////
//
// TCODE_OPENNURBS_CLASS
// length of entire openNURBS class object chunk
//
// TCODE_OPENNURBS_CLASS_UUID
// length of uuid (16 byte UUID + 4 byte CRC)
// 16 byte UUID ( a.k.a. GUID ) openNURBS class ID - determines specific openNURBS class
// 4 bytes (32 bit CRC of the UUID)
//
// TCODE_OPENNURBS_CLASS_DATA
// length of object data
// ... data that defines object
// use ON_classname::Read() to read this data and ON_classname::Write()
// to write this data
// 4 bytes (32 bit CRC of the object data)
//
// TCODE_OPENNURBS_CLASS_USERDATA ( 0 or more user data chunks)
//
// TCODE_OPENNURBS_CLASS_END
// 4 bytes = 0
//
/////////////////////////////////////////////////////////////////////////////////////
*/
/*
/////////////////////////////////////////////////////////////////////////////////////
//
//
// The TCODEs below were used in the version 1 file format and are needed so that
// the these files can be read and (optionally) written by the current OpenNURBS
// toolkit.
//
//
/////////////////////////////////////////////////////////////////////////////////////
*/
#define TCODE_ANNOTATION_SETTINGS (TCODE_ANNOTATION | 0x0001)
#define TCODE_TEXT_BLOCK (TCODE_ANNOTATION | 0x0004)
#define TCODE_ANNOTATION_LEADER (TCODE_ANNOTATION | 0x0005)
#define TCODE_LINEAR_DIMENSION (TCODE_ANNOTATION | 0x0006)
#define TCODE_ANGULAR_DIMENSION (TCODE_ANNOTATION | 0x0007)
#define TCODE_RADIAL_DIMENSION (TCODE_ANNOTATION | 0x0008)
/* old RhinoIO toolkit (pre February 2000) defines */
#define TCODE_RHINOIO_OBJECT_NURBS_CURVE (TCODE_OPENNURBS_OBJECT | 0x0008) /* old CRhinoNurbsCurve */
#define TCODE_RHINOIO_OBJECT_NURBS_SURFACE (TCODE_OPENNURBS_OBJECT | 0x0009) /* old CRhinoNurbsSurface */
#define TCODE_RHINOIO_OBJECT_BREP (TCODE_OPENNURBS_OBJECT | 0x000B) /* old CRhinoBrep */
#define TCODE_RHINOIO_OBJECT_DATA (TCODE_OPENNURBS_OBJECT | 0xFFFE) /* obsolete - don't confuse with TCODE_OPENNURBS_OBJECT_DATA */
#define TCODE_RHINOIO_OBJECT_END (TCODE_OPENNURBS_OBJECT | 0xFFFF) /* obsolete - don't confuse with TCODE_OPENNURBS_OBJECT_END */
/* OpenNURBS classes the require a unique tcode */
#define TCODE_OPENNURBS_BUFFER (TCODE_OPENNURBS_OBJECT | TCODE_CRC | 0x0100) /* chunk stores ON_Buffer classes */
/* legacy objects from Rhino 1.x */
#define TCODE_LEGACY_ASM (TCODE_LEGACY_GEOMETRY | 0x0001)
#define TCODE_LEGACY_PRT (TCODE_LEGACY_GEOMETRY | 0x0002)
#define TCODE_LEGACY_SHL (TCODE_LEGACY_GEOMETRY | 0x0003)
#define TCODE_LEGACY_FAC (TCODE_LEGACY_GEOMETRY | 0x0004)
#define TCODE_LEGACY_BND (TCODE_LEGACY_GEOMETRY | 0x0005)
#define TCODE_LEGACY_TRM (TCODE_LEGACY_GEOMETRY | 0x0006)
#define TCODE_LEGACY_SRF (TCODE_LEGACY_GEOMETRY | 0x0007)
#define TCODE_LEGACY_CRV (TCODE_LEGACY_GEOMETRY | 0x0008)
#define TCODE_LEGACY_SPL (TCODE_LEGACY_GEOMETRY | 0x0009)
#define TCODE_LEGACY_PNT (TCODE_LEGACY_GEOMETRY | 0x000A)
#define TCODE_STUFF 0x0100
#define TCODE_LEGACY_ASMSTUFF (TCODE_LEGACY_GEOMETRY | TCODE_STUFF | TCODE_LEGACY_ASM)
#define TCODE_LEGACY_PRTSTUFF (TCODE_LEGACY_GEOMETRY | TCODE_STUFF | TCODE_LEGACY_PRT)
#define TCODE_LEGACY_SHLSTUFF (TCODE_LEGACY_GEOMETRY | TCODE_STUFF | TCODE_LEGACY_SHL)
#define TCODE_LEGACY_FACSTUFF (TCODE_LEGACY_GEOMETRY | TCODE_STUFF | TCODE_LEGACY_FAC)
#define TCODE_LEGACY_BNDSTUFF (TCODE_LEGACY_GEOMETRY | TCODE_STUFF | TCODE_LEGACY_BND)
#define TCODE_LEGACY_TRMSTUFF (TCODE_LEGACY_GEOMETRY | TCODE_STUFF | TCODE_LEGACY_TRM)
#define TCODE_LEGACY_SRFSTUFF (TCODE_LEGACY_GEOMETRY | TCODE_STUFF | TCODE_LEGACY_SRF)
#define TCODE_LEGACY_CRVSTUFF (TCODE_LEGACY_GEOMETRY | TCODE_STUFF | TCODE_LEGACY_CRV)
#define TCODE_LEGACY_SPLSTUFF (TCODE_LEGACY_GEOMETRY | TCODE_STUFF | TCODE_LEGACY_SPL)
#define TCODE_LEGACY_PNTSTUFF (TCODE_LEGACY_GEOMETRY | TCODE_STUFF | TCODE_LEGACY_PNT)
/* legacy objects from Rhino 1.x */
#define TCODE_RH_POINT (TCODE_GEOMETRY | 0x0001)
#define TCODE_RH_SPOTLIGHT (TCODE_RENDER | 0x0001)
#define TCODE_OLD_RH_TRIMESH (TCODE_GEOMETRY | 0x0011)
#define TCODE_OLD_MESH_VERTEX_NORMALS (TCODE_GEOMETRY | 0x0012)
#define TCODE_OLD_MESH_UV (TCODE_GEOMETRY | 0x0013)
#define TCODE_OLD_FULLMESH (TCODE_GEOMETRY | 0x0014)
#define TCODE_MESH_OBJECT (TCODE_GEOMETRY | 0x0015)
#define TCODE_COMPRESSED_MESH_GEOMETRY (TCODE_GEOMETRY | 0x0017)
#define TCODE_ANALYSIS_MESH (TCODE_GEOMETRY | 0x0018)
#define TCODE_NAME (TCODE_INTERFACE | 0x0001)
#define TCODE_VIEW (TCODE_INTERFACE | 0x0002)
#define TCODE_CPLANE (TCODE_INTERFACE | 0x0003)
#define TCODE_NAMED_CPLANE (TCODE_INTERFACE | 0x0004)
#define TCODE_NAMED_VIEW (TCODE_INTERFACE | 0x0005)
#define TCODE_VIEWPORT (TCODE_INTERFACE | 0x0006)
#define TCODE_SHOWGRID (TCODE_SHORT | TCODE_INTERFACE | 0x0007)
#define TCODE_SHOWGRIDAXES (TCODE_SHORT | TCODE_INTERFACE | 0x0008)
#define TCODE_SHOWWORLDAXES (TCODE_SHORT | TCODE_INTERFACE | 0x0009)
#define TCODE_VIEWPORT_POSITION (TCODE_INTERFACE | 0x000A)
#define TCODE_VIEWPORT_TRACEINFO (TCODE_INTERFACE | 0x000B)
#define TCODE_SNAPSIZE (TCODE_INTERFACE | 0x000C)
#define TCODE_NEAR_CLIP_PLANE (TCODE_INTERFACE | 0x000D)
#define TCODE_HIDE_TRACE (TCODE_INTERFACE | 0x000E)
#define TCODE_NOTES (TCODE_INTERFACE | 0x000F)
#define TCODE_UNIT_AND_TOLERANCES (TCODE_INTERFACE | 0x0010)
#define TCODE_MAXIMIZED_VIEWPORT (TCODE_SHORT | TCODE_INTERFACE | 0x0011)
#define TCODE_VIEWPORT_WALLPAPER (TCODE_INTERFACE | 0x0012)
#define TCODE_SUMMARY (TCODE_INTERFACE | 0x0013)
#define TCODE_BITMAPPREVIEW (TCODE_INTERFACE | 0x0014)
#define TCODE_VIEWPORT_V1_DISPLAYMODE (TCODE_SHORT | TCODE_INTERFACE | 0x0015)
#define TCODE_LAYERTABLE (TCODE_SHORT | TCODE_TABLE | 0x0001) /* obsolete - do not use */
#define TCODE_LAYERREF (TCODE_SHORT | TCODE_TABLEREC | 0x0001)
#define TCODE_RGB (TCODE_SHORT | TCODE_DISPLAY | 0x0001)
#define TCODE_TEXTUREMAP (TCODE_DISPLAY | 0x0002)
#define TCODE_BUMPMAP (TCODE_DISPLAY | 0x0003)
#define TCODE_TRANSPARENCY (TCODE_SHORT | TCODE_DISPLAY | 0x0004)
#define TCODE_DISP_AM_RESOLUTION (TCODE_SHORT | TCODE_DISPLAY | 0x0005)
#define TCODE_RGBDISPLAY (TCODE_SHORT | TCODE_DISPLAY | 0x0006) /* will be used for color by object */
#define TCODE_RENDER_MATERIAL_ID (TCODE_DISPLAY | 0x0007) /* id for render material */
#define TCODE_LAYER (TCODE_DISPLAY | 0x0010)
/* obsolete layer typecodes from earlier betas - not used anymore */
#define TCODE_LAYER_OBSELETE_1 (TCODE_SHORT | TCODE_DISPLAY | 0x0013)
#define TCODE_LAYER_OBSELETE_2 (TCODE_SHORT | TCODE_DISPLAY | 0x0014)
#define TCODE_LAYER_OBSELETE_3 (TCODE_SHORT | TCODE_DISPLAY | 0x0015)
/* these were only ever used by AccuModel and never by Rhino */
#define TCODE_LAYERON (TCODE_SHORT | TCODE_DISPLAY | 0x0016)
#define TCODE_LAYERTHAWED (TCODE_SHORT | TCODE_DISPLAY | 0x0017)
#define TCODE_LAYERLOCKED (TCODE_SHORT | TCODE_DISPLAY | 0x0018)
#define TCODE_LAYERVISIBLE (TCODE_SHORT | TCODE_DISPLAY | 0x0012)
#define TCODE_LAYERPICKABLE (TCODE_SHORT | TCODE_DISPLAY | 0x0030)
#define TCODE_LAYERSNAPABLE (TCODE_SHORT | TCODE_DISPLAY | 0x0031)
#define TCODE_LAYERRENDERABLE (TCODE_SHORT | TCODE_DISPLAY | 0x0032)
/* use LAYERSTATE ( 0 = LAYER_ON, 1 = LAYER_OFF, 2 = LAYER_LOCKED ) instead of above individual toggles */
#define TCODE_LAYERSTATE (TCODE_SHORT | TCODE_DISPLAY | 0x0033)
#define TCODE_LAYERINDEX (TCODE_SHORT | TCODE_DISPLAY | 0x0034)
#define TCODE_LAYERMATERIALINDEX (TCODE_SHORT | TCODE_DISPLAY | 0x0035)
#define TCODE_RENDERMESHPARAMS (TCODE_DISPLAY | 0x0020) /* block of parameters for render meshes */
#define TCODE_DISP_CPLINES (TCODE_SHORT | TCODE_DISPLAY | 0x0022)
#define TCODE_DISP_MAXLENGTH (TCODE_DISPLAY | 0x0023)
#define TCODE_CURRENTLAYER (TCODE_SHORT | TCODE_DISPLAY | 0x0025 )
#define TCODE_LAYERNAME (TCODE_DISPLAY | 0x0011)
#define TCODE_LEGACY_TOL_FIT (TCODE_TOLERANCE | 0x0001)
#define TCODE_LEGACY_TOL_ANGLE (TCODE_TOLERANCE | 0x0002)
#endif
@@ -0,0 +1,590 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
////////////////////////////////////////////////////////////////
//
// defines ON_3dmObjectAttributes
//
////////////////////////////////////////////////////////////////
#if !defined(OPENNURBS_3DM_ATTRIBUTES_INC_)
#define OPENNURBS_3DM_ATTRIBUTES_INC_
/*
Description:
Top level OpenNURBS objects have geometry and attributes. The
geometry is stored in some class derived from ON_Geometry and
the attributes are stored in an ON_3dmObjectAttributes class.
Examples of attributes are object name, object id, display
attributes, group membership, layer membership, and so on.
Remarks:
7 January 2003 Dale Lear
Derived from ON_Object so ON_UserData can be attached
to ON_3dmObjectAttributes.
*/
class ON_CLASS ON_3dmObjectAttributes : public ON_Object
{
ON_OBJECT_DECLARE(ON_3dmObjectAttributes);
public:
static const ON_3dmObjectAttributes Unset;
static const ON_3dmObjectAttributes DefaultAttributes;
public:
// ON_Object virtual interface. See ON_Object
// for details.
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
// virtual
void Dump( ON_TextLog& ) const override;
// virtual
unsigned int SizeOf() const override;
// virtual
bool Write(ON_BinaryArchive&) const override;
// virtual
bool Read(ON_BinaryArchive&) override;
/*
Returns:
True if successful.
(xform is invertable or didn't need to be).
*/
bool Transform( const ON_Xform& xform );
// attributes of geometry and dimension table objects
public:
ON_3dmObjectAttributes();
~ON_3dmObjectAttributes();
// Default C++ copy constructor and operator= work fine
// Do not provide custom versions
// NO // ON_3dmObjectAttributes(const ON_3dmObjectAttributes&);
// NO // ON_3dmObjectAttributes& operator=(const ON_3dmObjectAttributes&);
bool operator==(const ON_3dmObjectAttributes&) const;
bool operator!=(const ON_3dmObjectAttributes&) const;
// Initializes all attributes to the default values.
void Default();
bool UpdateReferencedComponents(
const class ON_ComponentManifest& source_manifest,
const class ON_ComponentManifest& destination_manifest,
const class ON_ManifestMap& manifest_map
) override;
// Interface ////////////////////////////////////////////////////////
// An OpenNURBS object must be in one of three modes: normal, locked
// or hidden. If an object is in normal mode, then the object's layer
// controls visibility and selectability. If an object is locked, then
// the object's layer controls visibility by the object cannot be selected.
// If the object is hidden, it is not visible and it cannot be selected.
ON::object_mode Mode() const;
void SetMode( ON::object_mode ); // See Mode().
/*
Description:
Use this query to determine if an object is part of an
instance definition.
Returns:
True if the object is part of an instance definition.
*/
bool IsInstanceDefinitionObject() const;
/*
Returns:
Returns true if object is visible.
See Also:
ON_3dmObjectAttributes::SetVisible
*/
bool IsVisible() const;
/*
Description:
Controls object visibility
Parameters:
bVisible - [in] true to make object visible,
false to make object invisible
See Also:
ON_3dmObjectAttributes::IsVisible
*/
void SetVisible( bool bVisible );
// The Linetype used to display an OpenNURBS object is specified in one of two ways.
// If LinetypeSource() is ON::linetype_from_layer, then the object's layer
// ON_Layer::Linetype() is used.
// If LinetypeSource() is ON::linetype_from_object, then value of m_linetype is used.
ON::object_linetype_source LinetypeSource() const;
void SetLinetypeSource( ON::object_linetype_source ); // See LinetypeSource().
// The color used to display an OpenNURBS object is specified in one of three ways.
// If ColorSource() is ON::color_from_layer, then the object's layer
// ON_Layer::Color() is used.
// If ColorSource() is ON::color_from_object, then value of m_color is used.
// If ColorSource() is ON::color_from_material, then the diffuse color of the object's
// render material is used. See ON_3dmObjectAttributes::MaterialSource() to
// determine where to get the definition of the object's render material.
ON::object_color_source ColorSource() const;
void SetColorSource( ON::object_color_source ); // See ColorSource().
// The color used to plot an OpenNURBS object on paper is specified
// in one of three ways.
// If PlotColorSource() is ON::plot_color_from_layer, then the object's layer
// ON_Layer::PlotColor() is used.
// If PlotColorSource() is ON::plot_color_from_object, then value of PlotColor() is used.
ON::plot_color_source PlotColorSource() const;
void SetPlotColorSource( ON::plot_color_source ); // See PlotColorSource().
ON::plot_weight_source PlotWeightSource() const;
void SetPlotWeightSource( ON::plot_weight_source );
/*
Description:
If "this" has attributes (color, plot weight, ...) with
"by parent" sources, then the values of those attributes
on parent_attributes are copied.
Parameters:
parent_attributes - [in]
parent_layer - [in]
control_limits - [in]
The bits in control_limits determine which attributes may
may be copied.
1: visibility
2: color
4: render material
8: plot color
0x10: plot weight
0x20: linetype
0x40: display order
Returns:
The bits in the returned integer indicate which attributes were
actually modified.
1: visibility
2: color
4: render material
8: plot color
0x10: plot weight
0x20: linetype
0x40: display order
*/
//ON_DEPRECATED unsigned int ApplyParentalControl(
// const ON_3dmObjectAttributes& parent_attributes,
// unsigned int control_limits = 0xFFFFFFFF
// );
unsigned int ApplyParentalControl(
const ON_3dmObjectAttributes& parent_attributes,
const ON_Layer& parent_layer,
unsigned int control_limits = 0xFFFFFFFF
);
// Every OpenNURBS object has a UUID (universally unique identifier). The
// default value is nullptr. When an OpenNURBS object is added to a model, the
// value is checked. If the value is nullptr, a new UUID is created. If the
// value is not nullptr but it is already used by another object in the model,
// a new UUID is created. If the value is not nullptr and it is not used by
// another object in the model, then that value persists. When an object
// is updated, by a move for example, the value of m_uuid persists.
ON_UUID m_uuid;
// The m_name member is public to avoid breaking the SDK.
// Use SetName() and Name() for proper validation.
// OpenNURBS object have optional text names. More than one object in
// a model can have the same name and some objects may have no name.
// ON_ModelComponent::IsValidComponentName(m_name) should be true.
ON_wString m_name;
bool SetName(
const wchar_t* name,
bool bFixInvalidName
);
const ON_wString Name() const;
// OpenNURBS objects may have an URL. There are no restrictions on what
// value this URL may have. As an example, if the object came from a
// commercial part library, the URL might point to the definition of that
// part.
ON_wString m_url;
// Layer definitions in an OpenNURBS model are stored in a layer table.
// The layer table is conceptually an array of ON_Layer classes. Every
// OpenNURBS object in a model is on some layer. The object's layer
// is specified by zero based indicies into the ON_Layer array.
int m_layer_index;
// Linetype definitions in an OpenNURBS model are stored in a linetype table.
// The linetype table is conceptually an array of ON_Linetype classes. Every
// OpenNURBS object in a model references some linetype. The object's linetype
// is specified by zero based indicies into the ON_Linetype array.
// index 0 is reserved for continuous linetype (no pattern)
int m_linetype_index;
// Rendering material:
// If you want something simple and fast, set
// m_material_index to the index of the rendering material
// and ignore m_rendering_attributes.
// If you are developing a high quality plug-in renderer,
// and a user is assigning one of your fabulous rendering
// materials to this object, then add rendering material
// information to the m_rendering_attributes.m_materials[]
// array.
//
// Developers:
// As soon as m_rendering_attributes.m_materials[] is not empty,
// rendering material queries slow down. Do not populate
// m_rendering_attributes.m_materials[] when setting
// m_material_index will take care of your needs.
int m_material_index;
ON_ObjectRenderingAttributes m_rendering_attributes;
//////////////////////////////////////////////////////////////////
//
// BEGIN: Per object mesh parameter support
//
/*
Parameters:
mp - [in]
per object mesh parameters
Returns:
True if successful.
*/
bool SetCustomRenderMeshParameters(const class ON_MeshParameters& mp);
/*
Parameters:
bEnable - [in]
true to enable use of the per object mesh parameters.
false to disable use of the per object mesh parameters.
Returns:
False if the object doe not have per object mesh parameters
and bEnable was true. Use SetMeshParameters() to set
per object mesh parameters.
Remarks:
Sets the value of ON_MeshParameters::m_bCustomSettingsDisabled
to !bEnable
*/
bool EnableCustomRenderMeshParameters(bool bEnable);
/*
Returns:
Null or a pointer to fragile mesh parameters.
If a non-null pointer is returned, copy it and use the copy.
* DO NOT SAVE THIS POINTER FOR LATER USE. A call to
DeleteMeshParameters() will delete the class.
* DO NOT const_cast the returned pointer and change its
settings. You must use either SetMeshParameters()
or EnableMeshParameters() to change settings.
Remarks:
If the value of ON_MeshParameters::m_bCustomSettingsDisabled is
true, then do no use these parameters to make a render mesh.
*/
const ON_MeshParameters* CustomRenderMeshParameters() const;
/*
Description:
Deletes any per object mesh parameters.
*/
void DeleteCustomRenderMeshParameters();
//
// END: Per object mesh parameter support
//
//////////////////////////////////////////////////////////////////
/*
Description:
Determine if the simple material should come from
the object or from it's layer.
High quality rendering plug-ins should use m_rendering_attributes.
Returns:
Where to get material information if you do are too lazy
to look in m_rendering_attributes.m_materials[].
*/
ON::object_material_source MaterialSource() const;
/*
Description:
Specifies if the simple material should be the one
indicated by the material index or the one indicated
by the object's layer.
Parameters:
ms - [in]
*/
void SetMaterialSource( ON::object_material_source ms );
// If ON::color_from_object == ColorSource(), then m_color is the object's
// display color.
ON_Color m_color;
// If ON::plot_color_from_object == PlotColorSource(), then m_color is the object's
// display color.
ON_Color m_plot_color;
// Display order used to force objects to be drawn on top or behind each other
// 0 = draw object in standard depth buffered order
// <0 = draw object behind "normal" draw order objects
// >0 = draw object on top of "noraml" draw order objects
// Larger number draws on top of smaller number.
int m_display_order;
// Plot weight in millimeters.
// =0.0 means use the default width
// <0.0 means don't plot (visible for screen display, but does not show on plot)
double m_plot_weight_mm;
// Used to indicate an object has a decoration (like an arrowhead on a curve)
ON::object_decoration m_object_decoration;
// When a surface object is displayed in wireframe, m_wire_density controls
// how many isoparametric wires are used.
//
// @table
// value number of isoparametric wires
// -1 boundary wires
// 0 boundary and knot wires
// 1 boundary and knot wires and, if there are no
// interior knots, a single interior wire.
// N>=2 boundary and knot wires and (N-1) interior wires
int m_wire_density;
// If m_viewport_id is nil, the object is active in
// all viewports. If m_viewport_id is not nil, then
// this object is only active in a specific view.
// This field is primarily used to assign page space
// objects to a specific page, but it can also be used
// to restrict model space to a specific view.
ON_UUID m_viewport_id;
// Starting with V4, objects can be in either model space
// or page space. If an object is in page space, then
// m_viewport_id is not nil and identifies the page it
// is on.
ON::active_space m_space;
private:
bool m_bVisible;
unsigned char m_mode; // (m_mode % 16) = ON::object_mode values
// (m_mode / 16) = ON::display_mode values
unsigned char m_color_source; // ON::object_color_source values
unsigned char m_plot_color_source; // ON::plot_color_source values
unsigned char m_plot_weight_source; // ON::plot_weight_source values
unsigned char m_material_source; // ON::object_material_source values
unsigned char m_linetype_source; // ON::object_linetype_source values
unsigned char m_reserved_0;
ON_Xform m_reserved_future_frame = ON_Xform::Nan;
ON_SimpleArray<int> m_group; // array of zero based group indices
private:
ON__UINT_PTR m_reserved_ptr = 0;
public:
// group interface
// returns number of groups object belongs to
int GroupCount() const;
// Returns and array an array of GroupCount() zero based
// group indices. If GroupCount() is zero, then GroupList()
// returns nullptr.
const int* GroupList() const;
// Returns GroupCount() and puts a list of zero based group indices
// into the array.
int GetGroupList(ON_SimpleArray<int>&) const;
// Returns the index of the last group in the group list
// or -1 if the object is not in any groups
int TopGroup() const;
// Returns true if object is in group with the specified index
bool IsInGroup(
int // zero based group index
) const;
// Returns true if the object is in any of the groups in the list
bool IsInGroups(
int, // group_list_count
const int* // group_list[] array
) const;
// Returns true if object is in any of the groups in the list
bool IsInGroups(
const ON_SimpleArray<int>& // group_list[] array
) const;
// Adds object to the group with specified index by appending index to
// group list (If the object is already in group, nothing is changed.)
void AddToGroup(
int // zero based group index
);
// Removes object from the group with specified index. If the
// object is not in the group, nothing is changed.
void RemoveFromGroup(
int // zero based group index
);
// removes the object from the last group in the group list
void RemoveFromTopGroup();
// Removes object from all groups.
void RemoveFromAllGroups();
// display material references
/*
Description:
Searches for a matching display material. For a given
viewport id, there is at most one display material.
For a given display material id, there can be multiple
viewports. If there is a display reference in the
list with a nil viewport id, then the display material
will be used in all viewports that are not explictly
referenced in other ON_DisplayMaterialRefs.
Parameters:
search_material - [in]
found_material - [out]
If FindDisplayMaterialRef(), the input value of search_material
is never changed. If FindDisplayMaterialRef() returns true,
the chart shows the output value of display_material. When
there are multiple possibilities for a match, the matches
at the top of the chart have higher priority.
search_material found_material
input value output value
(nil,nil) (nil,did) if (nil,did) is in the list.
(nil,did) (vid,did) if (vid,did) is in the list.
(nil,did) (nil,did) if (nil,did) is in the list.
(vid,nil) (vid,did) if (vid,did) is in the list
(vid,nil) (vid,did) if (nil,did) is in the list
(vid,did) (vid,did) if (vid,did) is in the list.
Example:
ON_UUID display_material_id = ON_nil_uuid;
ON_Viewport vp = ...;
ON_DisplayMaterialRef search_dm;
search_dm.m_viewport_id = vp.ViewportId();
ON_DisplayMaterialRef found_dm;
if ( attributes.FindDisplayMaterial(search_dm, &found_dm) )
{
display_material_id = found_dm.m_display_material_id;
}
Returns:
True if a matching display material is found.
See Also:
ON_3dmObjectAttributes::AddDisplayMaterialRef
ON_3dmObjectAttributes::RemoveDisplayMaterialRef
*/
bool FindDisplayMaterialRef(
const ON_DisplayMaterialRef& search_material,
ON_DisplayMaterialRef* found_material = nullptr
) const;
/*
Description:
Quick way to see if a viewport has a special material.
Parameters:
viewport_id - [in]
display_material_id - [out]
Returns:
True if a material_id is assigned.
*/
bool FindDisplayMaterialId(
const ON_UUID& viewport_id,
ON_UUID* display_material_id = nullptr
) const;
/*
Description:
Add a display material reference to the attributes. If
there is an existing entry with a matching viewport id,
the existing entry is replaced.
Parameters:
display_material - [in]
Returns:
True if input is valid (material id != nil)
See Also:
ON_3dmObjectAttributes::FindDisplayMaterialRef
ON_3dmObjectAttributes::RemoveDisplayMaterialRef
*/
bool AddDisplayMaterialRef(
ON_DisplayMaterialRef display_material
);
/*
Description:
Remove a display material reference from the list.
Parameters:
viewport_id - [in] Any display material references
with this viewport id will be removed. If nil,
then viewport_id is ignored.
display_material_id - [in]
Any display material references that match the
viewport_id and have this display_material_id
will be removed. If nil, then display_material_id
is ignored.
Returns:
True if a display material reference was removed.
See Also:
ON_3dmObjectAttributes::FindDisplayMaterialRef
ON_3dmObjectAttributes::AddDisplayMaterialRef
*/
bool RemoveDisplayMaterialRef(
ON_UUID viewport_id,
ON_UUID display_material_id = ON_nil_uuid
);
/*
Description:
Remove a the entire display material reference list.
*/
void RemoveAllDisplayMaterialRefs();
/*
Returns:
Number of diplay material refences.
*/
int DisplayMaterialRefCount() const;
ON_SimpleArray<ON_DisplayMaterialRef> m_dmref;
private:
bool Internal_WriteV5( ON_BinaryArchive& archive ) const;
bool Internal_ReadV5( ON_BinaryArchive& archive );
};
#endif
// Brian G adding another comment on Tim's machine.
@@ -0,0 +1,186 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_3DM_PROPERTIES_INC_)
#define OPENNURBS_3DM_PROPERTIES_INC_
//////////////////////////////////////////////////////////////////////////////////////////
class ON_CLASS ON_3dmRevisionHistory
{
public:
/*
Default construction sets this = ON_3dmRevisionHistory::Empty
*/
ON_3dmRevisionHistory();
~ON_3dmRevisionHistory() = default;
ON_3dmRevisionHistory(const ON_3dmRevisionHistory&) = default;
ON_3dmRevisionHistory& operator=(const ON_3dmRevisionHistory&) = default;
/*
Description:
The Empty revision has a revision number zero,
all time values set to zero and all string
values empty.
*/
static const ON_3dmRevisionHistory Empty;
/*
Returns:
A revision history with
m_revision_count = 1
m_create_time = now
m_last_edit_time = now
m_sCreatedBy = current user
m_sLastEditedBy = current user
*/
static ON_3dmRevisionHistory FirstRevision();
int NewRevision(); // returns updated revision count
bool IsValid() const;
bool IsEmpty() const;
bool Read( ON_BinaryArchive& );
bool Write( ON_BinaryArchive& ) const;
void Dump( ON_TextLog& ) const;
/*
Returns:
true
if m_create_time is >= January 1, 1970
*/
bool CreateTimeIsSet() const;
/*
Returns:
true
if m_last_edit_time is >= January 1, 1970
*/
bool LastEditedTimeIsSet() const;
ON_wString m_sCreatedBy;
ON_wString m_sLastEditedBy;
struct tm m_create_time; // UCT create time
struct tm m_last_edit_time; // UCT las edited time
int m_revision_count = 0;
};
//////////////////////////////////////////////////////////////////////////////////////////
class ON_CLASS ON_3dmNotes
{
public:
ON_3dmNotes();
~ON_3dmNotes();
static const ON_3dmNotes Empty;
bool IsValid() const;
bool IsEmpty() const;
bool Read( ON_BinaryArchive& );
bool Write( ON_BinaryArchive& ) const;
void Dump(ON_TextLog&) const;
////////////////////////////////////////////////////////////////
//
// Interface - this information is serialized. Applications
// may want to derive a runtime class that has additional
// window and font information.
ON_wString m_notes;
bool m_bVisible; // true if notes window is showing
bool m_bHTML; // true if notes are in HTML
// last window position
int m_window_left;
int m_window_top;
int m_window_right;
int m_window_bottom;
};
//////////////////////////////////////////////////////////////////////////////////////////
class ON_CLASS ON_3dmApplication
{
// application that created the 3dm file
public:
ON_3dmApplication();
~ON_3dmApplication();
static const ON_3dmApplication Empty;
bool IsValid() const;
bool IsEmpty() const;
bool Read( ON_BinaryArchive& );
bool Write( ON_BinaryArchive& ) const;
void Dump( ON_TextLog& ) const;
ON_wString m_application_name; // short name like "Rhino 2.0"
ON_wString m_application_URL; // URL
ON_wString m_application_details; // whatever you want
};
//////////////////////////////////////////////////////////////////////////////////////////
class ON_CLASS ON_3dmProperties
{
public:
ON_3dmProperties() = default;
~ON_3dmProperties() = default;;
ON_3dmProperties(const ON_3dmProperties&) = default;
ON_3dmProperties& operator=(const ON_3dmProperties&) = default;
static const ON_3dmProperties Empty;
bool IsEmpty() const;
bool Read(
ON_BinaryArchive& archive
);
/*
Remarks:
If archive.ArchiveFileName() is not empty, that value is
written in place of m_3dmArchiveFullPathName in the 3dm archive.
If archive.ArchiveFileName() is empty, then m_3dmArchiveFullPathName
is written in the 3dm archive.
*/
bool Write(
ON_BinaryArchive& archive
) const;
void Dump( ON_TextLog& ) const;
ON_3dmRevisionHistory m_RevisionHistory;
ON_3dmNotes m_Notes;
ON_WindowsBitmap m_PreviewImage; // preview image of model
ON_3dmApplication m_Application; // application that created 3DM file
// name of .3dm archive when it was written. Used to find referenced files
// when the archive is moved or copied and then read.
ON_wString m_3dmArchiveFullPathName;
};
//////////////////////////////////////////////////////////////////////////////////////////
#endif
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,45 @@
/*
//
// Copyright (c) 1993-2018 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_APPLE_NSFONT_INC_)
#define OPENNURBS_APPLE_NSFONT_INC_
#if defined(ON_RUNTIME_APPLE_CORE_TEXT_AVAILABLE)
ON_DECL
unsigned int ON_AppleFontGlyphIndex(
CTFontRef appleFont,
unsigned int unicode_code_point
);
ON_DECL
bool ON_AppleFontGetGlyphMetrics(
CTFontRef appleFont,
unsigned int font_design_units_per_M,
unsigned int glyphIndex,
class ON_TextBox& glyph_metrics
);
ON_DECL
bool ON_AppleFontGetGlyphOutline(
CTFontRef appleFont,
unsigned int font_design_units_per_M,
unsigned int glyphIndex,
ON_OutlineFigure::Type figure_type,
class ON_Outline& outline
);
#endif
#endif
+602
View File
@@ -0,0 +1,602 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(ON_ARC_INC_)
#define ON_ARC_INC_
/*
Description:
An ON_Arc is a subcurve of 3d circle.
Details:
The curve is parameterized by an angle expressed in radians. For an IsValid() arc
the total subtended angle AngleRadians() = Domain()(1) - Domain()(0) must satisfy
0< AngleRadians() <2*Pi .
The parameterization of the ON_Arc is inherited from the ON_Circle it is derived from.
In particular
t -> center + cos(t)*radius*xaxis + sin(t)*radius*yaxis
where xaxis and yaxis, (part of ON_Circle::m_plane) form an othonormal frame of the plane
containing the circle.
*/
class ON_CLASS ON_Arc : public ON_Circle
{
public:
// Create a radius one arc with angle = 2*pi
ON_Arc() = default;
~ON_Arc() = default;
ON_Arc(const ON_Arc&) = default;
ON_Arc& operator=(const ON_Arc&) = default;
ON_Arc& operator=( const ON_Circle& );
static const ON_Arc UnitCircle; // unit circle in the xy plane
/*
Description:
Construct an arc from a circle and an angle in radians
Parameters:
circle - [in]
angle_in_radians - [in]
*/
ON_Arc(
const ON_Circle& circle,
double angle_in_radians
);
/*
Parameters:
circle - [in]
angle_interval_in_radians - [in] increasing angle interval
in radians with angle_interval_in_radians.Length() <= 2.0*ON_PI.
*/
ON_Arc(
const ON_Circle& circle,
ON_Interval angle_interval_in_radians
);
/*
Description:
Construct an arc from a plane, radius and an angle in radians.
The center of the arc is at the plane's origin.
Parameters:
plane - [in]
circle is in this plane with center at m_origin
center - [in]
circle's center point
radius - [in]
angle_in_radians - [in]
*/
ON_Arc(
const ON_Plane& plane,
double radius,
double angle_in_radians
);
/*
Description:
Construct an arc parallel to the world XY plane from a
center point, radius, and angle in radians.
The arc starts at center+(radius,0,0).
Parameters:
center - [in]
radius - [in]
angle_in_radians - [in]
*/
ON_Arc(
const ON_3dPoint& center,
double radius,
double angle_in_radians
);
/*
Description:
Construct an arc parallel to plane from a center point,
radius, and angle in radians.
The arc starts at center+radius*plane.xaxis.
Parameters:
plane - [in]
The plane x, y and z axis are used to defines the circle
plane's x, y and z axis. The plane origin is ignorned.
center - [in]
circle's center point
radius - [in]
angle_in_radians - [in]
*/
ON_Arc(
const ON_Plane& plane,
const ON_3dPoint& center,
double radius,
double angle_in_radians
);
/*
Description:
Construct an arc that passes through three 2d points.
Parameters:
start_point - [in]
interior_point - [in]
end_point - [in]
*/
ON_Arc(
const ON_2dPoint& start_point,
const ON_2dPoint& interior_point,
const ON_2dPoint& end_point
);
/*
Description:
Construct an arc that passes through three 3d points.
Parameters:
start_point - [in]
interior_point - [in]
end_point - [in]
*/
ON_Arc(
const ON_3dPoint& start_point,
const ON_3dPoint& interior_point,
const ON_3dPoint& end_point
);
/*
Description:
Create an arc from a circle and an angle in radians
Parameters:
circle - [in]
angle_in_radians - [in]
Returns:
true if input is valid and a valid arc is created.
*/
bool Create(
const ON_Circle& circle,
double angle_in_radians
);
/*
Description:
Create an arc from a circle and an increasing angle interval
Parameters:
circle - [in]
angle_interval_in_radians - [in] increasing angle interval in radians
with angle_interval_in_radians.Length() <= 2.0*ON_PI
Returns:
true if input is valid and a valid arc is created.
*/
bool Create(
const ON_Circle& circle,
ON_Interval angle_interval_in_radians
);
/*
Description:
Create an arc from a plane, radius and an angle in radians.
The center of the arc is at the plane's origin.
Parameters:
plane - [in]
circle is in this plane with center at m_origin
center - [in]
circle's center point
radius - [in]
angle_in_radians - [in]
*/
bool Create(
const ON_Plane& plane,
double radius,
double angle_in_radians
);
/*
Description:
Create an arc parallel to the world XY plane from a
center point, radius, and angle in radians.
The arc starts at center+(radius,0,0).
Parameters:
center - [in]
radius - [in]
angle_in_radians - [in]
*/
bool Create(
const ON_3dPoint& center,
double radius,
double angle_in_radians
);
/*
Description:
Create an arc parallel to plane from a center point,
radius, and angle in radians.
The arc starts at center+radius*plane.xaxis.
Parameters:
plane - [in]
The plane x, y and z axis are used to defines the circle
plane's x, y and z axis. The plane origin is ignorned.
center - [in]
circle's center point
radius - [in]
angle_in_radians - [in]
*/
bool Create(
const ON_Plane& plane,
const ON_3dPoint& center,
double radius,
double angle_in_radians
);
/*
Description:
Create an arc that passes through three 2d points.
Parameters:
start_point - [in]
interior_point - [in]
end_point - [in]
*/
bool Create(
const ON_2dPoint& start_point,
const ON_2dPoint& interior_point,
const ON_2dPoint& end_point
);
/*
Description:
Create an arc that passes through three 3d points.
Parameters:
start_point - [in]
interior_point - [in]
end_point - [in]
*/
bool Create(
const ON_3dPoint& start_point,
const ON_3dPoint& interior_point,
const ON_3dPoint& end_point
);
/*
Description:
Create an arc from a 2d start point, 2d start direction
and a 2d end point.
Parameters:
start_point - [in]
dir_at_start - [in]
end_point - [in]
*/
bool Create(
const ON_2dPoint& start_point,
const ON_2dVector& dir_at_start,
const ON_2dPoint& end_point
);
/*
Description:
Create an arc from a 3d start point, 3d start direction
and a 3d end point.
Parameters:
start_point - [in]
dir_at_start - [in]
end_point - [in]
*/
bool Create(
const ON_3dPoint& start_point,
const ON_3dVector& dir_at_start,
const ON_3dPoint& end_point
);
// Description:
// Creates a text dump of the arc listing the normal, center
// radius, start point, end point, and angle.
// Remarks:
// Dump() is intended for debugging and is not suitable
// for creating high quality text descriptions of an
// arc.
void Dump( ON_TextLog& dump ) const;
// Description:
// Checks an arc to make sure it is valid.
// Detail:
// Radius>0 and 0<AngleRadians()<=2 ON_PI
// Returns:
// true if the arc is valid.
bool IsValid() const;
// Description:
// Get arc's 3d axis aligned bounding box.
// Returns:
// 3d bounding box.
ON_BoundingBox BoundingBox() const;
// Description:
// Get arc's 3d axis aligned bounding box or the
// union of the input box with the arc's bounding box.
// Parameters:
// bbox - [in/out] 3d axis aligned bounding box
// bGrowBox - [in] (default=false)
// If true, then the union of the input bbox and the
// arc's bounding box is returned in bbox.
// If false, the arc's bounding box is returned in bbox.
// Returns:
// true if arc has bounding box and calculation was successful.
bool GetBoundingBox(
ON_BoundingBox& bbox,
int bGrowBox = false
) const;
/*
Description:
Get tight bounding box.
Parameters:
tight_bbox - [in/out] tight bounding box
bGrowBox -[in] (default=false)
If true and the input tight_bbox is valid, then returned
tight_bbox is the union of the input tight_bbox and the
arc's tight bounding box.
xform -[in] (default=nullptr)
If not nullptr, the tight bounding box of the transformed
arc is calculated. The arc is not modified.
Returns:
True if a valid tight_bbox is returned.
*/
bool GetTightBoundingBox(
ON_BoundingBox& tight_bbox,
bool bGrowBox = false,
const ON_Xform* xform = nullptr
) const;
// Returns:
// true if the arc is a complete circle; i.e., the arc's
// angle is 360 degrees.
bool IsCircle() const;
// Returns:
// The arc's subtended angle in radians.
double AngleRadians() const;
// Returns:
// The arc's subtended angle in degrees.
double AngleDegrees() const;
/*
Description:
Get evaluation domain.
Returns:
Evaluation domain (same as DomainRadians()).
*/
ON_Interval Domain() const;
// Returns:
// The arc's domain in radians.
ON_Interval DomainRadians() const;
// Returns:
// The arc's domain in degrees.
ON_Interval DomainDegrees() const;
// Description:
// Set arc's subtended angle in radians.
// Parameters:
// angle_in_radians - [in] 0 <= angle_in_radians <= 2.0*ON_PI
//
bool SetAngleRadians(
double angle_in_radians
);
/*
Description:
Set arc's angle interval in radians.
Parameters:
angle_in_radians - [in] increasing interval with
start and end angle in radians.
Length of the interval <= 2.0*ON_PI.
Returns:
true if successful.
*/
bool SetAngleIntervalRadians(
ON_Interval angle_in_radians
);
// Description:
// Set arc's domain as a subdomain of the circle.
// Parameters:
// domain_radian - [in] 0 < domain_radian[1] - domain_radian[0] <= 2.0 * ON*PI
//
bool Trim(
ON_Interval domain_radian
);
// Description:
// Set arc's subtended angle in degrees.
// Parameters:
// angle_in_degrees - [in] 0 < angle_in_degrees <= 360
bool SetAngleDegrees(
double angle_in_degrees
);
// Returns:
// Point at start of the arc.
ON_3dPoint StartPoint() const;
// Returns:
// Point at middle of the arc.
ON_3dPoint MidPoint() const;
// Returns:
// Point at end of the arc.
ON_3dPoint EndPoint() const;
// Description:
// Get the point on the arc that is closest to test_point.
// Parameters:
// test_point - [in]
// t - [out] parameter (in radians) of the point on the arc that
// is closest to test_point. If test_point is the center
// of the arc, then the starting point of the arc is
// (arc.Domain()[0]) returned.
bool ClosestPointTo(
const ON_3dPoint& test_point,
double* t
) const;
// Description:
// Get the point on the arc that is closest to test_point.
// Parameters:
// test_point - [in]
// Returns:
// The point on the arc that is closest to test_point.
// If test_point is the center of the arc, then the
// starting point of the arc is returned.
ON_3dPoint ClosestPointTo(
const ON_3dPoint& test_point
) const;
// Returns:
// Length of the arc = radius*(subtended angle in radians).
double Length() const;
/*
Returns:
Area of the arc's sector.
Remarks:
The arc's sector is the region bounded by the arc,
the line segment from the arc's end to the center,
and the line segment from the center to the arc's
start.
*/
double SectorArea() const;
/*
Returns:
Area centroid of the arc's sector.
Remarks:
The arc's sector is the region bounded by the arc,
the line segment from the arc's end to the center,
and the line segment from the center to the arc's
start.
*/
ON_3dPoint SectorAreaCentroid() const;
/*
Returns:
Area of the arc's segment.
Remarks:
The arc's segment is the region bounded by the arc and
the line segment from the arc's end to the arc's start.
*/
double SegmentArea() const;
/*
Returns:
Area centroid of the arc's segment.
Remarks:
The arc's segment is the region bounded by the arc and
the line segment from the arc's end to the arc's start.
*/
ON_3dPoint SegmentAreaCentroid() const;
// Description:
// Reverse the orientation of the arc. Changes the domain
// from [a,b] to [-b.-a].
bool Reverse();
// Description:
// Get a rational degree 2 NURBS curve representation
// of the arc. Note that the parameterization of NURBS curve
// does not match arc's transcendental paramaterization.
// Use GetRadianFromNurbFormParameter() and
// GetParameterFromRadian() to convert between the NURBS curve
// parameter and the transcendental parameter
// Parameters:
// nurbs_curve - [out] nurbs_curve returned here.
// Returns:
// 0 for failure and 2 for success.
int GetNurbForm(
ON_NurbsCurve& nurbs_curve
) const;
/*
Description:
Convert a NURBS curve arc parameter to a arc radians parameter.
Parameters:
nurbs_parameter - [in]
arc_radians_parameter - [out]
Example:
ON_Arc arc = ...;
double nurbs_t = 1.2345; // some number in interval (0,2.0*ON_PI).
double arc_t;
arc.GetRadianFromNurbFormParameter( nurbs_t, &arc_t );
ON_NurbsCurve nurbs_curve;
arc.GetNurbsForm( nurbs_curve );
arc_pt = arc.PointAt(arc_t);
nurbs_pt = nurbs_curve.PointAt(nurbs_t);
// arc_pt and nurbs_pt will be the same
Remarks:
The NURBS curve parameter is with respect to the NURBS curve
created by ON_Arc::GetNurbForm. At nurbs parameter values of
0.0, 0.5*ON_PI, ON_PI, 1.5*ON_PI, and 2.0*ON_PI, the nurbs
parameter and radian parameter are the same. At all other
values the nurbs and radian parameter values are different.
See Also:
ON_Arc::GetNurbFormParameterFromRadian
*/
bool GetRadianFromNurbFormParameter(
double nurbs_parameter,
double* arc_radians_parameter
) const;
/*
Description:
Convert a arc radians parameter to a NURBS curve arc parameter.
Parameters:
arc_radians_parameter - [in] 0.0 to 2.0*ON_PI
nurbs_parameter - [out]
Example:
ON_Arc arc = ...;
double arc_t = 1.2345; // some number in interval (0,2.0*ON_PI).
double nurbs_t;
arc.GetNurbFormParameterFromRadian( arc_t, &nurbs_t );
ON_NurbsCurve nurbs_curve;
arc.GetNurbsForm( nurbs_curve );
arc_pt = arc.PointAt(arc_t);
nurbs_pt = nurbs_curve.PointAt(nurbs_t);
// arc_pt and nurbs_pt will be the same
Remarks:
The NURBS curve parameter is with respect to the NURBS curve
created by ON_Arc::GetNurbForm. At radian values of
0.0, 0.5*ON_PI, ON_PI, 1.5*ON_PI, and 2.0*ON_PI, the nurbs
parameter and radian parameter are the same. At all other
values the nurbs and radian parameter values are different.
See Also:
ON_Arc::GetNurbFormParameterFromRadian
*/
bool GetNurbFormParameterFromRadian(
double arc_radians_parameter,
double* nurbs_parameter
) const;
private:
friend bool ON_BinaryArchive::ReadArc( ON_Arc& );
friend bool ON_BinaryArchive::WriteArc( const ON_Arc& );
// increasing interval with start and end angle in radians
ON_Interval m_angle = ON_Interval::ZeroToTwoPi;
};
#endif
+387
View File
@@ -0,0 +1,387 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(ON_GEOMETRY_CURVE_ARC_INC_)
#define ON_GEOMETRY_CURVE_ARC_INC_
/*
Description:
ON_ArcCurve is used to represent arcs and circles.
ON_ArcCurve.IsCircle() returns true if the curve
is a complete circle.
Remarks:
- An ON_ArcCurve is a subcurve of a circle, with a
constant speed parameterization. The parameterization is
an affine linear reparameterzation of the underlying arc
m_arc onto the domain m_t.
- A valid ON_ArcCurve has Radius()>0 and 0<AngleRadians()<=2*PI
and a strictly increasing Domain().
*/
class ON_CLASS ON_ArcCurve : public ON_Curve
{
ON_OBJECT_DECLARE(ON_ArcCurve);
public:
ON_ArcCurve() ON_NOEXCEPT;
virtual ~ON_ArcCurve();
ON_ArcCurve(const ON_ArcCurve&);
ON_ArcCurve& operator=(const ON_ArcCurve&);
#if defined(ON_HAS_RVALUEREF)
// rvalue copy constructor
ON_ArcCurve( ON_ArcCurve&& ) ON_NOEXCEPT;
// The rvalue assignment operator calls ON_Object::operator=(ON_Object&&)
// which could throw exceptions. See the implementation of
// ON_Object::operator=(ON_Object&&) for details.
ON_ArcCurve& operator=( ON_ArcCurve&& );
#endif
// virtual ON_Object::SizeOf override
unsigned int SizeOf() const override;
// virtual ON_Object::DataCRC override
ON__UINT32 DataCRC(ON__UINT32 current_remainder) const override;
/*
Description:
Create an arc curve with domain (0,arc.Length()).
*/
ON_ArcCurve(
const ON_Arc& arc
);
/*
Description:
Create an arc curve with domain (t0,t1)
*/
ON_ArcCurve(
const ON_Arc& arc,
double t0,
double t1
);
/*
Description:
Creates a curve that is a complete circle with
domain (0,circle.Length()).
*/
ON_ArcCurve(
const ON_Circle& circle
);
/*
Description:
Creates a curve that is a complete circle with domain (t0,t1).
*/
ON_ArcCurve(
const ON_Circle& circle,
double t0,
double t1
);
/*
Description:
Create an arc curve with domain (0,arc.Length()).
*/
ON_ArcCurve& operator=(const ON_Arc& arc);
/*
Description:
Creates a curve that is a complete circle with
domain (0,circle.Length()).
*/
ON_ArcCurve& operator=(const ON_Circle& circle);
/////////////////////////////////////////////////////////////////
// ON_Object overrides
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
void Dump( ON_TextLog& ) const override;
bool Write(
ON_BinaryArchive& // open binary file
) const override;
bool Read(
ON_BinaryArchive& // open binary file
) override;
/////////////////////////////////////////////////////////////////
// ON_Geometry overrides
int Dimension() const override;
// virtual ON_Geometry GetBBox override
bool GetBBox( double* boxmin, double* boxmax, bool bGrowBox = false ) const override;
// virtual ON_Geometry GetTightBoundingBox override
bool GetTightBoundingBox( class ON_BoundingBox& tight_bbox, bool bGrowBox = false, const class ON_Xform* xform = nullptr ) const override;
bool Transform(
const ON_Xform&
) override;
/////////////////////////////////////////////////////////////////
// ON_Curve overrides
// Description:
// virtual ON_Curve::SetDomain override.
// Set the domain of the curve
// Parameters:
// t0 - [in]
// t1 - [in] new domain will be [t0,t1]
// Returns:
// true if successful.
bool SetDomain(
double t0,
double t1
) override;
ON_Interval Domain() const override;
bool ChangeDimension(
int desired_dimension
) override;
bool ChangeClosedCurveSeam(
double t
) override;
int SpanCount() const override; // number of smooth spans in curve
bool GetSpanVector( // span "knots"
double* // array of length SpanCount() + 1
) const override; //
int Degree( // returns maximum algebraic degree of any span
// ( or a good estimate if curve spans are not algebraic )
) const override;
bool IsLinear( // true if curve locus is a line segment between
// between specified points
double = ON_ZERO_TOLERANCE // tolerance to use when checking linearity
) const override;
bool IsArc( // ON_Arc.m_angle > 0 if curve locus is an arc between
// specified points
const ON_Plane* = nullptr, // if not nullptr, test is performed in this plane
ON_Arc* = nullptr, // if not nullptr and true is returned, then arc parameters
// are filled in
double = 0.0 // tolerance to use when checking
) const override;
bool IsPlanar(
ON_Plane* = nullptr, // if not nullptr and true is returned, then plane parameters
// are filled in
double = 0.0 // tolerance to use when checking
) const override;
bool IsInPlane(
const ON_Plane&, // plane to test
double = 0.0 // tolerance to use when checking
) const override;
bool IsClosed( // true if curve is closed (either curve has
void // clamped end knots and euclidean location of start
) const override; // CV = euclidean location of end CV, or curve is
// periodic.)
bool IsPeriodic( // true if curve is a single periodic segment
void
) const override;
bool IsContinuous(
ON::continuity c,
double t,
int* hint = nullptr,
double point_tolerance=ON_ZERO_TOLERANCE,
double d1_tolerance=ON_ZERO_TOLERANCE,
double d2_tolerance=ON_ZERO_TOLERANCE,
double cos_angle_tolerance=ON_DEFAULT_ANGLE_TOLERANCE_COSINE,
double curvature_tolerance=ON_SQRT_EPSILON
) const override;
bool Reverse() override; // reverse parameterizatrion
// Domain changes from [a,b] to [-b,-a]
/*
Description:
Force the curve to start at a specified point.
Parameters:
start_point - [in]
Returns:
true if successful.
Remarks:
Some end points cannot be moved. Be sure to check return
code.
See Also:
ON_Curve::SetEndPoint
ON_Curve::PointAtStart
ON_Curve::PointAtEnd
*/
bool SetStartPoint(
ON_3dPoint start_point
) override;
/*
Description:
Force the curve to end at a specified point.
Parameters:
end_point - [in]
Returns:
true if successful.
Remarks:
Some end points cannot be moved. Be sure to check return
code.
See Also:
ON_Curve::SetStartPoint
ON_Curve::PointAtStart
ON_Curve::PointAtEnd
*/
bool SetEndPoint(
ON_3dPoint end_point
) override;
bool Evaluate( // returns false if unable to evaluate
double, // evaluation parameter
int, // number of derivatives (>=0)
int, // array stride (>=Dimension())
double*, // array of length stride*(ndir+1)
int = 0, // optional - determines which side to evaluate from
// 0 = default
// < 0 to evaluate from below,
// > 0 to evaluate from above
int* = 0 // optional - evaluation hint (int) used to speed
// repeated evaluations
) const override;
bool Trim( const ON_Interval& ) override;
// Description:
// Where possible, analytically extends curve to include domain.
// Parameters:
// domain - [in] if domain is not included in curve domain,
// curve will be extended so that its domain includes domain.
// Will not work if curve is closed. Original curve is identical
// to the restriction of the resulting curve to the original curve domain,
// Returns:
// true if successful.
bool Extend(
const ON_Interval& domain
) override;
/*
Description:
Splits (divides) the arc at the specified parameter.
The parameter must be in the interior of the arc's domain.
The ON_Curve pointers passed to ON_ArcCurve::Split must
either be nullptr or point to ON_ArcCurve objects.
If a pointer is nullptr, then an ON_ArcCurve will be created
in Split(). You may pass "this" as left_side or right_side.
Parameters:
t - [in] parameter to split the curve at in the
interval returned by Domain().
left_side - [out] left portion of curve returned here.
If not nullptr, left_side must point to an ON_ArcCuve.
right_side - [out] right portion of curve returned here
If not nullptr, right_side must point to an ON_ArcCuve.
Remarks:
Overrides virtual ON_Curve::Split.
*/
bool Split(
double t,
ON_Curve*& left_side,
ON_Curve*& right_side
) const override;
// virtual ON_Curve::GetNurbForm override
int GetNurbForm( // returns 0: unable to create NURBS representation
// with desired accuracy.
// 1: success - returned NURBS parameterization
// matches the curve's to wthe desired accuracy
// 2: success - returned NURBS point locus matches
// the curve's to the desired accuracy but, on
// the interior of the curve's domain, the
// curve's parameterization and the NURBS
// parameterization may not match to the
// desired accuracy.
ON_NurbsCurve&,
double = 0.0,
const ON_Interval* = nullptr // OPTIONAL subdomain of arc curve
) const override;
// virtual ON_Curve::HasNurbForm override
int HasNurbForm( // returns 0: unable to create NURBS representation
// with desired accuracy.
// 1: success - NURBS parameterization
// matches the curve's
// 2: success - returned NURBS point locus matches
// the curve'sbut, on
// the interior of the curve's domain, the
// curve's parameterization and the NURBS
// parameterization may not match to the
// desired accuracy.
) const override;
// virtual ON_Curve::GetCurveParameterFromNurbFormParameter override
bool GetCurveParameterFromNurbFormParameter(
double, // nurbs_t
double* // curve_t
) const override;
// virtual ON_Curve::GetNurbFormParameterFromCurveParameter override
bool GetNurbFormParameterFromCurveParameter(
double, // curve_t
double* // nurbs_t
) const override;
/*
Description:
Returns true if this arc curve is a complete circle.
*/
bool IsCircle() const;
// Returns:
// The arc's radius.
double Radius() const;
// Returns:
// The arc's subtended angle in radians.
double AngleRadians() const;
// Returns:
// The arc's subtended angle in degrees.
double AngleDegrees() const;
/////////////////////////////////////////////////////////////////
ON_Arc m_arc = ON_Arc::UnitCircle; // defualt = radius 1 circle in x-y plane
ON_Interval m_t = ON_Interval::ZeroToTwoPi;
// The dimension of a arc curve can be 2 or 3.
// (2 so ON_ArcCurve can be used as a trimming curve)
int m_dim = 3;
};
#endif
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2018 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_ATOMIC_OP_INC_)
#define OPENNURBS_ATOMIC_OP_INC_
#error OBSOLETE FILE
#endif
+126
View File
@@ -0,0 +1,126 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(ON_BASE32_INC_)
#define ON_BASE32_INC_
/*
Description:
Convert a number into base32 digits.
Parameters:
x - [in]
x_count - [in]
x[] is an array of length x_count and represents the value
x[0]*2^(8*(x_count-1)) + ... + x[x_count-2]*256 + x[x_count-1].
base32_digits - [out]
When base32_digits is not a dynamic array, base32_digits[]
must a be an array of length at least
((8*x_count)/5) + (((8*x_count)%5)?1:0) or 1,
whichever is greater.
The base32_digits[] array will be filled in with base32 digit
values (0 to 31) so that the value
b[0]*32^(b_count-1) + ... + b[b_count-2]*32 + b[b_count-1]
is the same as that defined by the x[] array.
Returns
The number of base 32 digits in the base32_digits[] array.
If 0 is returned, the input is not valid.
*/
ON_DECL
int ON_GetBase32Digits( const ON_SimpleArray<unsigned char>& x, ON_SimpleArray<unsigned char>& base32_digits );
ON_DECL
int ON_GetBase32Digits( const unsigned char* x, int x_count, unsigned char* base32_digits );
/*
Description:
Convert a list of base32 digits into a string form.
Parameters:
base32_digits - [in]
base32_digit_count - [in]
base32_digits[] is an array of length base32_digit_count.
Each element is in the range 0 to 31.
sBase32 - [out]
sBase32[] must be an array of length base32_digit_count+1 or 2,
whichever is greater. The string representation of the base 32
number will be put in this string. A hash mark symbol (#) is
used to indicate an error in the input value. The returned
string is null terminated.
Returns
True if the input is valid. False if the input is not valid,
in which case hash marks indicate the invalid entries.
*/
ON_DECL
bool ON_Base32ToString( const ON_SimpleArray<unsigned char>& base32_digits, ON_String& sBase32 );
ON_DECL
bool ON_Base32ToString( const ON_SimpleArray<unsigned char>& base32_digits, ON_wString& sBase32 );
ON_DECL
bool ON_Base32ToString( const unsigned char* base32_digits, int base32_digit_count, char* sBase32 );
/*
Description:
Fixt a common typos in sBase32 string. Lower case letters are
converted to upper case. The letters 'I', 'L', 'O' and 'S' are
converted to '1' (one), '1' (one) '0' zero and '5' (five).
Parameters:
sBase32 - [in]
sBase32clean - [out]
(can be the same string as sBase32)
Returns:
If the input is valid, the length of the converted string is returned.
If the input is not valid, 0 is returned.
*/
ON_DECL
int ON_CorrectBase32StringTypos( const wchar_t* sBase32, ON_wString& sBase32clean );
ON_DECL
int ON_CorrectBase32StringTypos( const char* sBase32, ON_String& sBase32clean );
ON_DECL
int ON_CorrectBase32StringTypos( const char* sBase32, char* sBase32clean );
/*
Description:
Convert a null terminate string containing the 32 symbols
0 1 2 3 4 5 6 7 8 9 A B C D E F G H J K M N P Q R T U V W X Y Z
(I,L,O and S are missing) into a list of base 32 digits.
Parameters:
sBase32 - [in]
String with base 32 digits
base32_digits - [out]
base32_digits[] is an array of length strlen(sBase32).
The returned array, element will be in the range 0 to 31.
sBase32[] must be an array of length base32_digit_count+1 or 2,
whichever is greater. The string representation of the base 32
number will be put in this string. A hash mark symbol (#) is
used to indicate an error in the input value. The returned
string is null terminated.
Returns
True if the input is valid. False if the input is not valid,
in which case hash marks indicate the invalid entries.
*/
ON_DECL
int ON_StringToBase32(const ON_wString& sBase32, ON_SimpleArray<unsigned char>& base32_digits );
ON_DECL
int ON_StringToBase32(const ON_String& sBase32, ON_SimpleArray<unsigned char>& base32_digits );
ON_DECL
int ON_StringToBase32(const char* sBase32, unsigned char* base32_digits );
#endif
+345
View File
@@ -0,0 +1,345 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_BASE64_INC_)
#define OPENNURBS_BASE64_INC_
//////////////////////////////////////////////////////////////////////////////////////////
class ON_CLASS ON_Base64EncodeStream
{
public:
ON_Base64EncodeStream();
virtual ~ON_Base64EncodeStream();
/*
Description:
ON_Base64EncodeStream delivers the base64 encoded stream by
calling a base64 encoded stream output handler function.
There are two options for specifying the base64 encoded stream
output handler function.
1. Overriding the virtual Out() function.
2. Providing a callback function.
SetCallback() is used to specify a callback function to handle
the base64 encoded stream and to specify a context pointer to be
passed to either option of the handler.
Parameters:
callback_function - [in]
Function to handle sections of the base64 encoded stream.
If callback_function is null, then the virtual Out()
function will be called. When callback_function
is specified, it must return true if the base64 encoding
calculation should continue and false to cancel the
base64 encoding calculation.
callback_context - [in]
This value is passed as the first argument when calling
callback_function or the virutal Out() function.
Returns:
True if successful.
Remarks:
Once base64 encoding has started, it would be unusual to
intentionally change the base64 encoded stream output handler,
but you can do this if you need to.
*/
bool SetCallback(
ON_StreamCallbackFunction callback_function,
void* callback_context
);
/*
Returns:
Current value of the callback function for handling
the base64 encoded stream. If the callback function is
null, the the virtual Out() function is used to
handle the output stream.
*/
ON_StreamCallbackFunction CallbackFunction() const;
/*
Returns:
Current value of the context pointer passed as the first
argument to the base64 encoded stream output handler function.
*/
void* CallbackContext() const;
/*
Description:
Call Begin() one time to initialize the base64 encoding
calculation. Then call In() one or more times
to submit the unencoded stream to the base64 encoding
calculation. When you reach the end of the unencoded
stream, call End().
Returns:
true if successful, false if an error occured.
*/
bool Begin();
/*
Description:
Call In() one or more times to base64 encode a stream of bytes.
After the last call to In(), call End(). Calling In() will
result in at least in_buffer_size/57 and at most
(in_buffer_size+56)/57 calls to to the output stream handler.
Parameters:
in_buffer_size - [in]
number of bytes in in_buffer
in_buffer - [in]
Returns:
true if successful, false if an error occured.
*/
bool In(
ON__UINT64 in_buffer_size,
const void* in_buffer
);
/*
Description:
If an explicit base 64 encoded stream output handler is not
specified ( CallbackFunction() returns null ), then the
virtual Out() function is called to handle the base 64 encoded
output stream. As the input stream is encoded, one or more
calls to Out() will occur.
With a possible exception of the last call to Out(), when Out()
is called, 57 input bytes have been encoded into 76 output
characters with ASCII codes A-Z, a-z, 0-9, +, /.
Parameters:
callback_context - [in]
context pointer set by calling SetCallback(). Typically
the context pointer is not used by a virtual override
because the context can be added as member variables
of the derived class, but it is available if needed.
out_buffer_size - [in]
number of non-null characters in out_buffer.
out_buffer - [in]
A null terminated ASCII string that is a base 64 encoding.
out_buffer[0...(out_buffer_size-1)] are ASCII characters with
values characters with ASCII codes A-Z, a-z, 0-9, +, /
and out_buffer[out_buffer_size] = 0.
Returns:
True to continue base 64 encodeing and false to cancel the
encoding calculation.
*/
virtual bool Out(
void* callback_context,
ON__UINT32 out_buffer_size,
const char* out_buffer
);
/*
Description:
After the last call to In(), call End(). Calling End() may
generate one call to the output stream handler with the value
of out_buffer_size = 4 to 76.
Returns:
true if successful, false if an error occured.
*/
bool End();
/*
Returns:
Then the returned value is the total number bytes in the input
stream. The size is updated every time In() is called before
any calls are made to the output stream handler. If the
calculation is finished ( End() has been called ), then the
returned value is the total number of bytes in the entire
input stream.
*/
ON__UINT64 InSize() const;
/*
Returns:
Then the returned value is the total number characters in the
output stream. The size is incremented immediately after each
call to the output stream handler. If the base64 encoding
calculation is finished ( End() has been called ), then the
returned value is the total number of bytes in the entire
output stream.
*/
ON__UINT64 OutSize() const;
/*
Returns:
Then the returned value is the 32-bit crc of the input stream.
The crc is updated every time In() is called before any calls
are made to the output stream handler. If the base64 encoding
calculation is finished ( End() has been called ), then the
returned value is the 32-bit crc of the entire input stream.
*/
ON__UINT32 InCRC() const;
/*
Returns:
Then the returned value is the 32bit crc of the output stream.
The crc is updated immediately after each call to the output
stream handler. If the calculation is finished ( End() has
been called ), then the returned value is the 32-bit crc of
the entire output stream.
*/
ON__UINT32 OutCRC() const;
private:
ON_StreamCallbackFunction m_out_callback_function;
void* m_out_callback_context;
ON__UINT64 m_in_size;
ON__UINT64 m_out_size;
ON__UINT32 m_in_crc;
ON__UINT32 m_out_crc;
void* m_implementation;
void* m_reserved;
void ErrorHandler();
private:
// prohibit use - no implementation
ON_Base64EncodeStream(const ON_Base64EncodeStream&);
ON_Base64EncodeStream& operator=(const ON_Base64EncodeStream&);
};
//////////////////////////////////////////////////////////////////////////////////////////
class ON_CLASS ON_DecodeBase64
{
public:
ON_DecodeBase64();
virtual ~ON_DecodeBase64();
void Begin();
// Decode will generate zero or more callbacks to the
// virtual Output() function. If the base 64 encoded information
// is in pieces, you can call Decode() for each piece. For example,
// if your encoded information is in a text file, you might call
// Decode() for every line in the file. Decode() returns 0 if
// there is nothing in base64str to decode or if it detects an
// error that prevents any further decoding. The function Error()
// can be used to determine if an error occured. Otherwise,
// Decode() returns a pointer to the location in the string where
// it stopped decoding because it detected a character, like a null
// terminator, an end of line character, or any other character
// that could not be part of the base 64 encoded information.
const char* Decode(const char* base64str);
const char* Decode(const char* base64str, size_t base64str_count);
const wchar_t* Decode(const wchar_t* base64str);
const wchar_t* Decode(const wchar_t* base64str, size_t base64str_count);
// You must call End() when Decode() returns 0 or when you have
// reached the end of your encoded information. End() may
// callback to Output() zero or one time. If all the information
// passed to Decode() was successfully decoded, then End()
// returns true. If something was not decoded, then End()
// returns false.
bool End();
// Override the virtual Output() callback function to process the
// decoded output. Each time Output() is called there are m_output_count
// bytes in the m_output[] array.
// Every call to Decode() can result in zero, one, or many callbacks
// to Output(). Calling End() may result in zero or one callbacks
// to Output().
virtual void Output();
// m_decode_count = total number of input base64 characters
// that Decode() has decoded.
unsigned int m_decode_count;
int m_output_count; // 0 to 512
unsigned char m_output[512];
// Call if your Output() function detects an error and
// wants to stop further decoding.
void SetError();
// Returns true if an error occured during decoding because
// invalid input was passed to Decode().
const bool Error() const;
private:
int m_status; // 1: error - decoding stopped
// 2: '=' encountered as 3rd char in Decode()
// 3: successfully parsed "**=="
// 4: successfully parsed "***="
// 5: End() successfully called.
// cached encoded input from previous call to Decode()
int m_cache_count;
int m_cache[4];
void DecodeHelper1(); // decodes "**==" quartet into 1 byte
void DecodeHelper2(); // decodes "***=" quartet into 2 bytes
};
/////////////////////////////////////////////////////////////////////
/*
class ON_CLASS ON_EncodeBase64
{
public:
ON_EncodeBase64();
virtual ~ON_EncodeBase64();
void Begin();
// Calling Encode will generate at least
// sizeof_buffer/57 and at most (sizeof_buffer+56)/57
// calls to Output(). Every callback to Output() will
// have m_output_count = 76.
void Encode(const void* buffer, size_t sizeof_buffer);
// Calling End may generate a single call to Output()
// If it does generate a single call to Output(),
// then m_output_count will be between 1 and 76.
void End(); // may generate a single call to Output().
// With a single exception, when Output() is called,
// 57 input bytes have been encoded into 76 output
// characters with ASCII codes A-Z, a-z, 0-9, +, /.
// m_output_count will be 76
// m_output[0...(m_output_count-1)] will be the base 64
// encoding.
// m_output[m_output_count] = 0.
// The Output() function can modify the values of m_output[]
// and m_output_count anyway it wants.
virtual void Output();
// Total number of bytes passed to Encode().
int m_encode_count;
// When the virtual Output() is called, there are m_output_count (1 to 76)
// characters of base64 encoded output in m_output[]. The remainder of
// the m_output[] array is zero. The Output function may modify the
// contents of m_output[] any way it sees fit.
int m_output_count;
char m_output[80];
private:
// input waiting to be encoded
// At most 56 bytes can be waiting to be processed in m_input[].
unsigned int m_unused2; // Here for alignment purposes. Never used by opennurbs.
unsigned int m_input_count;
unsigned char m_input[64];
void EncodeHelper1(const unsigned char*, char*);
void EncodeHelper2(const unsigned char*, char*);
void EncodeHelper3(const unsigned char*, char*);
void EncodeHelper57(const unsigned char*);
};
*/
#endif
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+524
View File
@@ -0,0 +1,524 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
////////////////////////////////////////////////////////////////
//
// Defines ON_WindowsBITMAPINFO class that is used to provide OS independent
// serialization of Windows device independent bitmaps (BITMAPINFO) used
// to store preview images.
//
////////////////////////////////////////////////////////////////
#if !defined(OPENNURBS_BITMAP_INC_)
#define OPENNURBS_BITMAP_INC_
class ON_CLASS ON_Bitmap : public ON_ModelComponent
{
ON_OBJECT_DECLARE(ON_Bitmap);
public:
ON_Bitmap() ON_NOEXCEPT;
~ON_Bitmap() = default;
ON_Bitmap(const ON_Bitmap&);
ON_Bitmap& operator=(const ON_Bitmap&) = default;
static const ON_Bitmap Unset;
/*
Parameters:
model_component_reference - [in]
none_return_value - [in]
value to return if ON_Layer::Cast(model_component_ref.ModelComponent())
is nullptr
Returns:
If ON_Layer::Cast(model_component_ref.ModelComponent()) is not nullptr,
that pointer is returned. Otherwise, none_return_value is returned.
*/
static const ON_Bitmap* FromModelComponentRef(
const class ON_ModelComponentReference& model_component_reference,
const ON_Bitmap* none_return_value
);
void Dump(
ON_TextLog&
) const override;
bool Write( class ON_BinaryArchive& ) const override;
bool Read( class ON_BinaryArchive& ) override;
unsigned int SizeOf() const override;
virtual
int Width() const;
virtual
int Height() const; // >0 means it's a bottom-up bitmap with origin at lower right
// <0 means it's a top-down bitmap with origin at upper left
virtual
int BitsPerPixel() const; // bits per pixel
virtual
size_t SizeofScan() const; // number of bytes per scan line
virtual
size_t SizeofImage() const; // size of current map in bytes
virtual
unsigned char* Bits(
int scan_line_index
);
virtual
const unsigned char* Bits(
int scan_line_index
) const;
const ON_FileReference& FileReference() const;
void SetFileReference(
const ON_FileReference& file_reference
);
void SetFileFullPath(
const wchar_t* file_full_path,
bool bSetContentHash
);
private:
ON_FileReference m_file_reference;
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_Bitmap*>;
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<const ON_Bitmap*>;
#endif
#if !defined(ON_OS_WINDOWS_GDI)
// These are the values of the Windows defines mentioned
// in the comment below. If you're running on Windows,
// they get defined by Windows system header files.
// If you aren't running on Windows, then you don't
// need them.
//#define BI_RGB 0L
//#define BI_RLE8 1L
//#define BI_RLE4 2L
//#define BI_BITFIELDS 3L
// Windows sizeof(ON_WindowsRGBQUAD) = 4.
struct ON_WindowsRGBQUAD {
// Mimics Windows RGBQUAD structure.
// For details searh for "RGBQUAD" at http://msdn.microsoft.com/default.asp
unsigned char rgbBlue; // BYTE
unsigned char rgbGreen; // BYTE
unsigned char rgbRed; // BYTE
unsigned char rgbReserved; // BYTE
};
// Windows packs BITMAPFILEHEADER
#pragma pack(push,2)
struct ON_WindowsBITMAPFILEHEADER {
unsigned short bfType; // WORD = file type, must be BM
unsigned int bfSize; // DWORD = size, in bytes, of the bitmap file
unsigned short bfReserved1; // WORD Reserved; must be zero
unsigned short bfReserved2; // WORD Reserved; must be zero
unsigned int bfOffBits; // DWORD = offset, in bytes, from the beginning of the BITMAPFILEHEADER structure to the bitmap bits
};
#pragma pack(pop)
// Mimics Windows BITMAPINFOHEADER structure.
// For details searh for "BITMAPINFOHEADER" at http://msdn.microsoft.com/default.asp
// Windows sizeof(BITMAPINFOHEADER) = 80.
struct ON_WindowsBITMAPINFOHEADER
{
unsigned int biSize; // DWORD = sizeof(BITMAPINFOHEADER)
int biWidth; // LONG = width (in pixels) of (decompressed) bitmap
int biHeight; // LONG = height (in pixels) of (decompressed) bitmap
// >0 means it's a bottom-up bitmap with origin
// in the lower left corner.
// <0 means it's a top-down bitmap with origin
// in the upper left corner.
unsigned short biPlanes; // WORD = number of planes
// (always 1 in current Windows versions)
unsigned short biBitCount; // WORD = bits per pixel (0,1,4,8,16,24,32 are valid)
// 1 See http://msdn.microsoft.com/default.asp
// 4 See http://msdn.microsoft.com/default.asp
// 8 The bitmap has a maximum of 256 colors,
// and the bmiColors member contains up
// to 256 entries. In this case, each byte
// in the array represents a single pixel.
// 16 See http://msdn.microsoft.com/default.asp
// 24 If biClrUsed=0 and biCompression=BI_RGB(0),
// then each 3-byte triplet in the bitmap
// array represents the relative intensities
// of blue, green, and red, respectively, for
// a pixel. For other possibilities, see
// http://msdn.microsoft.com/default.asp
// 32 If biClrUsed=0 and biCompression=BI_RGB(0),
// then each 4-byte DWORD in the bitmap
// array represents the relative intensities
// of blue, green, and red, respectively, for
// a pixel. The high byte in each DWORD is not
// used.
// If biClrUsed=3, biCompression=BITFIELDS(3),
// biColors[0] = red mask (0x00FF0000),
// biColors[1] = green mask (0x0000FF00), and
// biColors[2] = blue mask (0x000000FF),
// then tese masks are used with each 4-byte
// DWORD in the bitmap array to determine
// the pixel's relative intensities. //
// For other possibilities, see
// http://msdn.microsoft.com/default.asp
unsigned int biCompression; // DWORD Currently, Windows defines the following
// types of compression.
// =0 BI_RGB (no compression)
// =1 BI_RLE8 (run length encoded used for 8 bpp)
// =2 BI_RLE4 (run length encoded used for 4 bpp)
// =3 BI_BITFIELDS Specifies that the bitmap is
// not compressed and that the color table
// consists of three DWORD color masks that
// specify the red, green, and blue components,
// respectively, of each pixel. This is valid
// when used with 16- and 32-bit-per-pixel
// bitmaps.
// =4 BI_JPEG (not supported in Win 95/NT4)
//
unsigned int biSizeImage; // DWORD = bytes in image
int biXPelsPerMeter; // LONG
int biYPelsPerMeter; // LONG
unsigned int biClrUsed; // DWORD = 0 or true length of bmiColors[] array. If 0,
// then the value of biBitCount determines the
// length of the bmiColors[] array.
unsigned int biClrImportant; // DWORD
};
struct ON_WindowsBITMAPINFO
{
// Mimics Windows BITMAPINFO structure.
// For details searh for "BITMAPINFO" at http://msdn.microsoft.com/default.asp
ON_WindowsBITMAPINFOHEADER bmiHeader;
ON_WindowsRGBQUAD bmiColors[1]; // The "[1]" is for the compiler. In
// practice this array commonly has
// length 0, 3, or 256 and a BITMAPINFO*
// points to a contiguous piece of memory
// that contains
//
// BITMAPINFOHEADER
// RGBQUAD[length determined by flags]
// unsigned char[biSizeImage]
//
// See the ON_WindowsBITMAPINFOHEADER comments
// and http://msdn.microsoft.com/default.asp
// for more details.
};
#endif
class ON_CLASS ON_WindowsBitmap : public ON_Bitmap
{
ON_OBJECT_DECLARE(ON_WindowsBitmap);
// Uncompressed 8 bpp, 24 bpp, or 32 bpp Windows device
// independent bitmaps (DIB)
public:
ON_WindowsBitmap() = default;
~ON_WindowsBitmap();
ON_WindowsBitmap(const ON_WindowsBitmap&);
ON_WindowsBitmap& operator=(const ON_WindowsBitmap&);
static const ON_WindowsBitmap Unset;
/*
Parameters:
width - [in]
height - [in]
bits_per_pixel - [in]
1, 2, 4, 8, 16, 24, or 32
*/
bool Create(
int width,
int height,
int bits_per_pixel
);
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
bool IsEmpty() const;
bool Write( ON_BinaryArchive& ) const override; // writes compressed image
bool Read( ON_BinaryArchive& ) override; // reads compressed image
unsigned int SizeOf() const override;
public:
bool WriteCompressed( ON_BinaryArchive& ) const;
bool ReadCompressed( ON_BinaryArchive& );
bool WriteUncompressed( ON_BinaryArchive& ) const;
bool ReadUncompressed( ON_BinaryArchive& );
public:
int Width() const override;
int Height() const override; // >0 means it's a bottom-up bitmap with origin at lower right
// <0 means it's a top-down bitmap with origin at upper left
int PaletteColorCount() const; // number of colors in palette
int SizeofPalette() const; // number of bytes in palette
int BitsPerPixel() const override;
size_t SizeofScan() const override; // number of bytes per scan line
size_t SizeofImage() const override; // number of bytes in image
unsigned char* Bits(
int // index of scan line
) override;
const unsigned char* Bits(
int // index of scan line
) const override;
//int PaletteIndex( ON_Color ) const; // for 8bpp bitmaps
ON_Color Pixel(
int, // 0 <= i < width
int // 0 <= j < height
) const;
ON_Color Pixel(
int, // 0 <= i < width
const unsigned char* // value of Bits( j )
) const;
//bool SetColor( // sets entire map to specified color
// ON_Color
// );
#if defined(ON_OS_WINDOWS_GDI)
/*
Description:
Create an ON_WindowsBitmap from a contiguous bitmap.
Copies src.
Parameters:
src - [in] contiguous Windows device independent bitmap.
Remarks:
If the current Windows BITMAPINFO is identical to ON_WindowsBITMAPINFO,
then the result of this call is identical to
int color_count = number of colors in bitmap's palette;
ON_WindowsBitmap::Create( &src, &src.bmiColors[color_count], true ).
See Also:
ON_WindowsBitmap::Create
*/
ON_WindowsBitmap( const BITMAPINFO& src );
/*
Description:
Create an ON_WindowsBitmap from a contiguous bitmap.
Shares bitmap memory with src.
Parameters:
src - [in] contiguous Windows device independent bitmap.
See Also:
ON_WindowsBitmap::Create
Remarks:
~ON_WindowsBitmap will not delete src.
*/
ON_WindowsBitmap( const BITMAPINFO* src );
/*
Description:
Create an ON_WindowsBitmap from a contiguous bitmap.
Copies src.
Parameters:
src - [in] contiguous Windows device independent bitmap.
See Also:
ON_WindowsBitmap::Create
*/
ON_WindowsBitmap& operator=( const BITMAPINFO& src );
/*
Description:
Create and ON_WindowsBitmap from a Windows BITMAPINFO pointer
and a pointer to the bits.
This is intended to make it easy to write compressed bimaps.
For ON_WindowsBitmap classes created with ON_WindowsBitmap::Share,
ON_WindowsBitmap::Destroy and ~ON_WindowsBitmap will
not free the bmi and bits memory.
Parameters:
bmi - [in] valid BITMAPINFO
bits - [in] bits for BITMAPINFO
bCopy - [in] If true, the bmi and bits are copied into a contiguous
bitmap that will be deleted by ~ON_WindowsBitmap.
If false, the m_bmi and m_bits pointers on this class
are simply set to bmi and bits. In this case,
~ON_WindowsBitmap will not free the bmi or bits
memory.
Example:
ON_BinaryArchive archive = ...;
BITMAPINFO* bmi = 0;
unsigned char* bits = 0;
int color_count = ...; // number of colors in palette
int sizeof_palette = sizeof(bmi->bmiColors[0]) * color_count;
BITMAPINFO* bmi = (LPBITMAPINFO)calloc( 1, sizeof(*bmi) + sizeof_palette );
bmi->bmiHeader.biSize = sizeof(bmi->bmiHeader);
bmi->bmiHeader.biWidth = width;
bmi->bmiHeader.biHeight = height;
bmi->bmiHeader.biPlanes = 1;
bmi->bmiHeader.biBitCount = (USHORT)color_depth;
bmi->bmiHeader.biCompression = BI_RGB;
bmi->bmiHeader.biXPelsPerMeter = 0;
bmi->bmiHeader.biYPelsPerMeter = 0;
bmi->bmiHeader.biClrUsed = 0;
bmi->bmiHeader.biClrImportant = 0;
bmi->bmiHeader.biSizeImage = GetStorageSize();
// initialize palette
...
HBITMAP hbm = ::CreateDIBSection( nullptr, bmi, ..., (LPVOID*)&bits, nullptr, 0);
{
// Use ON_WindowsBitmap to write a compressed bitmap to
// archive. Does not modify bmi or bits.
ON_WindowsBitmap onbm;
onbm.Create(bmi,bit,false);
onbm.Write( arcive );
}
*/
bool Create(
const BITMAPINFO* bmi,
const unsigned char* bits,
bool bCopy
);
#endif
/*
Returns:
True if m_bmi and m_bits are in a single contiguous
block of memory.
False if m_bmi and m_bits are in two blocks of memory.
*/
bool IsContiguous() const;
#if defined(ON_OS_WINDOWS_GDI)
BITMAPINFO* m_bmi = nullptr;
#else
struct ON_WindowsBITMAPINFO* m_bmi = nullptr;
/*
Description:
Create an ON_WindowsBitmap from a contiguous bitmap ON_WindowsBITMAPINFO.
Parameters:
src - [in]
A contiguous Windows device independent bitmap. This means that the
"bits" in the bitmap begin at the memory location &m_bits->bmiColors[0].
See Also:
Remarks:
~ON_WindowsBitmap will not delete src.
*/
bool Create (
const struct ON_WindowsBITMAPINFO* src
);
#endif
unsigned char* m_bits = nullptr;
private:
int m_bFreeBMI = 0; // 0 m_bmi and m_bits are not freed by ON_WindowsBitmap::Destroy
// 1 m_bmi memory is freed by ON_WindowsBitmap::Destroy
// 2 m_bits memory is freed by ON_WindowsBitmap::Destroy
// 3 m_bmi and m_bits memory is freed by ON_WindowsBitmap::Destroy
private:
bool Internal_WriteV5( ON_BinaryArchive& ) const;
bool Internal_ReadV5( ON_BinaryArchive& );
protected:
void Internal_Destroy();
void Internal_Copy(
const ON_WindowsBitmap& src
);
};
/*
Description:
ON_WindowsBitmapEx is identical to ON_WindowsBitmap except that
it's Read/Write functions save bitmap names.
*/
class ON_CLASS ON_WindowsBitmapEx : public ON_WindowsBitmap
{
ON_OBJECT_DECLARE(ON_WindowsBitmapEx);
public:
ON_WindowsBitmapEx() = default;
~ON_WindowsBitmapEx() = default;
ON_WindowsBitmapEx(const ON_WindowsBitmapEx&) = default;
ON_WindowsBitmapEx& operator=(const ON_WindowsBitmapEx&) = default;
static const ON_WindowsBitmapEx Unset;
bool Write( ON_BinaryArchive& ) const override; // writes compressed image
bool Read( ON_BinaryArchive& ) override; // reads compressed image
private:
bool Internal_WriteV5( ON_BinaryArchive& ) const; // writes compressed image
bool Internal_ReadV5( ON_BinaryArchive& ); // reads compressed image
};
class ON_CLASS ON_EmbeddedBitmap : public ON_Bitmap
{
ON_OBJECT_DECLARE(ON_EmbeddedBitmap);
public:
ON_EmbeddedBitmap() = default;
~ON_EmbeddedBitmap();
ON_EmbeddedBitmap(const ON_EmbeddedBitmap&);
ON_EmbeddedBitmap& operator=(const ON_EmbeddedBitmap&);
static const ON_EmbeddedBitmap Unset;
void Create(
size_t sizeof_buffer
);
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
bool Write( ON_BinaryArchive& ) const override;
bool Read( ON_BinaryArchive& ) override;
unsigned int SizeOf() const override;
size_t SizeofImage() const override;
unsigned char* Bits(int) override;
const unsigned char* Bits(int) const override;
const void* m_buffer = nullptr;
size_t m_sizeof_buffer = 0;
bool m_managed_buffer = false; // true means the ON_EmbeddedBitmap class manages m_buffer memory.
ON__UINT32 m_buffer_crc32 = 0; // 32 bit crc from ON_CRC32
private:
bool Internal_WriteV5( ON_BinaryArchive& ) const;
bool Internal_ReadV5( ON_BinaryArchive& );
private:
void Internal_Destroy();
void Internal_Copy(
const ON_EmbeddedBitmap& src
);
};
#endif
+914
View File
@@ -0,0 +1,914 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(ON_BOUNDING_BOX_INC_)
#define ON_BOUNDING_BOX_INC_
////////////////////////////////////////////////////////////////
//
// ON_BoundingBox - axis aligned bounding box
//
class ON_CLASS ON_BoundingBox
{
public:
static const ON_BoundingBox EmptyBoundingBox; // ((1.0,0.0,0.0),(-1.0,0.0,0.0))
static const ON_BoundingBox UnsetBoundingBox; // all coordinates are ON_UNSET_VALUE
static const ON_BoundingBox NanBoundingBox; // all coordinates are ON_DBL_QNAN
ON_BoundingBox() ON_NOEXCEPT; // creates EmptyBoundingBox
~ON_BoundingBox() = default;
ON_BoundingBox(const ON_BoundingBox&) = default;
ON_BoundingBox& operator=(const ON_BoundingBox&) = default;
explicit ON_BoundingBox(
const ON_3dPoint&, // min corner of axis aligned bounding box
const ON_3dPoint& // max corner of axis aligned bounding box
);
// OBSOLETE
// temporary - use ON_ClippingRegion - this function will be removed soon.
int IsVisible(
const ON_Xform& bbox2c
) const;
// OBSOLETE
void Destroy(); // set this = ON_BoundingBox::EmptyBoundingBox
// operator[] returns min if index <= 0 and max if indes >= 1
ON_3dPoint& operator[](int);
const ON_3dPoint& operator[](int) const;
ON_3dPoint Min() const;
ON_3dPoint Max() const;
ON_3dVector Diagonal() const; // max corner - min corner
ON_3dPoint Center() const;
ON_3dPoint Corner( // 8 corners of box
int, // x_index 0 = Min().x, 1 = Max().x
int, // y_index 0 = Min().y, 1 = Max().y
int // z_index 0 = Min().z, 1 = Max().z
) const;
bool GetCorners(
ON_3dPointArray& box_corners // returns list of 8 corner points
) const;
bool GetCorners(
ON_3dPoint box_corners[8] // returns list of 8 corner points
) const;
/*
Parameters:
edges[] - out
12 edge lines. If the bounding box has no height, width or depth,
then the corresponding edges will have the same "from" and "to"
points.
Returns:
If the bounding box is valid, then true is returned and
12 line segments, some possibly a single point, are returned.
Otherwise false is returned and 12 line segments with "from"
and "to" points set to ON_3dPoint::UnsetPoint are returned.
*/
bool GetEdges(
ON_Line edges[12] // returns list of 12 edge segments
) const;
// OBSOLETE IsValid() = IsNotEmpty()
bool IsValid() const; // empty boxes are not valid
bool IsSet() const; // every coordinate is a finite, valid double, not ON_UNSET_VALUE and not ON_UNSET_POSITIVE_VALUE
bool IsUnset() const; // some coordinate is ON_UNSET_VALUE or ON_UNSET_POSITIVE_VALUE
bool IsNan() const; // some coordinate is a NAN
bool IsUnsetOrNan() const; // = IsUnset() or IsNan()
bool IsEmpty() const; // (m_min.x > m_max.x || m_min.y > m_max.y || m_min.z > m_max.z) && IsSet();
bool IsNotEmpty() const; // (m_min.x <= m_max.x && m_min.y <= m_max.y && m_min.z <= m_max.z) && IsSet()
bool IsPoint() const; // (m_min.x == m_max.x && m_min.y == m_max.y && m_min.z == m_max.z) && IsSet()
void Dump(class ON_TextLog&) const;
/*
Description:
Test a bounding box to see if it is degenerate (flat)
in one or more directions.
Parameters:
tolerance - [in] Distances <= tolerance will be considered
to be zero. If tolerance is negative (default), then
a scale invarient tolerance is used.
Returns:
@untitled table
0 box is not degenerate
1 box is a rectangle (degenerate in one direction)
2 box is a line (degenerate in two directions)
3 box is a point (degenerate in three directions)
4 box is not valid
*/
int IsDegenerate(
double tolerance = ON_UNSET_VALUE
) const;
//////////
// ON_BoundingBox::Transform() updates the bounding box
// to be the smallest axis aligned bounding box that contains
// the transform of the eight corner points of the input
// bounding box.
bool Transform( const ON_Xform& );
double Tolerance() const; // rough guess at a tolerance to use for comparing
// objects in this bounding box
// All of these Set() functions set or expand a box to enclose the points in the arguments
// If bGrowBox is true, the existing box is expanded, otherwise it is only set to the current point list
bool Set(
int dim,
bool is_rat,
int count,
int stride,
const double* point_array,
int bGrowBox = false
);
bool Set(
const ON_3dPoint& point,
int bGrowBox = false
);
bool Set(
const ON_2dPoint& point,
int bGrowBox = false
);
bool Set(
const ON_SimpleArray<ON_4dPoint>& point_array,
int bGrowBox = false
);
bool Set(
const ON_SimpleArray<ON_3dPoint>& point_array,
int bGrowBox = false
);
bool Set(
const ON_SimpleArray<ON_2dPoint>& point_array,
int bGrowBox = false
);
bool Set(
int dim,
bool is_rat,
int count,
int stride,
const float* point_array,
int bGrowBox = false
);
bool Set(
const ON_3fPoint& point,
int bGrowBox = false
);
bool Set(
const ON_2fPoint& point,
int bGrowBox = false
);
bool Set(
const ON_SimpleArray<ON_4fPoint>& point_array,
int bGrowBox = false
);
bool Set(
const ON_SimpleArray<ON_3fPoint>& point_array,
int bGrowBox = false
);
bool Set(
const ON_SimpleArray<ON_2fPoint>& point_array,
int bGrowBox = false
);
bool IsPointIn(
const ON_3dPoint& test_point, // point to test
int bStrictlyIn = false
// true to test for strict ( min < point < max )
// false to test for (min <= point <= max)
//
) const;
//////////
// Point on or in the box that is closest to test_point.
// If test_point is in or on the box, the test_point is returned.
ON_3dPoint ClosestPoint(
const ON_3dPoint& test_point
) const;
/*
Description:
Quickly find a lower bound on the distance
between the point and this bounding box.
Parameters:
P - [in]
Returns:
A distance that is less than or equal to the shortest
distance from the line to this bounding box.
Put another way, if Q is any point in this bounding box,
then P.DistanceTo(Q) >= MinimumDistanceTo(bbox).
*/
double MinimumDistanceTo( const ON_3dPoint& P ) const;
/*
Description:
Quickly find an upper bound on the distance
between the point and this bounding box.
Parameters:
P - [in]
Returns:
A distance that is greater than or equal to the
longest distance from the point P to this bounding box.
Put another way, if Q is any point in this bounding box,
then P.DistanceTo(Q) <= MaximumDistanceTo(bbox).
*/
double MaximumDistanceTo( const ON_3dPoint& P ) const;
/*
Description:
Quickly find a lower bound on the distance
between this and the other bounding box.
Parameters:
other - [in]
Returns:
A distance that is less than or equal to the shortest
distance between the bounding boxes.
Put another way, if Q is any point in this bounding box
and P is any point in the other bounding box,
then P.DistanceTo(Q) >= MinimumDistanceTo(bbox).
*/
double MinimumDistanceTo( const ON_BoundingBox& other ) const;
/*
Description:
Quickly find an upper bound on the distance
between this and the other bounding box.
Parameters:
other - [in]
Returns:
A distance that is greater than or equal to the longest
distance between the bounding boxes.
Put another way, if Q is any point in this bounding box
and P is any point in the other bounding box,
then P.DistanceTo(Q) <= MaximumDistanceTo(bbox).
*/
double MaximumDistanceTo( const ON_BoundingBox& other ) const;
/*
Description:
Quickly find a lower bound on the distance
between the line segment and this bounding box.
Parameters:
line - [in]
Returns:
A distance that is less than or equal to the shortest
distance from the line to this bounding box.
Put another way, if Q is any point on line
and P is any point in this bounding box, then
P.DistanceTo(Q) >= MinimumDistanceTo(bbox).
*/
double MinimumDistanceTo( const ON_Line& line ) const;
/*
Description:
Quickly find a tight lower bound on the distance
between the plane and this bounding box.
Parameters:
plane - [in]
Returns:
The minimum distance between a point on the plane
and a point on the bounding box.
See Also:
ON_PlaneEquation::MimimumValueAt
ON_PlaneEquation::MaximumValueAt
*/
double MinimumDistanceTo( const ON_Plane& plane ) const;
double MinimumDistanceTo( const ON_PlaneEquation& plane_equation ) const;
/*
Description:
Quickly find an upper bound on the distance
between the line segment and this bounding box.
Parameters:
line - [in]
Returns:
A distance that is greater than or equal to the
longest distance from the line to this bounding box.
Put another way, if Q is any point on the line
and P is any point in this bounding box, then
P.DistanceTo(Q) <= MaximumDistanceTo(bbox).
*/
double MaximumDistanceTo( const ON_Line& line ) const;
/*
Description:
Quickly find a tight upper bound on the distance
between the plane and this bounding box.
Parameters:
plane - [in]
Returns:
A distance that is equal to the longest distance from
the plane to this bounding box. Put another way,
if Q is any point on the plane and P is any point
in this bounding box, then
P.DistanceTo(Q) <= MaximumDistanceTo(bbox) and there
is at least one point on the bounding box where the
distance is equal to the returned value.
See Also:
ON_PlaneEquation::MaximumValueAt
*/
double MaximumDistanceTo( const ON_Plane& plane ) const;
double MaximumDistanceTo( const ON_PlaneEquation& plane_equation ) const;
/*
Description:
Quickly determine if the shortest distance from
the point P to the bounding box is greater than d.
Parameters:
d - [in] distance (> 0.0)
P - [in]
Returns:
True if if the shortest distance from the point P
to the bounding box is greater than d.
*/
bool IsFartherThan( double d, const ON_3dPoint& P ) const;
/*
Description:
Quickly determine if the shortest distance from the line
to the bounding box is greater than d.
Parameters:
d - [in] distance (> 0.0)
line - [in]
Returns:
True if the shortest distance from the line
to the bounding box is greater than d. It is not the
case that false means that the shortest distance
is less than or equal to d.
*/
bool IsFartherThan( double d, const ON_Line& line ) const;
/*
Description:
Quickly determine if the shortest distance from the plane
to the bounding box is greater than d.
Parameters:
d - [in] distance (> 0.0)
plane - [in]
Returns:
True if the shortest distance from the plane
to the bounding box is greater than d, and false
if the shortest distance is less than or equal to d.
*/
bool IsFartherThan( double d, const ON_Plane& plane ) const;
/*
Description:
Quickly determine if the shortest distance from the plane
to the bounding box is greater than d.
Parameters:
d - [in] distance (> 0.0)
plane_equation - [in] (the first three coefficients
are assumed to be a unit vector.
If not, adjust your d accordingly.)
Returns:
True if the shortest distance from the plane
to the bounding box is greater than d, and false
if the shortest distance is less than or equal to d.
*/
bool IsFartherThan( double d, const ON_PlaneEquation& plane_equation ) const;
/*
Description:
Quickly determine if the shortest distance this bounding
box to another bounding box is greater than d.
Parameters:
d - [in] distance (> 0.0)
other - [in] other bounding box
Returns:
True if if the shortest distance from this bounding
box to the other bounding box is greater than d.
*/
bool IsFartherThan( double d, const ON_BoundingBox& other ) const;
// Description:
// Get point in a bounding box that is closest to a line
// segment.
// Parameters:
// line - [in] line segment
// box_point - [out] point in box that is closest to line
// segment point at t0.
// t0 - [out] parameter of point on line that is closest to
// the box.
// t1 - [out] parameter of point on line that is closest to
// the box.
// Returns:
// 3 success - line segments intersects box in a segment
// from line(t0) to line(t1) (t0 < t1)
// 2 success - line segments intersects box in a single point
// at line(t0) (t0==t1)
// 1 success - line segment does not intersect box. Closest
// point on the line is at line(t0) (t0==t1)
// 0 failure - box is invalid.
// Remarks:
// The box is treated as a solid box. If the intersection
// of the line segment, then 3 is returned.
int GetClosestPoint(
const ON_Line&, // line
ON_3dPoint&, // box_point
double*, // t0
double* // t1
) const;
//////////
// Get points on bounding boxes that are closest to each other.
// If the boxes intersect, then the point at the centroid of the
// intersection is returned for both points.
bool GetClosestPoint(
const ON_BoundingBox&, // "other" bounding box
ON_3dPoint&, // point on "this" box that is closest to "other" box
ON_3dPoint& // point on "other" box that is closest to "this" box
) const;
//////////
// Point on the box that is farthest from the test_point.
ON_3dPoint FarPoint(
const ON_3dPoint& // test_point
) const;
//////////
// Get points on bounding boxes that are farthest from each other.
bool GetFarPoint(
const ON_BoundingBox&, // "other" bounding box
ON_3dPoint&, // point on "this" box that is farthest from "other" box
ON_3dPoint& // point on "other" box that is farthest from "this" box
) const;
/*
Description:
Intersect this with other_bbox and save intersection in this.
Parameters:
other_bbox - [in]
Returns:
True if this-intesect-other_bbox is a non-empty valid bounding box
and this is set. False if the intersection is empty, in which case
"this" is set to an invalid bounding box.
Remarks:
If "this" or other_bbox is invalid, they are treated as
the empty set, and false is returned.
*/
bool Intersection(
const ON_BoundingBox& other_bbox
);
/*
Description:
Set "this" to the intersection of bbox_A and bbox_B.
Parameters:
bbox_A - [in]
bbox_B - [in]
Returns:
True if the "this" is a non-empty valid bounding box.
False if the intersection is empty, in which case
"this" is set to an invalid bounding box.
Remarks:
If bbox_A or bbox_B is invalid, they are treated as
the empty set, and false is returned.
*/
bool Intersection( // this = intersection of two args
const ON_BoundingBox& bbox_A,
const ON_BoundingBox& bbox_B
);
bool Intersection( //Returns true when intersect is non-empty.
const ON_Line&, //Infinite Line segment to intersect with
double* =nullptr , // t0 parameter of first intersection point
double* =nullptr // t1 parameter of last intersection point (t0<=t1)
) const;
/*
Description:
Test a box to see if it is contained in this box.
Parameters:
other - [in] box to test
bProperSubSet - [in] if true, then the test is for a proper inclusion.
Returns:
If bProperSubSet is false, then the result is true when
this->m_min[i] <= other.m_min[i] and other.m_max[i] <= this->m_max[i].
for i=0,1 and 2.
If bProperSubSet is true, then the result is true when
the above condition is true and at least one of the inequalities is strict.
*/
bool Includes(
const ON_BoundingBox& other,
bool bProperSubSet = false
) const;
double Volume() const;
double Area() const;
// Union() returns true if union is not empty.
// Invalid boxes are treated as the empty set.
bool Union( // this = this union arg
const ON_BoundingBox&
);
bool Union( // this = union of two args
const ON_BoundingBox&,
const ON_BoundingBox&
);
/*
Description:
Test to see if "this" and other_bbox are disjoint (do not intersect).
Parameters:
other_bbox - [in]
Returns:
True if "this" and other_bbox are disjoint.
Remarks:
If "this" or other_bbox is invalid, then true is returned.
*/
bool IsDisjoint(
const ON_BoundingBox& other_bbox
) const;
/*
Description:
Test to see if "this" and line are disjoint (do not intersect or line is included).
Parameters:
line - [in]
infinite - [in] if false or not provided, then the line is considered bounded by start and end points.
Returns:
True if "this" and line are disjoint.
*/
bool IsDisjoint(const ON_Line& line) const;
bool IsDisjoint(const ON_Line& line, bool infinite) const;
bool SwapCoordinates( int, int );
/*
Description:
Expand the box by adding delta to m_max and subtracting
it from m_min. So, when delta is positive and the interval is
increasing this function expands the box on each side.
Returns:
true if the result is Valid.
*/
bool Expand(ON_3dVector delta);
ON_3dPoint m_min;
ON_3dPoint m_max;
};
/*
Returns:
True if lhs and rhs are identical.
*/
ON_DECL
bool operator==( const ON_BoundingBox& lhs, const ON_BoundingBox& rhs );
/*
Returns:
True if lhs and rhs are not equal.
*/
ON_DECL
bool operator!=( const ON_BoundingBox& lhs, const ON_BoundingBox& rhs );
class ON_CLASS ON_BoundingBoxAndHash
{
public:
ON_BoundingBoxAndHash() = default;
~ON_BoundingBoxAndHash() = default;
ON_BoundingBoxAndHash(const ON_BoundingBoxAndHash&) = default;
ON_BoundingBoxAndHash& operator=(const ON_BoundingBoxAndHash&) = default;
public:
// This hash depends on the context and is a hash
// of the information used to calculte the bounding box.
// It is not the hash of the box values
void Set(
const ON_BoundingBox& bbox,
const ON_SHA1_Hash& hash
);
const ON_BoundingBox& BoundingBox() const;
const ON_SHA1_Hash& Hash() const;
/*
Returns:
True if bounding box IsSet() is true and hash is not EmptyContentHash.
*/
bool IsSet() const;
bool Write(
class ON_BinaryArchive& archive
) const;
bool Read(
class ON_BinaryArchive& archive
);
private:
ON_BoundingBox m_bbox = ON_BoundingBox::UnsetBoundingBox;
ON_SHA1_Hash m_hash = ON_SHA1_Hash::EmptyContentHash;
};
/*
A class that caches 8 bounding box - hash pairs and keeps the most frequently
used bounding boxes.
*/
class ON_CLASS ON_BoundingBoxCache
{
public:
ON_BoundingBoxCache() = default;
~ON_BoundingBoxCache() = default;
ON_BoundingBoxCache(const ON_BoundingBoxCache&) = default;
ON_BoundingBoxCache& operator=(const ON_BoundingBoxCache&) = default;
public:
/*
Description:
Add a bounding box that can be found from a hash value.
Parameters:
bbox - [in]
hash - [in]
A hash of the information needed to create this bounding box.
*/
void AddBoundingBox(
const ON_BoundingBox& bbox,
const ON_SHA1_Hash& hash
);
void AddBoundingBox(
const ON_BoundingBoxAndHash& bbox_and_hash
);
/*
Description:
Get a cached bounding box.
Parameters:
hash - [in]
bbox - [out]
If the hash identifies a bounding box in the cache, then
that bounding box is returned. Otherwise ON_BoundingBox::NanBoundingBox
is returned.
Returns:
true - cached bounding box returned
false - bounding box not in cache.
*/
bool GetBoundingBox(
const ON_SHA1_Hash& hash,
ON_BoundingBox& bbox
) const;
/*
Description:
Remove a bounding box that can be found from a hash value.
Parameters:
hash - [in]
Returns:
true - hash was in the cache and removed.
false - hash was not in the cache.
Remarks:
If the hash values you are using are correctly computed and include
all information that the bouding box depends on, then
you never need to remove bounding boxes. Unused ones will get
removed as new ones are added.
*/
bool RemoveBoundingBox(
const ON_SHA1_Hash& hash
);
/*
Description:
Removes all bounding boxes.
Remarks:
If the hash values you are using are correctly computed and include
all information that the bouding box depends on, then
you never need to remove bounding boxes. Unused ones will get
removed as new ones are added.
If the hash does not include all information required to compute
the bounding boxes, then call RemoveAllBoundingBoxes() when the
non-hashed information changes.
*/
void RemoveAllBoundingBoxes();
/*
Returns:
Number of cached boxes.
*/
unsigned int BoundingBoxCount() const;
bool Write(
class ON_BinaryArchive& archive
) const;
bool Read(
class ON_BinaryArchive& archive
);
private:
// number of boxes set in m_cache[]
unsigned int m_count = 0;
// capacity of m_cache[] - set when needed
unsigned int m_capacity = 0;
// Bounding box cache. Most recently used boxes are first.
mutable ON_BoundingBoxAndHash m_cache[8];
/*
Returns:
m_cache[] array index of box with the hash.
ON_UNSET_UINT_INDEX if hash is not present in m_cache[] array.
*/
unsigned int Internal_CacheIndex(const ON_SHA1_Hash& hash) const;
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_BoundingBox>;
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_BoundingBoxAndHash>;
#endif
/*
Description:
Get a tight bounding box that contains the points.
Parameters:
dim - [in] (>=1)
is_rat - [in] true if points are rational
count - [in] number of points
stride - [in] stride between points
point_list - [in]
bbox - [in/out]
bGrowBox - [in] (default = false)
If the input bbox is valid and bGrowBox is true,
then the output bbox is the union of the input
bbox and the bounding box of the point list.
xform - [in] (default = nullptr)
If not null, the bounding box of the transformed
points is calculated. The points are not modified.
Returns:
True if the output bbox is valid.
*/
ON_DECL
bool ON_GetPointListBoundingBox(
int dim,
bool is_rat,
int count,
int stride,
const double* point_list,
ON_BoundingBox& bbox,
int bGrowBox = false,
const ON_Xform* xform = 0
);
ON_DECL
bool ON_GetPointListBoundingBox(
int dim,
bool is_rat,
int count,
int stride,
const float* point_list,
ON_BoundingBox& bbox,
int bGrowBox = false,
const ON_Xform* xform = 0
);
ON_DECL
bool ON_GetPointListBoundingBox(
int dim,
bool is_rat,
int count,
int stride,
const double* point_list,
double* boxmin, // min[dim]
double* boxmax, // max[dim]
int bGrowBox
);
ON_DECL
ON_BoundingBox ON_PointListBoundingBox(
int dim,
bool is_rat,
int count,
int stride,
const double* point_list
);
ON_DECL
bool ON_GetPointListBoundingBox(
int dim,
bool is_rat,
int count,
int stride,
const float* point_list,
float* boxmin, // min[dim]
float* boxmax, // max[dim]
int bGrowBox
);
ON_DECL
ON_BoundingBox ON_PointListBoundingBox( // low level workhorse function
int dim,
bool is_rat,
int count,
int stride,
const float* point_list
);
ON_DECL
bool ON_GetPointGridBoundingBox(
int dim,
bool is_rat,
int point_count0, int point_count1,
int point_stride0, int point_stride1,
const double* point_grid,
double* boxmin, // min[dim]
double* boxmax, // max[dim]
int bGrowBox
);
ON_DECL
ON_BoundingBox ON_PointGridBoundingBox(
int dim,
bool is_rat,
int point_count0, int point_count1,
int point_stride0, int point_stride1,
const double* point_grid
);
ON_DECL
double ON_BoundingBoxTolerance(
int dim,
const double* bboxmin,
const double* bboxmax
);
/*
Description:
Determine if an object is too large or too far
from the origin for single precision coordinates
to be useful.
Parameters:
bbox - [in]
Bounding box of an object with single precision
coordinates. An ON_Mesh is an example of an
object with single precision coordinates.
xform - [out]
If this function returns false and xform is not
null, then the identity transform is returned.
If this function returns true and xform is not
null, then the transform moves the region
contained in bbox to a location where single
precision coordinates will have enough
information for the object to be useful.
Returns:
true:
The region contained in bbox is too large
or too far from the origin for single
precision coordinates to be useful.
false:
A single precision object contained in bbox
will be satisfactory for common calculations.
*/
ON_DECL
bool ON_BeyondSinglePrecision( const ON_BoundingBox& bbox, ON_Xform* xform );
ON_DECL
bool ON_WorldBBoxIsInTightBBox(
const ON_BoundingBox& tight_bbox,
const ON_BoundingBox& world_bbox,
const ON_Xform* xform
);
#endif
+120
View File
@@ -0,0 +1,120 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(ON_BOX_INC_)
#define ON_BOX_INC_
class ON_CLASS ON_Box
{
public:
ON_Plane plane;
// intervals are finite and increasing when the box is valid
ON_Interval dx;
ON_Interval dy;
ON_Interval dz;
ON_Box();
ON_Box( const ON_BoundingBox& bbox );
~ON_Box();
bool IsValid() const;
bool Create( const ON_BoundingBox& bbox );
void Destroy();
ON_3dPoint Center() const;
bool GetCorners( ON_3dPoint* corners ) const;
bool GetCorners( ON_SimpleArray<ON_3dPoint>& corners ) const;
ON_BoundingBox BoundingBox() const;
ON_3dPoint PointAt(
double r,
double s,
double t
) const;
bool ClosestPointTo(
ON_3dPoint point,
double* r,
double* s,
double* t
) const;
// returns point on box that is closest to given point
ON_3dPoint ClosestPointTo(
ON_3dPoint test_point
) const;
// rotate sphere about its origin
bool Rotate(
double sin_angle, // sin(angle)
double cos_angle, // cos(angle)
const ON_3dVector& axis_of_rotation // axis of rotation
);
bool Rotate(
double angle_radians, // angle in radians
const ON_3dVector& axis_of_rotation // axis of rotation
);
// rotate sphere about a point and axis
bool Rotate(
double sin_angle, // sin(angle)
double cos_angle, // cos(angle)
const ON_3dVector& axis_of_rotation, // axis of rotation
const ON_3dPoint& center_of_rotation // center of rotation
);
bool Rotate(
double angle_radians, // angle in radians
const ON_3dVector& axis_of_rotation, // axis of rotation
const ON_3dPoint& center_of_rotation // center of rotation
);
bool Translate(
const ON_3dVector&
);
bool Transform( const ON_Xform& );
/*
Description:
Test the box to see if it is degenerate (flat)
in one or more directions.
Parameters:
tolerance - [in] Distances <= tolerance will be considered
to be zero. If tolerance is negative (default), then
a scale invarient tolerance is used.
Returns:
@untitled table
0 box is not degenerate
1 box is a rectangle (degenerate in one direction)
2 box is a line (degenerate in two directions)
3 box is a point (degenerate in three directions)
4 box is not valid
*/
int IsDegenerate(
double tolerance = ON_UNSET_VALUE
) const;
double Volume() const;
double Area() const;
};
#endif
File diff suppressed because it is too large Load Diff
+325
View File
@@ -0,0 +1,325 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(ON_CIRCLE_INC_)
#define ON_CIRCLE_INC_
class ON_NurbsCurve;
/*
Description:
ON_Circle is a circle in 3d. The cirle is represented by a radius and an
orthonormal frame of the plane containing the circle, with origin at the center.
An Is_Valid() circle has positive radius and an Is_ Valid() plane defining the frame.
The circle is parameterized by radians from 0 to 2 Pi given by
t -> center + cos(t)*radius*xaxis + sin(t)*radius*yaxis
where center, xaxis and yaxis define the orthonormal frame of the circle's plane.
*/
class ON_CLASS ON_Circle
{
public:
ON_Plane plane = ON_Plane::World_xy;
double radius = 1.0;
ON_Circle() = default;
~ON_Circle() = default;
ON_Circle(const ON_Circle&) = default;
ON_Circle& operator=(const ON_Circle&) = default;
static const ON_Circle UnitCircle; // unit circle in the xy plane
// Creates a circle in the plane with center at
// plane.origin.
ON_Circle(
const ON_Plane& plane,
double radius
);
// Creates a circle parallel to the world XY plane
// with given center and radius
ON_Circle(
const ON_3dPoint& center,
double radius
);
// Creates a circle parallel to the plane
// with given center and radius.
ON_Circle(
const ON_Plane& plane,
const ON_3dPoint& center,
double radius
);
// Create a circle through three 2d points.
// The start/end of the circle is at point P.
ON_Circle( // circle through 3 2d points
const ON_2dPoint& P,
const ON_2dPoint& Q,
const ON_2dPoint& R
);
// Create a circle through three 3d points.
// The start/end of the circle is at point P.
ON_Circle(
const ON_3dPoint& P,
const ON_3dPoint& Q,
const ON_3dPoint& R
);
// Creates a circle in the plane with center at
// plane.origin.
bool Create(
const ON_Plane& plane,
double radius
);
// Creates a circle parallel to the world XY plane
// with given center and radius
bool Create(
const ON_3dPoint& center,
double radius
);
// Creates a circle parallel to the plane
// with given centr and radius.
bool Create(
const ON_Plane& plane,
const ON_3dPoint& center,
double radius
);
// Create a circle through three 2d points.
// The start/end of the circle is at point P.
bool Create( // circle through 3 2d points
const ON_2dPoint& P,
const ON_2dPoint& Q,
const ON_2dPoint& R
);
// Create a circle through three 3d points.
// The start/end of the circle is at point P.
bool Create(
const ON_3dPoint& P,
const ON_3dPoint& Q,
const ON_3dPoint& R
);
// Create a circle from two 2d points and a
// tangent at the first point.
// The start/end of the circle is at point P.
bool Create(
const ON_2dPoint& P,
const ON_2dVector& tangent_at_P,
const ON_2dPoint& Q
);
// Create a circle from two 3d points and a
// tangent at the first point.
// The start/end of the circle is at point P.
bool Create(
const ON_3dPoint& P,
const ON_3dVector& tangent_at_P,
const ON_3dPoint& Q
);
// A Valid circle has m_radius>0 and m_plane.IsValid().
bool IsValid() const;
//bool UpdatePoints(); // sets m_point[] to have valid points
bool IsInPlane( const ON_Plane&, double = ON_ZERO_TOLERANCE ) const;
double Radius() const;
double Diameter() const;
double Circumference() const;
const ON_3dPoint& Center() const;
const ON_3dVector& Normal() const;
const ON_Plane& Plane() const; // plane containing circle
ON_BoundingBox BoundingBox() const;
/*
Description:
Get tight bounding box.
Parameters:
tight_bbox - [in/out] tight bounding box
bGrowBox -[in] (default=false)
If true and the input tight_bbox is valid, then returned
tight_bbox is the union of the input tight_bbox and the
arc's tight bounding box.
xform -[in] (default=nullptr)
If not nullptr, the tight bounding box of the transformed
arc is calculated. The arc is not modified.
Returns:
True if a valid tight_bbox is returned.
*/
bool GetTightBoundingBox(
ON_BoundingBox& tight_bbox,
bool bGrowBox = false,
const ON_Xform* xform = nullptr
) const;
bool Transform( const ON_Xform& );
// Circles use trigonometric parameterization
// t -> center + cos(t)*radius*xaxis + sin(t)*radius*yaxis
ON_3dPoint PointAt(
double // evaluation parameter
) const;
ON_3dVector DerivativeAt(
int, // derivative (>=0)
double // evaluation parameter
) const;
ON_3dVector TangentAt(double) const;
// returns parameters of point on circle that is closest to given point
bool ClosestPointTo(
const ON_3dPoint& point,
double* t
) const;
// returns point on circle that is closest to given point
ON_3dPoint ClosestPointTo(
const ON_3dPoint& point
) const;
// evaluate circle's implicit equation in plane
double EquationAt( const ON_2dPoint& plane_point ) const;
ON_2dVector GradientAt( const ON_2dPoint& plane_point ) const;
// rotate circle about its center
bool Rotate(
double sin_angle,
double cos_angle,
const ON_3dVector& axis_of_rotation
);
bool Rotate(
double angle_in_radians,
const ON_3dVector& axis_of_rotation
);
// rotate circle about a point and axis
bool Rotate(
double sin_angle,
double cos_angle,
const ON_3dVector& axis_of_rotation,
const ON_3dPoint& center_of_rotation
);
bool Rotate(
double angle_in_radians,
const ON_3dVector& axis_of_rotation,
const ON_3dPoint& center_of_rotation
);
bool Translate(
const ON_3dVector& delta
);
bool Reverse();
// Description:
// Get a four span rational degree 2 NURBS circle representation
// of the circle.
// Returns:
// 2 for success, 0 for failure
// Remarks:
// Note that the parameterization of NURBS curve
// does not match circle's transcendental paramaterization.
// Use ON_Circle::GetRadianFromNurbFormParameter() and
// ON_Circle::GetParameterFromRadian() to convert between
// the NURBS curve parameter and the transcendental parameter.
int GetNurbForm(
ON_NurbsCurve& nurbs_curve
) const;
/*
Description:
Convert a NURBS curve circle parameter to a circle radians parameter.
Parameters:
nurbs_parameter - [in]
circle_radians_parameter - [out]
Example:
ON_Circle circle = ...;
double nurbs_t = 1.2345; // some number in interval (0,2.0*ON_PI).
double circle_t;
circle.GetRadianFromNurbFormParameter( nurbs_t, &circle_t );
ON_NurbsCurve nurbs_curve;
circle.GetNurbsForm( nurbs_curve );
circle_pt = circle.PointAt(circle_t);
nurbs_pt = nurbs_curve.PointAt(nurbs_t);
// circle_pt and nurbs_pt will be the same
Remarks:
The NURBS curve parameter is with respect to the NURBS curve
created by ON_Circle::GetNurbForm. At nurbs parameter values of
0.0, 0.5*ON_PI, ON_PI, 1.5*ON_PI, and 2.0*ON_PI, the nurbs
parameter and radian parameter are the same. At all other
values the nurbs and radian parameter values are different.
See Also:
ON_Circle::GetNurbFormParameterFromRadian
*/
bool GetRadianFromNurbFormParameter(
double nurbs_parameter,
double* circle_radians_parameter
) const;
/*
Description:
Convert a circle radians parameter to a NURBS curve circle parameter.
Parameters:
circle_radians_parameter - [in] 0.0 to 2.0*ON_PI
nurbs_parameter - [out]
Example:
ON_Circle circle = ...;
double circle_t = 1.2345; // some number in interval (0,2.0*ON_PI).
double nurbs_t;
circle.GetNurbFormParameterFromRadian( circle_t, &nurbs_t );
ON_NurbsCurve nurbs_curve;
circle.GetNurbsForm( nurbs_curve );
circle_pt = circle.PointAt(circle_t);
nurbs_pt = nurbs_curve.PointAt(nurbs_t);
// circle_pt and nurbs_pt will be the same
Remarks:
The NURBS curve parameter is with respect to the NURBS curve
created by ON_Circle::GetNurbForm. At radian values of
0.0, 0.5*ON_PI, ON_PI, 1.5*ON_PI, and 2.0*ON_PI, the nurbs
parameter and radian parameter are the same. At all other
values the nurbs and radian parameter values are different.
See Also:
ON_Circle::GetNurbFormParameterFromRadian
*/
bool GetNurbFormParameterFromRadian(
double circle_radians_parameter,
double* nurbs_parameter
) const;
};
#endif
+448
View File
@@ -0,0 +1,448 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_COLOR_INC_)
#define OPENNURBS_COLOR_INC_
///////////////////////////////////////////////////////////////////////////////
//
// Class ON_Color
//
class ON_CLASS ON_Color
{
public:
ON_Color() = default;
~ON_Color() = default;
ON_Color(const ON_Color&) = default;
ON_Color& operator=(const ON_Color&) = default;
static const ON_Color UnsetColor; // 0xFFFFFFFFu
static const ON_Color Black; // 0x00000000u
static const ON_Color White; // 0x00FFFFFFu on little endan, 0xFFFFFF00u on big endian
static const ON_Color SaturatedRed; // 0x000000FFu on little endan, 0xFF000000u on big endian
static const ON_Color SaturatedGreen; // 0x0000FF00u on little endan, 0x00FF0000u on big endian
static const ON_Color SaturatedBlue; // 0x00FF0000u on little endan, 0x0000FF00u on big endian
static const ON_Color SaturatedYellow; // 0x0000FFFFu on little endan, 0xFFFF0000u on big endian
static const ON_Color SaturatedCyan; // 0x00FFFF00u on little endan, 0x00FFFF00u on big endian
static const ON_Color SaturatedMagenta; // 0x00FF00FFu on little endan, 0xFF00FF00u on big endian
static const ON_Color SaturatedGold; // 0x0000BFFFu on little endan, 0xFFBF0000u on big endian
static const ON_Color Gray105; // R = G = B = 105 (medium dark)
static const ON_Color Gray126; // R = G = B = 128 (medium)
static const ON_Color Gray160; // R = G = B = 160 (medium light)
static const ON_Color Gray230; // R = G = B = 230 (light)
static const ON_Color Gray250; // R = G = B = 250 (lightest)
// If you need to use byte indexing to convert RGBA components to and from
// an unsigned int ON_Color value and want your code to work on both little
// and big endian computers, then use the RGBA_byte_index enum.
//
// unsigned int u;
// unsigned char* rgba = &y;
// rbga[ON_Color::kRedByteIndex] = red value 0 to 255.
// rbga[ON_Color::kGreenByteIndex] = green value 0 to 255.
// rbga[ON_Color::kBlueByteIndex] = blue value 0 to 255.
// rbga[ON_Color::kAlphaByteIndex] = alpha value 0 to 255.
// ON_Color color = u;
enum RGBA_byte_index : unsigned int
{
// same for both little and big endian computers.
kRedByteIndex = 0,
kGreenByteIndex = 1,
kBlueByteIndex = 2,
kAlphaByteIndex = 3
};
/*
Returns:
A random color.
*/
static const ON_Color RandomColor();
/*
Parameters:
seed - [in]
hue_range - [in]
range of hues. Use ON_Interval::ZeroToTwoPi for all hues.
saturation_range - [in]
range of saturations. Use ON_Interval::ZeroToOne for all saturations.
value_range - [in]
range of values. Use ON_Interval::ZeroToOne for all values.
Returns:
A color generated from seed. The color for a given seed will always be the same.
*/
static const ON_Color RandomColor(
ON_Interval hue_range,
ON_Interval saturation_range,
ON_Interval value_range
);
/*
Returns:
A color generated from seed. The color for a given seed will always be the same.
*/
static const ON_Color RandomColor(
ON__UINT32 seed
);
/*
Parameters:
seed - [in]
hue_range - [in]
range of hues. Use ON_Interval::ZeroToTwoPi for all hues.
saturation_range - [in]
range of saturations. Use ON_Interval::ZeroToOne for all saturations.
value_range - [in]
range of values. Use ON_Interval::ZeroToOne for all values.
Returns:
A color generated from seed. The color for a given seed will always be the same.
*/
static const ON_Color RandomColor(
ON__UINT32 seed,
ON_Interval hue_range,
ON_Interval saturation_range,
ON_Interval value_range
);
// If you need to use shifting to convert RGBA components to and from
// an unsigned int ON_COlor value and you want your code to work
// on both little and big endian computers, use the RGBA_shift enum.
//
// unsigned int u = 0;
// u |= ((((unsigned int)red) & 0xFFU) << ON_Color::RGBA_shift::kRedShift);
// u |= ((((unsigned int)green) & 0xFFU) << ON_Color::RGBA_shift::kGreenShift);
// u |= ((((unsigned int)blue) & 0xFFU) << ON_Color::RGBA_shift::kBlueShift);
// u |= ((((unsigned int)alpha) & 0xFFU) << ON_Color::RGBA_shift::kAlphaShift);
// ON_Color color = u;
enum RGBA_shift : unsigned int
{
#if defined(ON_LITTLE_ENDIAN)
kRedShift = 0,
kGreenShift = 8,
kBlueShift = 16,
kAlphaShift = 24
#elif defined(ON_BIG_ENDIAN)
kRedShift = 24,
kGreenShift = 16,
kBlueShift = 8,
kAlphaShift = 0
#else
#error unknown endian
#endif
};
// Sets A = 0
ON_Color(
int red, // ( 0 to 255 )
int green, // ( 0 to 255 )
int blue // ( 0 to 255 )
);
ON_Color(
int red, // ( 0 to 255 )
int green, // ( 0 to 255 )
int blue, // ( 0 to 255 )
int alpha // ( 0 to 255 ) (0 = opaque, 255 = transparent)
);
/*
Parameters:
colorref - [in]
Windows COLORREF in little endian RGBA order.
*/
ON_Color(
unsigned int colorref
);
// Conversion to Windows COLORREF in little endian RGBA order.
operator unsigned int() const;
/*
Description:
Call this function when the color is needed in a
Windows COLORREF format with alpha = 0;
Returns
A Windows COLOREF with alpha = 0.
*/
unsigned int WindowsRGB() const;
// < 0 if this < arg, 0 ir this==arg, > 0 if this > arg
int Compare( const ON_Color& ) const;
int Red() const; // ( 0 to 255 )
int Green() const; // ( 0 to 255 )
int Blue() const; // ( 0 to 255 )
int Alpha() const; // ( 0 to 255 ) (0 = opaque, 255 = transparent)
double FractionRed() const; // ( 0.0 to 1.0 )
double FractionGreen() const; // ( 0.0 to 1.0 )
double FractionBlue() const; // ( 0.0 to 1.0 )
double FractionAlpha() const; // ( 0.0 to 1.0 ) (0.0 = opaque, 1.0 = transparent)
void SetRGB(
int red, // red in range 0 to 255
int green, // green in range 0 to 255
int blue // blue in range 0 to 255
);
void SetFractionalRGB(
double red, // red in range 0.0 to 1.0
double green, // green in range 0.0 to 1.0
double blue // blue in range 0.0 to 1.0
);
void SetAlpha(
int alpha // alpha in range 0 to 255 (0 = opaque, 255 = transparent)
);
void SetFractionalAlpha(
double alpha // alpha in range 0.0 to 1.0 (0.0 = opaque, 1.0 = transparent)
);
void SetRGBA(
int red, // red in range 0 to 255
int green, // green in range 0 to 255
int blue, // blue in range 0 to 255
int alpha // alpha in range 0 to 255 (0 = opaque, 255 = transparent)
);
// input args
void SetFractionalRGBA(
double red, // red in range 0.0 to 1.0
double green, // green in range 0.0 to 1.0
double blue, // blue in range 0.0 to 1.0
double alpha // alpha in range 0.0 to 1.0 (0.0 = opaque, 1.0 = transparent)
);
// Hue() returns an angle in the range 0 to 2*pi
//
// 0 = red, pi/3 = yellow, 2*pi/3 = green,
// pi = cyan, 4*pi/3 = blue,5*pi/3 = magenta,
// 2*pi = red
double Hue() const;
// Returns 0.0 (gray) to 1.0 (saturated)
double Saturation() const;
// Returns 0.0 (black) to 1.0 (white)
double Value() const;
void SetHSV(
double h, // hue in radians 0 to 2*pi
double s, // satuation 0.0 = gray, 1.0 = saturated
double v // value
);
///<summary>
/// Formats used by ON_Color::ToText() and ON_Color::ToString().
///</summary>
enum class TextFormat: unsigned char
{
///<summary>
/// Indicates no format has been selected. Empty text is created.
///</summary>
Unset = 0,
///<summary>
/// red,green,blue as floating point values from 0.0 to 1.0.
///</summary>
FractionalRGB = 1,
///<summary>
/// red,green,blue as floating point values from 0.0 to 1.0. alpha is appended if it is not zero.
///</summary>
FractionalRGBa = 2,
///<summary>
/// red,green,blue,alpha as floating point values from 0.0 to 1.0.
///</summary>
FractionalRGBA = 3,
///<summary>
/// red,green,blue as decimal integers from 0 to 255.
///</summary>
DecimalRGB = 4,
///<summary>
/// red,green,blue as decimal integers from 0 to 255. alpha is appended if it is not zero.
///</summary>
DecimalRGBa = 5,
///<summary>
/// red,green,blue,alpha as decimal integers from 0 to 255.
///</summary>
DecimalRGBA = 6,
///<summary>
/// red,green,blue as hexadecimal integers from 0 to 255.
///</summary>
HexadecimalRGB = 7,
///<summary>
/// red,green,blue as hexadecimal integers from 0 to 255. alpha is appended if it is not zero.
///</summary>
HexadecimalRGBa = 8,
///<summary>
/// red,green,blue,alpha as hexadecimal integers from 0 to 255.
///</summary>
HexadecimalRGBA = 9,
///<summary>
/// hue (0 to 2pi), saturation (0 to 1), value (0 to 1) as floating point values.
///</summary>
HSV = 10,
///<summary>
/// hue (0 to 2pi), saturation (0 to 1), value (0 to 1) as floating point values. alpha (0 to 1) is appended if it is not zero.
///</summary>
HSVa = 11,
///<summary>
/// hue (0 to 2pi), saturation (0 to 1), value (0 to 1), alpha (0 to 1) as floating point values.
///</summary>
HSVA = 12,
};
/*
Parameters:
format - [in]
separator - [in]
character to sepearate numbers (unicode code point - UTF-16 surrogate pairs not supported)
pass 0 for default.
bFormatUnsetColor - [in]
If true, ON_Color::UnsetColor will return "UnsetColor". Otherwise ON_Color::UnsetColor will return the empty string.
text_log - [in]
destination of the text.
*/
const ON_wString ToString(
ON_Color::TextFormat format,
wchar_t separator,
bool bFormatUnsetColor,
class ON_TextLog& text_log
) const;
/*
Parameters:
format - [in]
If format is ON_Color::TextFormat::Unset, then text_log.ColorFormat is used.
separator - [in]
character to sepearate numbers (unicode code point - UTF-16 surrogate pairs not supported)
pass 0 for default.
bFormatUnsetColor - [in]
If true, ON_Color::UnsetColor will return "UnsetColor". Otherwise ON_Color::UnsetColor will return the empty string.
text_log - [in]
destination of the text.
*/
void ToText(
ON_Color::TextFormat format,
wchar_t separator,
bool bFormatUnsetColor,
class ON_TextLog& text_log
) const;
private:
union {
// On little endian (Intel) computers, m_color has the same byte order
// as Windows COLORREF values.
// On little endian computers, m_color = 0xaabbggrr as an unsigned int value.
// On big endian computers, m_color = 0xrrggbbaa as an unsigned int value
// rr = red component 0-255
// gg = grean component 0-255
// bb = blue component 0-255
// aa = alpha 0-255. 0 means opaque, 255 means transparent.
unsigned int m_color = 0;
// m_colorComponent is a 4 unsigned byte array in RGBA order
// red component = m_RGBA[ON_Color::RGBA_byte::kRed]
// grean component = m_RGBA[ON_Color::RGBA_byte::kGreen]
// blue component = m_RGBA[ON_Color::RGBA_byte::kBlue]
// alpha component = m_RGBA[ON_Color::RGBA_byte::kAlpha]
unsigned char m_RGBA[4];
};
};
///////////////////////////////////////////////////////////////////////////////
//
// Class ON_ColorStop
//
// Combination of a color and a single value. Typically used for defining
// gradient fills over a series of colors.
class ON_CLASS ON_ColorStop
{
public:
ON_ColorStop() = default;
ON_ColorStop(const ON_Color& color, double position);
bool Write(class ON_BinaryArchive& archive) const;
bool Read(class ON_BinaryArchive& archive);
ON_Color m_color = ON_Color::UnsetColor;
double m_position = 0;
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_ColorStop>;
#endif
class ON_CLASS ON_4fColor
{
public:
ON_4fColor();
~ON_4fColor() = default;
ON_4fColor(const ON_4fColor&) = default;
ON_4fColor& operator=(const ON_4fColor&) = default;
static const ON_4fColor Unset;
//Note that these function will set the alpha correctly from ON_Colors "inverted" alpha.
ON_4fColor(const ON_Color&);
ON_4fColor& operator=(const ON_Color&);
//Will invert the opacity alpha to transparency.
operator ON_Color(void) const;
float Red(void) const;
void SetRed(float);
float Green(void) const;
void SetGreen(float);
float Blue(void) const;
void SetBlue(float);
//Alpha in ON_4fColor is OPACITY - not transparency as in ON_Color.
float Alpha(void) const;
void SetAlpha(float);
void SetRGBA(float r, float g, float b, float a);
bool IsValid(class ON_TextLog* text_log = nullptr) const;
// < 0 if this < arg, 0 ir this==arg, > 0 if this > arg
int Compare(const ON_4fColor&) const;
private:
float m_color[4];
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_4fColor>;
#endif
#endif
+493
View File
@@ -0,0 +1,493 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_COMPRESS_INC_)
#define OPENNURBS_COMPRESS_INC_
typedef bool (*ON_StreamCallbackFunction)( void* context, ON__UINT32 size, const void* buffer );
class ON_CLASS ON_CompressStream
{
public:
ON_CompressStream();
virtual ~ON_CompressStream();
/*
Description:
ON_CompressStream delivers the compressed stream by calling
a compressed stream output handler function. There are two
options for specifying the compressed stream output handler
function.
1. Overriding the virtual Out() function.
2. Providing a callback function.
SetCallback() is used to specify a callback function to handle
the compressed stream and to specify a context pointer to be
passed to either option of the handler.
Parameters:
callback_function - [in]
Function to call with sections of the compressed stream.
If callback_function is null, then the virtual Out()
function will be called. When callback_function
is specified, it must return true if the compression
calculation should continue and false to cancel the
compression calculation.
callback_context - [in]
This value is passed as the first argument when calling
callback_function or the virutal Out() function.
Returns:
True if successful.
Remarks:
Once compression has started, it would be unusual to
intentionally change the compressed stream output handler,
but you can do this if you need to.
*/
bool SetCallback(
ON_StreamCallbackFunction callback_function,
void* callback_context
);
/*
Returns:
Current value of the callback function for handling
the compressed stream. If the callback function is
null, the the virtual Out() function is used to
handle
*/
ON_StreamCallbackFunction CallbackFunction() const;
/*
Returns:
Current value of the context pointer passed as the first
argument to the compressed stream output handler function.
*/
void* CallbackContext() const;
/*
Description:
Call Begin() one time to initialize the compression
calculation. Then call In() one or more times
to submit the uncompressed stream to the compression calculation.
When you reach the end of the uncompressed stream, call
End().
Returns:
true if successful, false if an error occured.
*/
bool Begin();
/*
Description:
Call In() one or more times to compress a stream of uncompressed
bytes. After the last call to In(), call End(). Calling In()
may generate zero or more calls to the output stream handler.
Parameters:
in_buffer_size - [in]
number of bytes in in_buffer
in_buffer - [in]
Returns:
true if successful, false if an error occured.
*/
bool In(
ON__UINT64 in_buffer_size,
const void* in_buffer
);
/*
Description:
If an explicit compressed stream output handler is not specified
( CallbackFunction() returns null ), then the virtual Out()
function is called to handle the compressed output stream.
As the input stream is compressed, one or more calls to Out()
will occur.
Returns:
True to continue compressing and false to cancel the compression
calculation.
Remarks:
In general, it is probably going to be easier to test and debug
your code if you ignore the callback_context parameter and add
a member variable to your derived class to make additional
information accessable to your Out function.
*/
virtual bool Out(
void* callback_context,
ON__UINT32 out_buffer_size,
const void* out_buffer
);
/*
Description:
After the last call to In(), call End().
Calling End() may generate zero or more
calls to the output stream handler.
Returns:
true if successful, false if an error occured.
*/
bool End();
/*
Returns:
Then the returned value is the total number bytes in the input
stream. The size is updated every time In() is called before
any calls are made to the output stream handler. If the
calculation is finished ( End() has been called ), then the
returned value is the total number of bytes in the entire
input stream.
*/
ON__UINT64 InSize() const;
/*
Returns:
Then the returned value is the total number bytes in the output
stream. The size is incremented immediately after each call to
the output stream handler. If the compression calculation is
finished ( End() has been called ), then the returned value is
the total number of bytes in the entire output stream.
*/
ON__UINT64 OutSize() const;
/*
Returns:
Then the returned value is the 32-bit crc of the input stream.
The crc is updated every time In() is called before any calls
are made to the output stream handler. If the compression
calculation is finished ( End() has been called ), then the
returned value is the 32-bit crc of the entire input stream.
*/
ON__UINT32 InCRC() const;
/*
Returns:
Then the returned value is the 32bit crc of the output stream.
The crc is updated immediately after each call to the output
stream handler. If the calculation is finished ( End() has
been called ), then the returned value is the 32-bit crc of
the entire output stream.
*/
ON__UINT32 OutCRC() const;
private:
ON_StreamCallbackFunction m_out_callback_function;
void* m_out_callback_context;
ON__UINT64 m_in_size;
ON__UINT64 m_out_size;
ON__UINT32 m_in_crc;
ON__UINT32 m_out_crc;
void* m_implementation;
void* m_reserved;
void ErrorHandler();
private:
// prohibit use - no implementation
ON_CompressStream(const ON_CompressStream&);
ON_CompressStream& operator=(const ON_CompressStream&);
};
class ON_CLASS ON_UncompressStream
{
public:
ON_UncompressStream();
virtual ~ON_UncompressStream();
/*
Description:
ON_UncompressStream delivers the uncompressed stream by calling
an uncompressed stream output handler function. There are two
options for specifying the uncompressed stream output handler
function.
1. Overriding the virtual Out() function.
2. Providing a callback function.
SetCallback() is used to specify a callback function to handle
the uncompressed stream and to specify a context pointer to be
passed to either option of the handler.
Parameters:
callback_function - [in]
Function to call with sections of the uncompressed stream.
If callback_function is null, then the virtual Out()
function will be called. When callback_function
is specified, it must return true if the uncompression
calculation should continue and false to cancel the
uncompression calculation.
callback_context - [in]
This value is passed as the first argument when calling
callback_function or the virutal Out() function.
Returns:
True if successful.
Remarks:
Once uncompression has started, it would be unusual to
intentionally change the uncompressed stream output handler,
but you can do this if you need to.
*/
bool SetCallback(
ON_StreamCallbackFunction callback_function,
void* callback_context
);
/*
Returns:
Current value of the callback function for handling
the uncompressed stream. If the callback function is
null, the the virtual UncompressedStreamOut() function
is used.
*/
ON_StreamCallbackFunction CallbackFunction() const;
/*
Returns:
Current value of the context pointer passed as the first
argument to the uncompressed stream output handler function.
*/
void* CallbackContext() const;
/*
Description:
Call BeginUnompressStream() one time to initialize the compression
calculation. Then call In() one or more times
to submit the compressed stream to the uncompression calculation.
When you reach the end of the compressed stream, call
End().
Returns:
true if successful, false if an error occured.
*/
bool Begin();
/*
Description:
Call In() one or more times to uncompress a stream of compressed
bytes. After the last call to In(), call End(). Calling End()
may generate zero or more calls to the output stream handler.
Parameters:
in_buffer_size - [in]
number of bytes in in_buffer
in_buffer - [in]
Returns:
true if successful, false if an error occured.
*/
bool In(
ON__UINT64 in_buffer_size,
const void* in_buffer
);
/*
Description:
If an explicit uncompressed stream handler is not specified
( CallbackFunction() returns null ), then the virtual Out()
function is called to handle the uncompressed output stream.
As the input stream is uncompressed, one or more calls to Out()
will occur.
Returns:
True to continue uncompressing and false to cancel the
uncompression calculation.
Remarks:
In general, it is probably going to be easier to test and debug
your code if you ignore the callback_context parameter and add
a member variable to your derived class to make additional
information accessable to your Out function.
*/
virtual bool Out(
void* callback_context,
ON__UINT32 out_buffer_size,
const void* out_buffer
);
/*
Description:
After the last call to In(), call End().
Calling End() may generate zero or more
calls to the output stream handler.
Returns:
true if successful, false if an error occured.
*/
bool End();
/*
Returns:
Then the returned value is the total number bytes in the input
stream. The size is updated every time In() is called before
any calls are made to the output stream handler. If the
calculation is finished ( End() has been called ), then the
returned value is the total number of bytes in the entire
input stream.
*/
ON__UINT64 InSize() const;
/*
Returns:
Then the returned value is the total number bytes in the output
stream. The size is incremented immediately after each call to
the output stream handler. If the compression calculation is
finished ( End() has been called ), then the returned value is
the total number of bytes in the entire output stream.
*/
ON__UINT64 OutSize() const;
/*
Returns:
Then the returned value is the 32-bit crc of the input stream.
The crc is updated every time In() is called before any calls
are made to the output stream handler. If the compression
calculation is finished ( End() has been called ), then the
returned value is the 32-bit crc of the entire input stream.
*/
ON__UINT32 InCRC() const;
/*
Returns:
Then the returned value is the 32bit crc of the output stream.
The crc is updated immediately after each call to the output
stream handler. If the calculation is finished ( End() has
been called ), then the returned value is the 32-bit crc of
the entire output stream.
*/
ON__UINT32 OutCRC() const;
private:
ON_StreamCallbackFunction m_out_callback_function;
void* m_out_callback_context;
ON__UINT64 m_in_size;
ON__UINT64 m_out_size;
ON__UINT32 m_in_crc;
ON__UINT32 m_out_crc;
void* m_implementation;
void* m_reserved;
void ErrorHandler();
private:
// prohibit use - no implementation
ON_UncompressStream(const ON_UncompressStream&);
ON_UncompressStream& operator=(const ON_UncompressStream&);
};
/*
Description:
Simple tool for uncompressing a buffer when the output
buffer size is known.
Parameters:
sizeof_compressed_buffer - [in]
byte count
compressed_buffer - [in]
sizeof_uncompressed_buffer
byte count
uncompressed_buffer - [out]
Returns:
Number of bytes written to uncompressed_buffer.
*/
ON_DECL
size_t ON_UncompressBuffer(
size_t sizeof_compressed_buffer,
const void* compressed_buffer,
size_t sizeof_uncompressed_buffer,
void* uncompressed_buffer
);
class ON_CLASS ON_CompressedBuffer
{
public:
ON_CompressedBuffer();
~ON_CompressedBuffer();
ON_CompressedBuffer(const ON_CompressedBuffer& src);
ON_CompressedBuffer& operator=(const ON_CompressedBuffer& src);
/*
Description:
Compress inbuffer.
Parameters:
sizeof__inbuffer - [in]
Number of bytes in inbuffer.
inbuffer - [in]
Uncompressed information.
sizeof_element - [out]
This parameter only matters if the buffer will be compressed,
and decompressed on CPUs with different endianness. If this
is the case, then the types in the buffer need to have the
same size (2,4, or 8).
Returns:
True if inbuffer is successfully compressed.
*/
bool Compress(
size_t sizeof__inbuffer, // sizeof uncompressed input data
const void* inbuffer, // uncompressed input data
int sizeof_element
);
/*
Returns:
Number of bytes in the uncompressed information.
*/
size_t SizeOfUncompressedBuffer() const;
/*
Description:
Uncompress the contents of this ON_CompressedBuffer.
Parameters:
outbuffer - [in/out]
This buffer must have at least SizeOfUncompressedBuffer() bytes.
If the function returns true, then the uncopressed information
is stored in this buffer.
bFailedCRC - [out]
If not null, then this boolean is set to true if the CRC
of the uncompressed information has changed.
Returns:
True if uncompressed information is returned in outbuffer.
*/
bool Uncompress( // read and uncompress
void* outbuffer, // uncompressed output data returned here
int* bFailedCRC
) const;
/*
Description:
Destroy the current informtion in the ON_CompressedBuffer
so the class can be reused.
*/
void Destroy();
bool Write(ON_BinaryArchive& binary_archive) const;
bool Read(ON_BinaryArchive& binary_archive);
/////////////////////////////////////////////////
//
// Implementation
//
bool CompressionInit(struct ON_CompressedBufferHelper*) const;
bool CompressionEnd(struct ON_CompressedBufferHelper*) const;
size_t DeflateHelper( // returns number of bytes written
struct ON_CompressedBufferHelper*,
size_t sizeof___inbuffer, // sizeof uncompressed input data ( > 0 )
const void* in___buffer // uncompressed input data ( != nullptr )
);
bool InflateHelper(
struct ON_CompressedBufferHelper*,
size_t sizeof___outbuffer, // sizeof uncompressed data
void* out___buffer // buffer for uncompressed data
) const;
bool WriteChar(
size_t count,
const void* buffer
);
size_t m_sizeof_uncompressed;
size_t m_sizeof_compressed;
ON__UINT32 m_crc_uncompressed;
ON__UINT32 m_crc_compressed;
int m_method; // 0 = copied, 1 = compressed
int m_sizeof_element;
size_t m_buffer_compressed_capacity;
void* m_buffer_compressed;
};
#endif
+884
View File
@@ -0,0 +1,884 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2014 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_COMPSTAT_INC_)
#define OPENNURBS_COMPSTAT_INC_
//////////////////////////////////////////////////////////////////////////
//
// ON_ComponentState and ON_ComponentStatus
//
#pragma region RH_C_SHARED_ENUM [ON_ComponentState] [Rhino.Geometry.ComponentState] [internal:byte]
///<summary><para>Provides a set of values describing component state.</para>
///<para>This is not a bit field.</para>
///<para>Some of these values are mutually exclusive and should not be combined.</para></summary>
enum class ON_ComponentState : unsigned char
{
///<summary>Not a valid status.</summary>
Unset = 0,
///<summary>This is a default component state.</summary>
Clear = 1,
///<summary>This is a default component state, but not selected.</summary>
NotSelected = 2,
///<summary>This component is selected.</summary>
Selected = 3,
///<summary>This component is selected persistently.</summary>
SelectedPersistent = 4,
///<summary>This is a default component state, but not highlighted.</summary>
NotHighlighted = 5,
///<summary>This component is highlighted.</summary>
Highlighted = 6,
///<summary>This is a default component state, but not hidden.</summary>
NotHidden = 7,
///<summary>This component is hidden.</summary>
Hidden = 8,
///<summary>This is a default component state, but not locked.</summary>
NotLocked = 9,
///<summary>This component is locked.</summary>
Locked = 10,
///<summary>This is a default component state, but not damaged.</summary>
NotDamaged = 11,
///<summary>This component is damaged.</summary>
Damaged = 12,
///<summary>This component is not deleted.</summary>
NotDeleted = 13,
///<summary>This component is deleted.</summary>
Deleted = 14,
///<summary>This runtime mark is clear.</summary>
RuntimeMarkClear = 15,
///<summary>This runtime mark is set.</summary>
RuntimeMarkSet = 16
};
#pragma endregion
ON_DECL
ON_ComponentState ON_ComponentStateFromUnsigned(
unsigned int state_as_unsigned
);
class ON_CLASS ON_ComponentStatus
{
public:
static const ON_ComponentStatus NoneSet;
static const ON_ComponentStatus Selected;
static const ON_ComponentStatus SelectedPersistent;
static const ON_ComponentStatus Highlighted;
static const ON_ComponentStatus Hidden;
static const ON_ComponentStatus Locked;
static const ON_ComponentStatus Deleted;
static const ON_ComponentStatus Damaged;
static const ON_ComponentStatus Marked;
/*
The six bits for SelectedPersistent, Highlighted, Hidden, Locked, and Damaged are set.
The two bits for Deleted and RuntimeMark are clear.
*/
static const ON_ComponentStatus AllSet;
/*
Returns:
A logical and of the status bit in lhs and rhs.
*/
static const ON_ComponentStatus LogicalAnd(ON_ComponentStatus lhs, ON_ComponentStatus rhs);
/*
Returns:
A logical and of the status bit in lhs and rhs.
*/
static const ON_ComponentStatus LogicalOr(ON_ComponentStatus lhs, ON_ComponentStatus rhs);
/*
Description:
A tool for adding a status check filter. This tool pays attention to RuntimeMark().
Paramters:
candidate - [in]
pass_bits - [in]
fail_bits - [in]
Returns:
Checking is perfomed in the folloing order and every bit, include the RuntimeMark() bit, are tested.
First:
If ON_ComponentStatus::LogicalAnd(candidate,status_pass) has any set bits,
then true is returned.
Second:
If ON_ComponentStatus::LogicalAnd(candidate,status_fail) has any set bits,
then false is returned.
Third:
If status_fail has no set bits the true is returned.
Forth:
If status_pass has any set bits then false is returned.
Fifth:
True is returned.
Examples:
StatusCheck(candidate,ON_ComponentStatus::Selected,ON_ComponentStatus::NoneSet) = candidate.>IsSelected().
StatusCheck(candidate,ON_ComponentStatus::NoneSet,ON_ComponentStatus::Selected) = !candidate.>IsSelected().
StatusCheck(candidate,ON_ComponentStatus::NoneSet,ON_ComponentStatus::NoneSet) = true;
StatusCheck(candidate,ON_ComponentStatus::AllSet,ON_ComponentStatus::NoneSet) = true;
StatusCheck(candidate,ON_ComponentStatus::NoneSet,ON_ComponentStatus::AllSet) = candidate.IsClear() && false==candidate.RuntimeMark();
*/
static bool StatusCheck(
ON_ComponentStatus candidate,
ON_ComponentStatus status_pass,
ON_ComponentStatus status_fail
);
ON_ComponentStatus() = default;
~ON_ComponentStatus() = default;
ON_ComponentStatus(const ON_ComponentStatus&) = default;
ON_ComponentStatus& operator=(const ON_ComponentStatus&) = default;
/*
Description:
Constructs a status with the specified state set.
*/
ON_ComponentStatus(
ON_ComponentState state
);
bool operator==(ON_ComponentStatus);
bool operator!=(ON_ComponentStatus);
/*
Returns:
True if every setting besides runtime mark is 0 or false.
Ignores the runtime mark state.
Remarks:
The runtime mark setting is ignored by IsClear().
*/
bool IsClear() const;
/*
Returns:
True if some setting besides runtime mark is 1 or true.
Ignores the runtime mark state.
Remarks:
The runtime mark setting is ignored by IsNotClear().
*/
bool IsNotClear() const;
/*
Description:
Sets *this = status_to_copy and returns 1 if a state setting changed.
Returns:
1 if status changed.
0 if status did not change.
Remarks:
The runtime mark setting cannot be changed using SetStatus().
*/
unsigned int SetStatus(
ON_ComponentStatus status_to_copy
);
/*
Description:
If a state is set in states_to_set, the same state is set in "this".
Parameters:
states_to_set - [in]
Returns:
1 if status changed.
0 if status did not change.
Remarks:
The runtime mark setting cannot be changed using SetStates().
*/
unsigned int SetStates(
ON_ComponentStatus states_to_set
);
/*
Description:
If a state is set in states_to_clear, the same state is cleared in "this".
Parameters:
states_to_clear - [in]
Returns:
1 if status changed.
0 if status did not change.
Remarks:
The runtime mark setting cannot be changed using ClearStates().
*/
unsigned int ClearStates(
ON_ComponentStatus states_to_clear
);
//////////////////////////////////////////////////////////////////////////
//
// RuntimeMark
//
bool RuntimeMark() const;
/*
Returns:
Input value of RuntimeMark();
*/
bool SetRuntimeMark(
bool bRuntimeMark
);
/*
Returns:
Input value of RuntimeMark();
*/
bool SetRuntimeMark();
/*
Returns:
Input value of RuntimeMark();
*/
bool ClearRuntimeMark();
ON__UINT8 MarkBits() const;
ON__UINT8 SetMarkBits(ON__UINT8 bits);
/*
Returns:
(0==mark_bits) ? RuntimeMark() : (mark_bits == MarkBits()
*/
bool IsMarked(
ON__UINT8 mark_bits
) const;
//////////////////////////////////////////////////////////////////////////
//
// Selection
//
/*
Returns:
ON_ComponentState::not_selected,
ON_ComponentState::Selected or
ON_ComponentState::Selected_pesistent.
*/
ON_ComponentState SelectedState() const;
/*
Returns:
1 if status changed.
0 if status did not change.
*/
unsigned int SetSelectedState(
bool bSelectedState,
bool bPersistent,
bool bSynchronizeHighlight
);
unsigned int SetSelectedState(
ON_ComponentState selected_state,
bool bSynchronizeHighlight
);
/*
Returns:
false
The selection state is ON_ComponentState::not_selected.
true
The selection state is ON_ComponentState::Selected
or ON_ComponentState::Selected_pesistent.
*/
bool IsSelected() const;
/*
Returns:
false
The selection state is ON_ComponentState::not_selected.
true
The selection state is ON_ComponentState::Selected_pesistent.
*/
bool IsSelectedPersistent() const;
//////////////////////////////////////////////////////////////////////////
//
// Highlighted
//
/*
Returns:
1 if status changed.
0 if status did not change.
*/
unsigned int SetHighlightedState(
bool bIsHighlighed
);
/*
Returns:
false if not highlighted.
true otherwise.
*/
bool IsHighlighted() const;
//////////////////////////////////////////////////////////////////////////
//
// Hidden
//
/*
Returns:
1 if status changed.
0 if status did not change.
*/
unsigned int SetHiddenState(
bool bIsHidden
);
/*
Returns:
false if not hidden.
true otherwise.
(ON_ComponentStatus::HIDDEN_STATE::not_hidden != HiddenState())
*/
bool IsHidden() const;
//////////////////////////////////////////////////////////////////////////
//
// Locked
//
/*
Returns:
1 if status changed.
0 if status did not change.
*/
unsigned int SetLockedState(
bool bIsLocked
);
/*
Returns:
false if not locked.
true otherwise.
(ON_ComponentStatus::LOCKED_STATE::not_locked != LockedState())
*/
bool IsLocked() const;
//////////////////////////////////////////////////////////////////////////
//
// Deleted
//
/*
Returns:
1 if status changed.
0 if status did not change.
*/
unsigned int SetDeletedState(
bool bIsDeleted
);
/*
Returns:
false if not hidden.
true otherwise.
(ON_ComponentStatus::DELETED_STATE::not_deleted != DeletedState())
*/
bool IsDeleted() const;
//////////////////////////////////////////////////////////////////////////
//
// Damaged
//
/*
Returns:
1 if status changed.
0 if status did not change.
*/
unsigned int SetDamagedState(
bool bIsDamaged
);
/*
Returns:
false if not damaged.
true otherwise.
(ON_ComponentStatus::DAMAGED_STATE::not_damaged != DamagedState())
*/
bool IsDamaged() const;
//////////////////////////////////////////////////////////////////////////
//
// Checking multiple state values efficently
//
bool operator==(const ON_ComponentStatus&) const;
bool operator!=(const ON_ComponentStatus&) const;
/*
Parameters:
states_filter - [in]
If no states are specified, then false is returned.
comparand - [in]
If a state is set in states_filter, the corresponding state
in "this" and comparand will be tested.
Returns:
True if every tested state in "this" and comparand are identical.
Remarks:
For the purposes of this test, ON_ComponentState::Selected
and ON_ComponentState::SelectedPersistent are considered equal.
*/
bool AllEqualStates(
ON_ComponentStatus states_filter,
ON_ComponentStatus comparand
) const;
/*
Parameters:
states_filter - [in]
If no states are specified, then false is returned.
comparand - [in]
If a state is set in states_filter, the corresponding state
in "this" and comparand will be tested.
Returns:
True if at least one tested state in "this" and comparand are identical.
Remarks:
For the purposes of this test, ON_ComponentState::Selected
and ON_ComponentState::SelectedPersistent are considered equal.
*/
bool SomeEqualStates(
ON_ComponentStatus states_filter,
ON_ComponentStatus comparand
) const;
/*
Parameters:
states_filter - [in]
If no states are specified, then false is returned.
comparand - [in]
If a state is set in states_filter, the corresponding state
in "this" and comparand will be tested.
Returns:
True if every tested state in "this" and comparand are different.
Remarks:
For the purposes of this test, ON_ComponentState::Selected
and ON_ComponentState::SelectedPersistent are considered equal.
*/
bool NoEqualStates(
ON_ComponentStatus states_filter,
ON_ComponentStatus comparand
) const;
private:
friend class ON_AggregateComponentStatus;
// NOTE:
// Hidden, Selected, ..., Mark() bool values are saved
// as single bits on m_status_flags.
unsigned char m_status_flags = 0U;
// extra bits for advanced marking
// no rules for use and runtime only - never saved in 3dm archives
// NOTE: Mark() and MarkBits() are independent.
// bool Mark() is a bit on m_status_flags.
// ON__UINT8 MarkBits() returns m_mark_bits.
ON__UINT8 m_mark_bits = 0U;
};
//////////////////////////////////////////////////////////////////////////
//
// ON_AggregateComponentStatus
//
//
/*
ON_AggregateComponentStatus is obsolte.
It exists because the virtual interface on ON_Object and the member on ON_Brep
cannot be changed without breakky the pubic C++ SDK.
Whenever possible, use ON_AggregateComponentStatusEx.
*/
class ON_CLASS ON_AggregateComponentStatus
{
public:
static const ON_AggregateComponentStatus Empty;
static const ON_AggregateComponentStatus NotCurrent;
ON_AggregateComponentStatus() = default;
~ON_AggregateComponentStatus() = default;
ON_AggregateComponentStatus(const ON_AggregateComponentStatus&) = default;
ON_AggregateComponentStatus& operator=(const ON_AggregateComponentStatus&) = default;
ON_AggregateComponentStatus(const class ON_AggregateComponentStatusEx&);
ON_AggregateComponentStatus& operator=(const class ON_AggregateComponentStatusEx&);
/*
Description:
Sets all states to clear.
Marks status as current.
Does not change compoent count
Returns
true if successful.
false if information is not current and ClearAllStates() failed.
*/
bool ClearAllStates();
/*
Description:
Sets all states specified by states_to_clear to clear.
Does not change current mark.
Does not change compoent count.
Returns
true if successful.
false if information is not current and ClearAggregateStatus() failed.
*/
bool ClearAggregateStatus(
ON_ComponentStatus states_to_clear
);
/*
Description:
Add the status information in component_status to this aggregate status.
Parameters:
component_status - [in]
Returns:
true if successful.
false if information is not current and Add failed.
*/
bool Add(
ON_ComponentStatus component_status
);
/*
Description:
Add the status information in aggregate_status to this aggregate status.
Parameters:
aggregate_status - [in]
Returns:
true if successful.
false if information is not current and Add failed.
*/
bool Add(
const ON_AggregateComponentStatus& aggregate_status
);
/*
Returns:
true if this is empty
false if not empty.
*/
bool IsEmpty() const;
/*
Returns:
true if the information is current (valid, up to date, ...).
false if the information is not current.
Remarks:
If the information is not current, all counts are zero and states are clear.
*/
bool IsCurrent() const;
/*
Description:
Mark the information as not current.
Erases all information.
*/
void MarkAsNotCurrent();
ON_ComponentStatus AggregateStatus() const;
unsigned int ComponentCount() const;
/*
Returns:
Number of compoents that are selected or persistently selected.
*/
unsigned int SelectedCount() const;
/*
Returns:
Number of compoents that are persistently selected.
*/
unsigned int SelectedPersistentCount() const;
unsigned int HighlightedCount() const;
unsigned int HiddenCount() const;
unsigned int LockedCount() const;
unsigned int DamagedCount() const;
private:
// a bitwise or of all component status settings
ON_ComponentStatus m_aggregate_status = ON_ComponentStatus::NoneSet;
private:
unsigned char m_current = 0; // 0 = empty, 1 = current, 2 = dirty
private:
unsigned char m_reserved1 = 0;
private:
// number of components
unsigned int m_component_count = 0;
// number of selected components (includes persistent and non persistent)
unsigned int m_selected_count = 0;
// number of selected components
unsigned int m_selected_persistent_count = 0;
// number of highlighted components
unsigned int m_highlighted_count = 0;
// number of hidden components
unsigned int m_hidden_count = 0;
// number of locked components
unsigned int m_locked_count = 0;
// number of damaged components
unsigned int m_damaged_count = 0;
};
class ON_CLASS ON_AggregateComponentStatusEx : private ON_AggregateComponentStatus
{
public:
static const ON_AggregateComponentStatusEx Empty;
static const ON_AggregateComponentStatusEx NotCurrent;
ON_AggregateComponentStatusEx() = default;
~ON_AggregateComponentStatusEx() = default;
ON_AggregateComponentStatusEx(const ON_AggregateComponentStatusEx&) = default;
ON_AggregateComponentStatusEx& operator=(const ON_AggregateComponentStatusEx&) = default;
ON_AggregateComponentStatusEx(const ON_AggregateComponentStatus&);
ON_AggregateComponentStatusEx& operator=(const ON_AggregateComponentStatus&);
/*
Returns:
A runtime serial number that is incremented every time a component status setting
changes, even when the actual counts may be unknown.
If the returned value is 0, status information is unknown.
*/
ON__UINT64 ComponentStatusSerialNumber() const;
/*
Description:
Sets all states to clear.
Marks status as current.
Does not change compoent count
Returns
true if successful.
false if information is not current and ClearAllStates() failed.
*/
bool ClearAllStates();
/*
Description:
Sets all states specified by states_to_clear to clear.
Does not change current mark.
Does not change compoent count.
Returns
true if successful.
false if information is not current and ClearAggregateStatus() failed.
*/
bool ClearAggregateStatus(
ON_ComponentStatus states_to_clear
);
/*
Description:
Add the status information in component_status to this aggregate status.
Parameters:
component_status - [in]
Returns:
true if successful.
false if information is not current and Add failed.
*/
bool Add(
ON_ComponentStatus component_status
);
/*
Description:
Add the status information in aggregate_status to this aggregate status.
Parameters:
aggregate_status - [in]
Returns:
true if successful.
false if information is not current and Add failed.
*/
bool Add(
const ON_AggregateComponentStatus& aggregate_status
);
/*
Returns:
true if this is empty
false if not empty.
*/
bool IsEmpty() const;
/*
Returns:
true if the information is current (valid, up to date, ...).
false if the information is not current.
Remarks:
If the information is not current, all counts are zero and states are clear.
*/
bool IsCurrent() const;
/*
Description:
Mark the information as not current.
Erases all information.
*/
void MarkAsNotCurrent();
ON_ComponentStatus AggregateStatus() const;
unsigned int ComponentCount() const;
/*
Returns:
Number of compoents that are selected or persistently selected.
*/
unsigned int SelectedCount() const;
/*
Returns:
Number of compoents that are persistently selected.
*/
unsigned int SelectedPersistentCount() const;
unsigned int HighlightedCount() const;
unsigned int HiddenCount() const;
unsigned int LockedCount() const;
unsigned int DamagedCount() const;
private:
// Whenever component status changes, m_runtime_serial_number is changed by calling Internal_ChangeStatusSerialNumber().
void Internal_ChangeStatusSerialNumber();
ON__UINT64 m_component_status_serial_number = 0;
};
//////////////////////////////////////////////////////////////////////////
//
// ON_UniqueTester
//
class ON_CLASS ON_UniqueTester
{
public:
ON_UniqueTester() = default;
~ON_UniqueTester();
ON_UniqueTester(const ON_UniqueTester&);
ON_UniqueTester& operator=(const ON_UniqueTester&);
public:
/*
Description:
If p is not in the list, it is added.
Returns:
True if p is in the list.
*/
bool InList(ON__UINT_PTR x) const;
/*
Description:
If p is not in the list, it is added.
Returns:
True if p is not in the list and was added. False if p was already in the list.
*/
bool AddToList(ON__UINT_PTR x);
void ClearList();
unsigned int Count() const;
public:
/*
Description:
Add x to the list. The expert caller is certain that x is not already in the list.
For large lists, using this function when appropriate, can result in substantial
speed improvments.
Parameters:
x - [in]
A value that is known to not be in the list.
*/
void ExpertAddNewToList(ON__UINT_PTR x);
private:
class Block
{
public:
static Block* NewBlock();
static void DeleteBlock(Block*);
public:
enum : size_t {BlockCapacity=1000};
size_t m_count = 0;
ON__UINT_PTR* m_a = nullptr;
class Block* m_next = nullptr;
bool InBlock(size_t sorted_count,ON__UINT_PTR p) const;
void SortBlock();
private:
static int Compare(ON__UINT_PTR* lhs, ON__UINT_PTR* rhs);
Block() = default;
~Block() = delete;
Block(const Block&) = delete;
Block& operator=(const Block&) = delete;
};
size_t m_sorted_count = 0;
Block* m_block_list = nullptr;
private:
void Internal_CopyFrom(const ON_UniqueTester& src);
void Internal_Destroy();
void Internal_AddValue(ON__UINT_PTR x);
};
#endif
+190
View File
@@ -0,0 +1,190 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(ON_CONE_INC_)
#define ON_CONE_INC_
class ON_NurbsSurface;
class ON_Brep;
// Description:
// Lightweight right circular cone. Use ON_ConeSurface if
// you need ON_Cone geometry as a virtual ON_Surface.
class ON_CLASS ON_Cone
{
public:
// Creates a cone with world XY plane as the base plane,
// center = (0,0,0), radius = 0.0, height = 0.0.
ON_Cone();
// See ON_Cone::Create.
ON_Cone(
const ON_Plane& plane,
double height,
double radius
);
~ON_Cone();
// Description:
// Creates a right circular cone from a plane, height,
// and radius.
// plane - [in] The apex of cone is at plane.origin and
// the axis of the cone is plane.zaxis.
// height - [in] The center of the base is height*plane.zaxis.
// radius - [in] tan(cone angle) = radius/height
bool Create(
const ON_Plane& plane,
double height,
double radius
);
// Returns true if plane is valid, height is not zero, and
// radius is not zero.
bool IsValid() const;
// Returns:
// Center of base circle.
// Remarks:
// The base point is plane.origin + height*plane.zaxis.
ON_3dPoint BasePoint() const;
// Returns:
// Point at the tip of the cone.
// Remarks:
// The apex point is plane.origin.
const ON_3dPoint& ApexPoint() const;
// Returns:
// Unit vector axis of cone.
const ON_3dVector& Axis() const;
// Returns:
// The angle (in radians) between the axis and the
// side of the cone.
// The angle and the height have the same sign.
double AngleInRadians() const;
// Returns:
// The angle Iin degrees) between the axis and the side.
// The angle and the height have the same sign.
double AngleInDegrees() const;
// evaluate parameters and return point
// Parameters:
// radial_parameter - [in] 0.0 to 2.0*ON_PI
// height_parameter - [in] 0 = apex, height = base
ON_3dPoint PointAt(
double radial_parameter,
double height_parameter
) const;
// Parameters:
// radial_parameter - [in] (in radians) 0.0 to 2.0*ON_PI
// height_parameter - [in] 0 = apex, height = base
// Remarks:
// If radius>0 and height>0, then the normal points "out"
// when height_parameter >= 0.
ON_3dVector NormalAt(
double radial_parameter,
double height_parameter
) const;
// Description:
// Get iso curve circle at a specified height.
// Parameters:
// height_parameter - [in] 0 = apex, height = base
ON_Circle CircleAt(
double height_parameter
) const;
// Description:
// Get iso curve line segment at a specified angle.
// Parameters:
// radial_parameter - [in] (in radians) 0.0 to 2.0*ON_PI
ON_Line LineAt(
double radial_parameter
) const;
// returns parameters of point on cone that is closest to given point
bool ClosestPointTo(
ON_3dPoint point,
double* radial_parameter,
double* height_parameter
) const;
// returns point on cone that is closest to given point
ON_3dPoint ClosestPointTo(
ON_3dPoint
) const;
bool Transform( const ON_Xform& );
// rotate cone about its origin
bool Rotate(
double sin_angle,
double cos_angle,
const ON_3dVector& axis_of_rotation
);
bool Rotate(
double angle_in_radians,
const ON_3dVector& axis_of_rotation
);
// rotate cone about a point and axis
bool Rotate(
double sin_angle,
double cos_angle,
const ON_3dVector& axis_of_rotation,
const ON_3dPoint& center_of_rotation
);
bool Rotate(
double angle_in_radians,
const ON_3dVector& axis_of_rotation,
const ON_3dPoint& center_of_rotation
);
bool Translate(
const ON_3dVector& delta
);
/*
returns:
0 = failure
2 = success
*/
int GetNurbForm( ON_NurbsSurface& ) const;
/*
Description:
Creates a surface of revolution definition of the cylinder.
Parameters:
srf - [in] if not nullptr, then this srf is used.
Result:
A surface of revolution or nullptr if the cylinder is not
valid or is infinite.
*/
ON_RevSurface* RevSurfaceForm( ON_RevSurface* srf = nullptr ) const;
public:
ON_Plane plane; // apex = plane.origin, axis = plane.zaxis
double height; // not zero
double radius; // not zero
};
#endif
+427
View File
@@ -0,0 +1,427 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(ON_CONVEX_POLY_INC_)
#define ON_CONVEX_POLY_INC_
// A Simplex in 3d
class ON_CLASS ON_3dSimplex
{
public:
ON_3dSimplex(); // An empty simplex
explicit ON_3dSimplex(const ON_3dPoint& a); // 0-simplex in 3d
ON_3dSimplex(const ON_3dPoint& a, const ON_3dPoint& b); // 1-simplex
ON_3dSimplex(const ON_3dPoint& a, const ON_3dPoint& b, const ON_3dPoint& c); // 2-simplex
ON_3dSimplex(const ON_3dPoint& a, const ON_3dPoint& b, const ON_3dPoint& c, const ON_3dPoint& d); // 3-simplex
ON_3dSimplex(const ON_3dSimplex& rhs) = default;
ON_3dSimplex& operator=(const ON_3dSimplex& rhs) = default;
~ON_3dSimplex() = default;
int Count() const; // Number of Verticies <=4
bool IsValid(double eps) const; // true if the Verticies are affinely independent
/*
Description:
Evaluate a point in a Simplex from a barycentric coordinate b.
Returns:
The point
b[0] * Vertex[0] + ... + b[Count()-1] * Vertex[Count()-1]
Notes:
If b[0] + ... + b[Count()-1] = 1 and b[i]>=0 for i=0 to Count()-1 then the
returned point is on the simplex
*/
ON_3dPoint Evaluate(const double* b) const;
ON_3dPoint Evaluate(const ON_4dPoint& b) const;
/*
Description:
Find Closest Point to this simplex from a base point P0 or the Origin.
If true is retuned then Evaluate(Bary) is the closest point on the Simplex.
maximum_distance - optional upperbound on closest point. If maximum_distance>=0 is specified and
Dist(P0, Simplex)>maximum_distance then false is returned.
*/
bool GetClosestPoint(const ON_3dPoint& P0, ON_4dPoint& Bary, double maximum_distance = ON_DBL_MAX) const;
bool GetClosestPointToOrigin(ON_4dPoint& Bary) const;
/*
Count() Volume() returns
0 0.0
1 0.0
2 length >=0
3 area >=0
4 volume >=0
*/
double Volume() const;
double SignedVolume() const; // returns ON_UNSET_VALUE if Count()<4 else the signed volume
/*
FaceNormal(noti) is the oriented face normal obtained by omitting vertex noti.
FaceNormal returns ON_UNSET_VALUE if Count()<3 or Count()==4 noti not 0,1,2 or 3.
FaceUnitNormal returns ON_UNSET_VALUE if Count()<3 or Count()==4 noti not 0,1,2 or 3 or if FaceNormal(noti)=Zero_Vector
*/
ON_3dVector FaceNormal(int noti = 0) const;
ON_3dVector FaceUnitNormal(int noti = 0) const;
/*
Edge vector from Vertex(e0) to Vertex(e1)
*/
ON_3dVector Edge(int e0, int e1)const;
/* If 0<=i<Count() modify this simplex by removing Vertex[i], specifically,
Vertex[k] is fixed for k<i , and
Vertex[k] <- Vertex[k+1] for i<= k= Count()-2
*/
bool RemoveVertex(int i);
/* append new vertex at end*/
bool AddVertex(const ON_3dPoint&);
/* Modify a vertex. i<Count() */
bool SetVertex(int i, ON_3dPoint P);
// Returns a Vertex or a reference to one when 0<=i<Count()
ON_3dPoint& operator[](int);
const ON_3dPoint& operator[](int i) const;
ON_3dPoint Vertex(int i) const;
ON_3dPoint& Vertex(int i);
/* Maximum absolute value of vertex coordinates*/
double MaximumCoordinate() const;
/*
Description:
Get Simplex's 3d axis aligned bounding box.
Returns:
3d bounding box.
*/
ON_BoundingBox BoundingBox() const;
/*
Description:
Get simplexes 3d axis aligned bounding box or the
union of the input box with the object's bounding box.
Parameters:
bbox - [in/out] 3d axis aligned bounding box
bGrowBox - [in] (default=false)
If true, then the union of the input bbox and the
object's bounding box is returned in bbox.
If false, the object's bounding box is returned in bbox.
Returns:
true if object has bounding box and calculation was successful.
*/
bool GetBoundingBox(
ON_BoundingBox& bbox,
int bGrowBox = false
) const;
/*
Description:
Get tight bounding box with respect to a given frame
Parameters:
tight_bbox - [in/out] tight bounding box
bGrowBox -[in] (default=false)
If true and the input tight_bbox is valid, then returned
tight_bbox is the union of the input tight_bbox and the
line's tight bounding box.
xform -[in] (default=nullptr)
If not nullptr, the tight bounding box of the transformed
triangle is calculated. The triangle is not modified.
Returns:
True if a valid tight_bbox is returned.
*/
bool GetTightBoundingBox(
ON_BoundingBox& tight_bbox,
bool bGrowBox = false,
const ON_Xform* xform = nullptr
) const;
bool Transform(
const ON_Xform& xform
);
// rotate line about a point and axis
bool Rotate(
double sin_angle,
double cos_angle,
const ON_3dVector& axis_of_rotation,
const ON_3dPoint& center_of_rotation
);
bool Rotate(
double angle_in_radians,
const ON_3dVector& axis_of_rotation,
const ON_3dPoint& center_of_rotation
);
bool Translate(
const ON_3dVector& delta
);
private:
int m_n; // Number of points stored in m_V. 0<= m_n <= 4
ON_3dVector m_V[4];
bool Closest3plex(ON_4dPoint& Bary) const;
bool Closest2plex(ON_4dPoint& Bary) const;
bool Closest1plex(ON_4dPoint& Bary) const;
static bool RoundBarycentricCoordinate(ON_4dPoint& Bary);
};
/*
This is a base class for a convex polytope in 3d space, i.e. the convex hull of a
finite set of points called verticies.
This is the base type in the implementation of the GJK algorithm
ClosestPoint(ON_ConvexPoly& A, ON_ConvexPoly& B, ...)
*/
class ON_CLASS ON_ConvexPoly
{
public:
/*
Returns: Number of verticies >=0
*/
virtual int Count() const = 0;
/*
Returns: Vertex[i] for i=0,...,Count()-1
*/
virtual ON_3dVector Vertex(int i) const = 0;
/*
Description:
Let K be this ON_ConvexPoly then for a non-zero vector W the support Support(W) are point in K defined by
arg max x * W
x \in K
This method returns one of these points in Support(W).
i0 is an optional initial index seed value. It may provide a performance enhancement toward finding
a minimizer.
*/
ON_3dPoint Support(ON_3dVector W, int i0 =0) const
{
return Vertex(SupportIndex(W, i0));
}
/*
Description:
For any vector W there is a vetex that is Support(W)
SupportIndex( W, i0) returns a vertex index for a vertex that is the support.
Veretx( K.SupportIndex( W )) = K.Support(W );
*/
virtual int SupportIndex(ON_3dVector W, int i0=0) const = 0;
/*
Description:
Points in a Convex Polytope are parameterized , not necessaily uniquely,
by an ON_4dex of vertex indicies and a 4d barycentric point B
Evaluate(Ind, B ) = Sum_{i=0,..,3} Vertex(Ind[i])*B[i], where the sum is taken over i such that Ind[i]>=0
If B is a barycentric coordinte
B[i]>=0 and B[0] + B[1] + B[2] + B[3] = 1.0
then Evaluate( Ind, B) is a point in the convex polytope
*/
ON_3dPoint Evaluate(ON_4dex dex, ON_4dPoint B)const
{
ON_3dVector v(0, 0, 0);
if (dex.i >= 0)
v = B[0] * Vertex(dex.i);
if (dex.j >= 0)
v += B[1] * Vertex(dex.j);
if (dex.k >= 0)
v += B[2] * Vertex(dex.k);
if (dex.l >= 0)
v += B[3] * Vertex(dex.l);
return v;
};
/*
Description:
Computes the closest point on this convex polytope from a point P0.
Parameters:
P0 - [in] Base Point for closest point
dex -[out]
bary - [out] Evaluate(dex,bary) is the closest point on this polyhedran
maximum_distance - [in ] optional upper bound on distance
Returns:
Returns true if a closest point is found and it is within optional maximum_distance bound;
Details:
Setting maximum_distance can speedup the calculation in cases where dist(P0, *this)>maximum_distance.
*/
bool GetClosestPoint( ON_3dPoint P0,
ON_4dex& dex, ON_4dPoint& bary,
double maximum_distance = ON_DBL_MAX) const;
// Expert version of GetClosestPoint.
// dex is used at input to seed search algorithm.
// the points of *this singled out by dex must define a nondegenerate simplex
bool GetClosestPointSeeded(ON_3dPoint P0,
ON_4dex& dex, ON_4dPoint& Bary,
double maximum_distance = ON_DBL_MAX) const;
/*
Description:
Computes a pair of points on *this and BHull that achieve the minimum distance between
the two convex polytopes.
Parameters:
BHull - [in] the other convex polytope
adex, bdex -[out] Evaluate(adex,bary) is the closest point on this polyhedron
bary - [out] BHull.Evaluate(bdex,bary) is the closest point on BHull.
maximum_distance - [in ] optional upper bound on distance
Returns:
Returns true if a closest points are found and they are within optional maximum_distance bound;
Details:
Setting maximum_distance can speedup the calculation in cases where dist(*this, BHull)>maximum_distance.
*/
bool GetClosestPoint(const ON_ConvexPoly& BHull,
ON_4dex& Adex, ON_4dex& Bdex, ON_4dPoint& bary,
double maximum_distance = ON_DBL_MAX) const;
// Expert version of GetClosestPoint.
// Adex and Bdex are used at input to seed search algorithm.
// the points of this-Bhull singled out by Adex and Bdex must define a nondegenerate simplex
bool GetClosestPointSeeded(const ON_ConvexPoly& BHull,
ON_4dex& Adex, ON_4dex& Bdex, ON_4dPoint& bary,
double maximum_distance = ON_DBL_MAX) const;
/*
Description:
This is a bound on the collection of verticies.
Vertex(i).MaximumCoordinate()<= MaximumCoordinate() for all i
*/
virtual double MaximumCoordinate() const = 0;
/*
Description:
A point represented by a ON_4dex D and a barycentric coordinate B
can be put in a standard form so that non-negative elements of D are unique and
corresponding coordinates are positive. Furthemore, the non-negative
indicies are all listed before the unset ( neagative ) values
*/
static bool Standardize(ON_4dex& D, ON_4dPoint& B);
/*
Returns:
true if d[i]<n for i=0..3 a valid ON_4dex for a point in a ON_ConvexPolyBase with Count()=n
*/
static bool IsValid4DexN(const ON_4dex& D, int n)
{
for (int i = 0; i < 4; i++) {
if (D[i] > n) return false;
}
return true;
}
bool IsValid4Dex(const ON_4dex& D) const { return IsValid4DexN(D, Count()); };
virtual ~ON_ConvexPoly() {};
};
// 3d convex hull defined by an explicit collection of points called verticies.
// Note: verticies need not be extreme points
// WARNING: Points are referenced not stored for optimal performance in'
// some applications.
// The list of points must remain alive and in there initial location
// For the duration of this object.
class ON_CLASS ON_ConvexHullRef : public ON_ConvexPoly
{
public:
ON_ConvexHullRef() { m_n = 0; m_is_rat = false; m_stride = 3; };
ON_ConvexHullRef(const ON_3dVector* V0, int count); // a 3d point array
ON_ConvexHullRef(const ON_3dPoint* V0, int count); // a 3d point array
ON_ConvexHullRef(const ON_4dPoint* V0, int count); // a array of homogeneous points
ON_ConvexHullRef(const double* v0, bool is_rat, int n); // v0 is an array of 3dpoints or homo 4d points
ON_ConvexHullRef(const double* v0, bool is_rat, int n, int stride); // v0 is an array of 3dpoints or homo 4d points
void Initialize(const ON_3dVector* V0, int count);
void Initialize(const ON_4dPoint* V0, int count);
void Initialize(const double* V0, ON::point_style style, int count); // style must be either not_rational or homogeneous_rational = 2,
int Count() const override { return m_n; }
ON_3dVector Vertex(int j) const override;
// Support map
virtual int SupportIndex(ON_3dVector W, int i0) const override;
virtual double MaximumCoordinate() const override;
virtual ~ON_ConvexHullRef() override {};
private:
int m_n = 0;
bool m_is_rat= false;
const double* m_v = nullptr;
int m_stride=3;
};
// 3d convex hull defined by an explicit collection of points called verticies.
// Note: verticies need not be extreme points
class ON_CLASS ON_ConvexHullPoint2 : public ON_ConvexPoly
{
public:
ON_ConvexHullPoint2() = default;
ON_ConvexHullPoint2(int init_capacity) : m_Vert(init_capacity) {};
virtual int Count() const override { return m_Vert.Count(); }
virtual ON_3dVector Vertex(int j) const override { return m_Vert[j]; }
// Support map
virtual int SupportIndex(ON_3dVector W, int i0) const override {
return Ref.SupportIndex(W, i0);
};
virtual double MaximumCoordinate() const override;
virtual ~ON_ConvexHullPoint2() override {};
int AppendVertex(const ON_3dPoint& P); // return index of new vertex. must set Adjacent Indicies.
void Empty();
bool SetCapacity(int vcnt) {
m_Vert.SetCapacity(vcnt);
return true;
};
private:
ON_ConvexHullRef Ref;
ON_SimpleArray<ON_3dVector> m_Vert;
};
/*
Compute Convex hull of 2d points
Parameters:
Pnt - array of points, this is array of working data. The points are sorted in place as part of the algorithm
HUll - the sequence Hull[0], HUll[1]... ,*Hull.Last() == Hull[0] defines the convex hull with a positive orientation retuns 2.
PntInd - otional array to be filled in so that Hull[i] = Pnt[ PntInd[i]] where Pnt is the original input point
Returns
dimension of the convex hull
2 - Hull is 2 dimensional
1 - Hull is a line segments
0 - hull is a point
<0 error
*/
ON_DECL
int ON_ConvexHull2d(const ON_SimpleArray<ON_2dPoint>& Pnt, ON_SimpleArray<ON_2dPoint>& Hull, ON_SimpleArray< int>* PntInd = nullptr);
#endif
+108
View File
@@ -0,0 +1,108 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2015 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_CPP_BASE_INC_)
#define OPENNURBS_CPP_BASE_INC_
// basic C++ declarations
#if !defined(UUID_DEFINED) && !defined(GUID_DEFINED)
// basic C++ declarations
bool operator==(const struct ON_UUID_struct& a, const struct ON_UUID_struct& b);
bool operator!=(const struct ON_UUID_struct& a, const struct ON_UUID_struct& b);
#endif
class ON_CLASS ON_StopWatch
{
public:
ON_StopWatch() = default;
~ON_StopWatch() = default;
ON_StopWatch(const ON_StopWatch&) = default;
ON_StopWatch& operator=(const ON_StopWatch&) = default;
public:
enum class State : unsigned char
{
///<summary>
/// The stopwatch is off.
///</summary>
Off = 0,
///<summary>
/// The stopwatch is started and running.
///</summary>
Running = 1,
///<summary>
/// The stopwatch has been started and stopped.
///</summary>
Stopped = 2
};
/*
Description:
If the stopwatch is off or stopped, it is started. Otherwise nothing happens.
*/
void Start();
/*
Description:
If the stopwatch is running, then it is stopped. Otherwise nothing happens.
Returns:
If the stopwatch was running, the elapsed time from the most recent Start().
Otherwise, 0.0 is returned.
*/
double Stop();
/*
Description:
The stopwatch is reset and turned off. Any previously set times are lost.
*/
void Reset();
/*
Returns:
Current state of the stopwatch.
*/
ON_StopWatch::State CurrentState() const;
/*
Returns:
The elapsed time in seconds.
Remarks:
If the stopwatch is running, the elapsed time is the duration from the most recent Start() to now.
If the stopwatch is stopped, the elapsed time is the duration between the most recent Start() and Stop().
If the stopwatch is off, the elapsed time is zero.
*/
double ElapsedTime() const;
private:
// current state
ON_StopWatch::State m_state = ON_StopWatch::State::Off;
#pragma ON_PRAGMA_WARNING_PUSH
#pragma ON_PRAGMA_WARNING_DISABLE_MSC( 4251 )
// C4251: ... : class 'std::...'
// needs to have dll-interface to be used by clients ...
// m_start and m_stop are private and all code that manages them is explicitly implemented in the DLL.
std::chrono::high_resolution_clock::time_point m_start; // most recent Start() time.
std::chrono::high_resolution_clock::time_point m_stop; // most recent Stop() time.
#pragma ON_PRAGMA_WARNING_POP
};
#endif
+152
View File
@@ -0,0 +1,152 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_CRC_INC_)
#define OPENNURBS_CRC_INC_
ON_BEGIN_EXTERNC
/*
Description:
Continues 16 bit CRC calulation to include the buffer.
Parameters:
current_remainder - [in]
sizeof_buffer - [in] number of bytes in buffer
buffer - [in]
Example:
16 bit CRC calculations are typically done something like this:
const ON__UINT16 crc_seed = 0; // or 1, or your favorite starting value
// Compute CRC on "good" data
unsigned ON__UINT16 first_crc = crc_seed;
first_crc = ON_CRC16( first_crc, size1, buffer1 );
...
first_crc = ON_CRC16( first_crc, sizeN, bufferN );
unsigned char two_zero_bytes[2] = (0,0);
first_crc = ON_CRC16( first_crc, 2, two_zero_bytes );
// make sure 16 bit CRC calculation is valid
ON__UINT16 check_crc_calculation = ON_CRC16( first_crc, 2, &first_crc );
if ( check_crc_calculation != 0 )
{
printf("ON_CRC16() calculated a bogus 16 bit CRC\n");
}
// Do something that may potentially change the values in
// the buffers (like storing them on a faulty disk).
// Compute CRC on "suspect" data
ON__UINT16 second_crc = crc_seed;
second_crc = ON_CRC16( second_crc, size1, buffer1 );
...
second_crc = ON_CRC16( second_crc, sizeN, bufferN );
if ( 0 != ON_CRC16( second_crc, 2, &first_crc ) )
{
printf( "The value of at least one byte has changed.\n" );
}
*/
ON_DECL
ON__UINT16 ON_CRC16(
ON__UINT16 current_remainder,
size_t sizeof_buffer,
const void* buffer
);
/*
Description:
Continues 32 bit CRC calulation to include the buffer
ON_CRC32() is a slightly altered version of zlib 1.3.3's crc32()
and the zlib "legal stuff" is reproduced below.
ON_CRC32() and zlib's crc32() compute the same values. ON_CRC32()
was renamed so it wouldn't clash with the other crc32()'s that are
out there and the argument order was switched to match that used by
the legacy ON_CRC16().
Parameters:
current_remainder - [in]
sizeof_buffer - [in] number of bytes in buffer
buffer - [in]
Example:
32 bit CRC calculations are typically done something like this:
const ON__UINT32 crc_seed = 0; // or 1, or your favorite starting value
//Compute CRC on "good" data
ON__UINT32 first_crc = crc_seed;
first_crc = ON_CRC32( first_crc, size1, buffer1 );
...
first_crc = ON_CRC32( first_crc, sizeN, bufferN );
// Do something that may potentially change the values in
// the buffers (like storing them on a faulty disk).
// Compute CRC on "suspect" data
ON__UINT32 second_crc = crc_seed;
second_crc = ON_CRC32( second_crc, size1, buffer1 );
...
second_crc = ON_CRC32( second_crc, sizeN, bufferN );
if ( second_crc != first_crc )
{
printf( "The value of at least one byte has changed.\n" );
}
*/
ON_DECL
ON__UINT32 ON_CRC32(
ON__UINT32 current_remainder,
size_t sizeof_buffer,
const void* buffer
);
/*
zlib.h -- interface of the 'zlib' general purpose compression library
version 1.1.3, July 9th, 1998
Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jean-loup Gailly Mark Adler
jloup@gzip.org madler@alumni.caltech.edu
The data format used by the zlib library is described by RFCs (Request for
Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt
(zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
*/
ON_END_EXTERNC
#endif
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,201 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_CURVE_ON_SURFACE_INC_)
#define OPENNURBS_CURVE_ON_SURFACE_INC_
class ON_CLASS ON_CurveOnSurface : public ON_Curve
{
ON_OBJECT_DECLARE(ON_CurveOnSurface);
public:
ON_CurveOnSurface() ON_NOEXCEPT;
/*
Remarks:
Deletes m_c2, m_c3, and m_s. Use ON_CurveProxy or ON_SurfaceProxy
if you need to use curves or a surface that you do not want deleted.
*/
virtual ~ON_CurveOnSurface();
private:
ON_CurveOnSurface(const ON_CurveOnSurface&); // no implementation
private:
ON_CurveOnSurface& operator=(const ON_CurveOnSurface&); // no implementation
#if defined(ON_HAS_RVALUEREF)
public:
// rvalue copy constructor
ON_CurveOnSurface( ON_CurveOnSurface&& ) ON_NOEXCEPT;
// The rvalue assignment operator calls ON_Object::operator=(ON_Object&&)
// which could throw exceptions. See the implementation of
// ON_Object::operator=(ON_Object&&) for details.
ON_CurveOnSurface& operator=( ON_CurveOnSurface&& );
#endif
public:
/*
Parameters:
p2dCurve - [in] ~ON_CurveOnSurface() will delete this curve.
Use an ON_CurveProxy if you don't want the original deleted.
p3dCurve - [in] ~ON_CurveOnSurface() will delete this curve.
Use an ON_CurveProxy if you don't want the original deleted.
pSurface - [in] ~ON_CurveOnSurface() will delete this surface.
Use an ON_SurfaceProxy if you don't want the original deleted.
*/
ON_CurveOnSurface( ON_Curve* p2dCurve, // required 2d curve
ON_Curve* p3dCurve, // optional 3d curve
ON_Surface* pSurface // required surface
);
// virtual ON_Object::SizeOf override
unsigned int SizeOf() const override;
/////////////////////////////////////////////////////////////////
// ON_Object overrides
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
void Dump( ON_TextLog& ) const override; // for debugging
bool Write(
ON_BinaryArchive& // open binary file
) const override;
bool Read(
ON_BinaryArchive& // open binary file
) override;
/////////////////////////////////////////////////////////////////
// ON_Geometry overrides
int Dimension() const override;
// virtual ON_Geometry GetBBox override
bool GetBBox( double* boxmin, double* boxmax, bool bGrowBox = false ) const override;
bool Transform(
const ON_Xform&
) override;
// (optional - default uses Transform for 2d and 3d objects)
bool SwapCoordinates(
int, int // indices of coords to swap
) override;
/////////////////////////////////////////////////////////////////
// ON_Curve overrides
ON_Interval Domain() const override;
int SpanCount() const override; // number of smooth spans in curve
bool GetSpanVector( // span "knots"
double* // array of length SpanCount() + 1
) const override; //
int Degree( // returns maximum algebraic degree of any span
// ( or a good estimate if curve spans are not algebraic )
) const override;
// (optional - override if curve is piecewise smooth)
bool GetParameterTolerance( // returns tminus < tplus: parameters tminus <= s <= tplus
double, // t = parameter in domain
double*, // tminus
double* // tplus
) const override;
bool IsLinear( // true if curve locus is a line segment between
// between specified points
double = ON_ZERO_TOLERANCE // tolerance to use when checking linearity
) const override;
bool IsArc( // ON_Arc.m_angle > 0 if curve locus is an arc between
// specified points
const ON_Plane* = nullptr, // if not nullptr, test is performed in this plane
ON_Arc* = nullptr, // if not nullptr and true is returned, then arc parameters
// are filled in
double = ON_ZERO_TOLERANCE // tolerance to use when checking
) const override;
bool IsPlanar(
ON_Plane* = nullptr, // if not nullptr and true is returned, then plane parameters
// are filled in
double = ON_ZERO_TOLERANCE // tolerance to use when checking
) const override;
bool IsInPlane(
const ON_Plane&, // plane to test
double = ON_ZERO_TOLERANCE // tolerance to use when checking
) const override;
bool IsClosed( // true if curve is closed (either curve has
void // clamped end knots and euclidean location of start
) const override; // CV = euclidean location of end CV, or curve is
// periodic.)
bool IsPeriodic( // true if curve is a single periodic segment
void
) const override;
bool Reverse() override; // reverse parameterizatrion
// Domain changes from [a,b] to [-b,-a]
bool Evaluate( // returns false if unable to evaluate
double, // evaluation parameter
int, // number of derivatives (>=0)
int, // array stride (>=Dimension())
double*, // array of length stride*(ndir+1)
int = 0, // optional - determines which side to evaluate from
// 0 = default
// < 0 to evaluate from below,
// > 0 to evaluate from above
int* = 0 // optional - evaluation hint (int) used to speed
// repeated evaluations
) const override;
int GetNurbForm( // returns 0: unable to create NURBS representation
// with desired accuracy.
// 1: success - returned NURBS parameterization
// matches the curve's to wthe desired accuracy
// 2: success - returned NURBS point locus matches
// the curve's to the desired accuracy but, on
// the interior of the curve's domain, the
// curve's parameterization and the NURBS
// parameterization may not match to the
// desired accuracy.
ON_NurbsCurve&,
double = 0.0,
const ON_Interval* = nullptr // OPTIONAL subdomain of 2d curve
) const override;
/////////////////////////////////////////////////////////////////
// Interface
// ~ON_CurveOnSurface() deletes these classes. Use a
// ON_CurveProxy and/or ON_SurfaceProxy wrapper if you don't want
// the destructor to destroy the curves
ON_Curve* m_c2; // REQUIRED parameter space (2d) curve
ON_Curve* m_c3; // OPTIONAL 3d curve (approximation) to srf(crv2(t))
ON_Surface* m_s;
};
#endif
+467
View File
@@ -0,0 +1,467 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
////////////////////////////////////////////////////////////////
//
// Definition of curve proxy object
//
////////////////////////////////////////////////////////////////
#if !defined(OPENNURBS_CURVEPROXY_INC_)
#define OPENNURBS_CURVEPROXY_INC_
/*
Description:
An ON_CurveProxy is a reference to an ON_Curve.
One may specify a subdomain of the referenced curve
and apply a affine reparameterization, possibly reversing
the orientation. The underlying curve cannot be modified through
the curve proxy.
Details:
The reference to the "real_curve" is const, so most functions
which modify an ON_Curve will fail when passed an ON_CurveProxy.
*/
class ON_CurveProxy;
class ON_CLASS ON_CurveProxy : public ON_Curve
{
ON_OBJECT_DECLARE(ON_CurveProxy);
public:
ON_CurveProxy() ON_NOEXCEPT;
virtual ~ON_CurveProxy();
ON_CurveProxy( const ON_CurveProxy& );
ON_CurveProxy& operator=(const ON_CurveProxy&);
#if defined(ON_HAS_RVALUEREF)
// rvalue copy constructor
ON_CurveProxy( ON_CurveProxy&& ) ON_NOEXCEPT;
// The rvalue assignment operator calls ON_Object::operator=(ON_Object&&)
// which could throw exceptions. See the implementation of
// ON_Object::operator=(ON_Object&&) for details.
ON_CurveProxy& operator=( ON_CurveProxy&& );
#endif
public:
// virtual ON_Object::DestroyRuntimeCache override
void DestroyRuntimeCache( bool bDelete = true ) override;
ON_CurveProxy( const ON_Curve* );
ON_CurveProxy( const ON_Curve*, ON_Interval );
// virtual ON_Object::SizeOf override
unsigned int SizeOf() const override;
// virtual ON_Object::DataCRC override
ON__UINT32 DataCRC(ON__UINT32 current_remainder) const override;
/*
Description:
Sets the curve geometry that "this" is a proxy for.
Sets proxy domain to proxy_curve->Domain().
Parameters:
real_curve - [in]
*/
void SetProxyCurve( const ON_Curve* real_curve );
/*
Description:
Sets the curve geometry that "this" is a proxy for.
Sets proxy domain to proxy_curve->Domain().
Parameters:
real_curve - [in]
real_curve_subdomain - [in] increasing sub interval of
real_curve->Domain(). This interval defines the
portion the "real" curve geometry that "this" proxy
uses.
bReversed - [in] true if the parameterization of "this" proxy
as a curve is reversed from the underlying "real" curve
geometry.
*/
void SetProxyCurve( const ON_Curve* real_curve,
ON_Interval real_curve_subdomain
);
/*
Returns:
"Real" curve geometry that "this" is a proxy for.
*/
const ON_Curve* ProxyCurve() const;
/*
Description:
Sets portion of the "real" curve that this proxy represents.
Does NOT change the domain of "this" curve.
Parameters:
proxy_curve_subdomain - [in] increasing sub interval of
ProxyCurve()->Domain(). This interval defines the
portion the curve geometry that "this" proxy uses.
Remarks:
This function is poorly named. It does NOT set the proxy
curve's domain. It does set the interval of the "real"
curve for which "this" is a proxy.
*/
bool SetProxyCurveDomain( ON_Interval proxy_curve_subdomain );
/*
Returns:
Sub interval of the "real" curve's domain that "this" uses.
This interval is not necessarily the same as "this" curve's
domain.
Remarks:
This function is poorly named. It does NOT get the proxy
curve's domain. It does get the evaluation interval
of the "real" curve for which "this" is a proxy.
*/
ON_Interval ProxyCurveDomain() const;
/*
Returns:
True if "this" as a curve is reversed from the "real" curve
geometry.
*/
bool ProxyCurveIsReversed() const;
protected:
// Used by CRhinoPolyEdgeSegment::Create() to restore the
// value of ON_CurveProxy::m_bReversed.
void SetProxyCurveIsReversed(bool bReversed);
public:
/*
Parameters:
t - [in] parameter for "this" curve
Returns:
Corresponding parameter in m_real_curve's domain.
*/
double RealCurveParameter( double t ) const;
/*
Parameters:
real_curve_parameter - [in] m_real_curve parameter
Returns:
Corresponding parameter for "this" curve
*/
double ThisCurveParameter( double real_curve_parameter ) const;
private:
// "real" curve geometry that "this" is a proxy for.
const ON_Curve* m_real_curve;
// If true, the parameterization of "this" proxy is
// the reverse of the m_curve parameterization.
bool m_bReversed;
// The m_domain interval is always increasing and included in
// m_curve->Domain(). The m_domain interval defines the portion
// of m_curve that "this" proxy uses and it can be a proper
// sub-interval of m_curve->Domain().
ON_Interval m_real_curve_domain;
// The evaluation domain of this curve. If "t" is a parameter for
// "this" and "r" is a parameter for m_curve, then when m_bReversed==false
// we have
// t = m_this_domain.ParameterAt(m_real_curve_domain.NormalizedParameterAt(r))
// r = m_real_curve_domain.ParameterAt(m_this_domain.NormalizedParameterAt(t))
// and when m_bReversed==true we have
// t = m_this_domain.ParameterAt(1 - m_real_curve_domain.NormalizedParameterAt(r))
// r = m_real_curve_domain.ParameterAt(1 - m_this_domain.NormalizedParameterAt(t))
ON_Interval m_this_domain;
ON_Interval RealCurveInterval( const ON_Interval* sub_domain ) const;
public:
/*
Description:
Get a duplicate of the curve.
Returns:
A duplicate of the curve.
Remarks:
The caller must delete the returned curve.
For non-ON_CurveProxy objects, this simply duplicates the curve using
ON_Object::Duplicate.
For ON_CurveProxy objects, this duplicates the actual proxy curve
geometry and, if necessary, trims and reverse the result to that
the returned curve's parameterization and locus match the proxy curve's.
*/
ON_Curve* DuplicateCurve() const override;
/////////////////////////////////////////////////////////////////
// ON_Object overrides
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
void Dump( ON_TextLog& ) const override; // for debugging
bool Write( // returns false - nothing serialized
ON_BinaryArchive& // open binary file
) const override;
bool Read( // returns false - nothing serialized
ON_BinaryArchive& // open binary file
) override;
/////////////////////////////////////////////////////////////////
// ON_Geometry overrides
int Dimension() const override;
// virtual ON_Geometry GetBBox override
bool GetBBox( double* boxmin, double* boxmax, bool bGrowBox = false ) const override;
bool Transform(
const ON_Xform&
) override;
/////////////////////////////////////////////////////////////////
// ON_Curve overrides
// Returns:
// domain of the curve.
// Remarks:
// If m_bReverse is true, this returns the reverse
// of m_domain.
ON_Interval Domain() const override;
/* virtual ON_Curve::SetDomain() override */
bool SetDomain(
double t0,
double t1
) override;
bool SetDomain( ON_Interval domain );
int SpanCount() const override; // number of smooth spans in curve
bool GetSpanVector(
double*
) const override;
int Degree( // returns maximum algebraic degree of any span
// ( or a good estimate if curve spans are not algebraic )
) const override;
// (optional - override if curve is piecewise smooth)
bool GetParameterTolerance( // returns tminus < tplus: parameters tminus <= s <= tplus
double, // t = parameter in domain
double*, // tminus
double* // tplus
) const override;
bool IsLinear( // true if curve locus is a line segment between
// between specified points
double = ON_ZERO_TOLERANCE // tolerance to use when checking linearity
) const override;
// virtual override of ON_Curve::IsPolyline
int IsPolyline(
ON_SimpleArray<ON_3dPoint>* pline_points = nullptr,
ON_SimpleArray<double>* pline_t = nullptr
) const override;
bool IsArc( // ON_Arc.m_angle > 0 if curve locus is an arc between
// specified points
const ON_Plane* = nullptr, // if not nullptr, test is performed in this plane
ON_Arc* = nullptr, // if not nullptr and true is returned, then arc parameters
// are filled in
double = ON_ZERO_TOLERANCE // tolerance to use when checking
) const override;
bool IsPlanar(
ON_Plane* = nullptr, // if not nullptr and true is returned, then plane parameters
// are filled in
double = ON_ZERO_TOLERANCE // tolerance to use when checking
) const override;
bool IsInPlane(
const ON_Plane&, // plane to test
double = ON_ZERO_TOLERANCE // tolerance to use when checking
) const override;
bool IsClosed( // true if curve is closed (either curve has
void // clamped end knots and euclidean location of start
) const override; // CV = euclidean location of end CV, or curve is
// periodic.)
bool IsPeriodic( // true if curve is a single periodic segment
void
) const override;
/*
Description:
Search for a derivatitive, tangent, or curvature discontinuity.
Parameters:
c - [in] type of continity to test for. If ON::continuity::C1_continuous
t0 - [in] search begins at t0
t1 - [in] (t0 < t1) search ends at t1
t - [out] if a discontinuity is found, the *t reports the
parameter at the discontinuity.
hint - [in/out] if GetNextDiscontinuity will be called repeatedly,
passing a "hint" with initial value *hint=0 will increase the speed
of the search.
dtype - [out] if not nullptr, *dtype reports the kind of discontinuity
found at *t. A value of 1 means the first derivative or unit tangent
was discontinuous. A value of 2 means the second derivative or
curvature was discontinuous.
cos_angle_tolerance - [in] default = cos(1 degree) Used only when
c is ON::continuity::G1_continuous or ON::continuity::G2_continuous. If the cosine
of the angle between two tangent vectors
is <= cos_angle_tolerance, then a G1 discontinuity is reported.
curvature_tolerance - [in] (default = ON_SQRT_EPSILON) Used only when
c is ON::continuity::G2_continuous or ON::continuity::Gsmooth_continuous.
ON::continuity::G2_continuous:
If K0 and K1 are curvatures evaluated
from above and below and |K0 - K1| > curvature_tolerance,
then a curvature discontinuity is reported.
ON::continuity::Gsmooth_continuous:
If K0 and K1 are curvatures evaluated from above and below
and the angle between K0 and K1 is at least twice angle tolerance
or ||K0| - |K1|| > (max(|K0|,|K1|) > curvature_tolerance,
then a curvature discontinuity is reported.
Returns:
true if a discontinuity was found on the interior of the interval (t0,t1).
Remarks:
Overrides ON_Curve::GetNextDiscontinuity.
*/
bool GetNextDiscontinuity(
ON::continuity c,
double t0,
double t1,
double* t,
int* hint=nullptr,
int* dtype=nullptr,
double cos_angle_tolerance=ON_DEFAULT_ANGLE_TOLERANCE_COSINE,
double curvature_tolerance=ON_SQRT_EPSILON
) const override;
/*
Description:
Test continuity at a curve parameter value.
Parameters:
c - [in] continuity to test for
t - [in] parameter to test
hint - [in] evaluation hint
point_tolerance - [in] if the distance between two points is
greater than point_tolerance, then the curve is not C0.
d1_tolerance - [in] if the difference between two first derivatives is
greater than d1_tolerance, then the curve is not C1.
d2_tolerance - [in] if the difference between two second derivatives is
greater than d2_tolerance, then the curve is not C2.
cos_angle_tolerance - [in] default = cos(1 degree) Used only when
c is ON::continuity::G1_continuous or ON::continuity::G2_continuous. If the cosine
of the angle between two tangent vectors
is <= cos_angle_tolerance, then a G1 discontinuity is reported.
curvature_tolerance - [in] (default = ON_SQRT_EPSILON) Used only when
c is ON::continuity::G2_continuous or ON::continuity::Gsmooth_continuous.
ON::continuity::G2_continuous:
If K0 and K1 are curvatures evaluated
from above and below and |K0 - K1| > curvature_tolerance,
then a curvature discontinuity is reported.
ON::continuity::Gsmooth_continuous:
If K0 and K1 are curvatures evaluated from above and below
and the angle between K0 and K1 is at least twice angle tolerance
or ||K0| - |K1|| > (max(|K0|,|K1|) > curvature_tolerance,
then a curvature discontinuity is reported.
Returns:
true if the curve has at least the c type continuity at the parameter t.
Remarks:
Overrides ON_Curve::IsContinuous.
*/
bool IsContinuous(
ON::continuity c,
double t,
int* hint = nullptr,
double point_tolerance=ON_ZERO_TOLERANCE,
double d1_tolerance=ON_ZERO_TOLERANCE,
double d2_tolerance=ON_ZERO_TOLERANCE,
double cos_angle_tolerance=ON_DEFAULT_ANGLE_TOLERANCE_COSINE,
double curvature_tolerance=ON_SQRT_EPSILON
) const override;
bool Reverse() override; // reverse parameterizatrion
// Domain changes from [a,b] to [-b,-a]
bool Evaluate( // returns false if unable to evaluate
double, // evaluation parameter
int, // number of derivatives (>=0)
int, // array stride (>=Dimension())
double*, // array of length stride*(ndir+1)
int = 0, // optional - determines which side to evaluate from
// 0 = default
// < 0 to evaluate from below,
// > 0 to evaluate from above
int* = 0 // optional - evaluation hint (int) used to speed
// repeated evaluations
) const override;
// override of virtual ON_Curve::Trim
bool Trim(
const ON_Interval& domain
) override;
// override of virtual ON_Curve::Split
bool Split(
double t,
ON_Curve*& left_side,
ON_Curve*& right_side
) const override;
int GetNurbForm( // returns 0: unable to create NURBS representation
// with desired accuracy.
// 1: success - returned NURBS parameterization
// matches the curve's to wthe desired accuracy
// 2: success - returned NURBS point locus matches
// the curve's to the desired accuracy but, on
// the interior of the curve's domain, the
// curve's parameterization and the NURBS
// parameterization may not match to the
// desired accuracy.
ON_NurbsCurve&,
double = 0.0,
const ON_Interval* = nullptr // OPTIONAL subdomain of ON_CurveProxy::Domain()
) const override;
int HasNurbForm( // returns 0: unable to create NURBS representation
// with desired accuracy.
// 1: success - returned NURBS parameterization
// matches the curve's to wthe desired accuracy
// 2: success - returned NURBS point locus matches
// the curve's to the desired accuracy but, on
// the interior of the curve's domain, the
// curve's parameterization and the NURBS
// parameterization may not match to the
// desired accuracy.
) const override;
// virtual ON_Curve::GetCurveParameterFromNurbFormParameter override
bool GetCurveParameterFromNurbFormParameter(
double, // nurbs_t
double* // curve_t
) const override;
// virtual ON_Curve::GetNurbFormParameterFromCurveParameter override
bool GetNurbFormParameterFromCurveParameter(
double, // curve_t
double* // nurbs_t
) const override;
};
#endif
+152
View File
@@ -0,0 +1,152 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_CYLINDER_INC_)
#define OPENNURBS_CYLINDER_INC_
class ON_NurbsSurface;
class ON_RevSurface;
class ON_Brep;
/*
Description:
ON_Cylinder is a right circular cylinder.
*/
class ON_CLASS ON_Cylinder
{
public:
ON_Cylinder(); // zeros all fields - cylinder is invalid
ON_Cylinder( // infinte cylinder
const ON_Circle& // point on the bottom plane
);
ON_Cylinder( // infinte cylinder
const ON_Circle&, // point on the bottom plane
double // height
);
~ON_Cylinder();
bool Create(
const ON_Circle& // point on the bottom plane
);
bool Create(
const ON_Circle&, // point on the bottom plane
double // height
);
bool IsValid() const; // returns true if all fields contain reasonable
// information and equation jibes with point and Z.
bool IsFinite() const; // returns true if the cylinder is finite
// (height[0] != height[1]) and false if the
// cylinder is infinite.
const ON_3dVector& Axis() const;
const ON_3dPoint& Center() const;
double Height() const; // returns 0 for infinite cylinder
ON_Circle CircleAt(
double // linear parameter
) const;
ON_Line LineAt(
double // angular parameter
) const;
// evaluate parameters and return point
ON_3dPoint PointAt(
double, // angular parameter [0,2pi]
double // linear parameter (height from base circle's plane)
) const;
ON_3dPoint NormalAt(
double, // angular parameter [0,2pi]
double // linear parameter (height from base circle's plane)
) const;
// returns parameters of point on cylinder that is closest to given point
bool ClosestPointTo(
ON_3dPoint,
double*, // angular parameter [0,2pi]
double* // linear parameter (height from base circle's plane)
) const;
// returns point on cylinder that is closest to given point
ON_3dPoint ClosestPointTo(
ON_3dPoint
) const;
// For intersections see ON_Intersect();
// rotate cylinder about its origin
bool Rotate(
double, // sin(angle)
double, // cos(angle)
const ON_3dVector& // axis of rotation
);
bool Rotate(
double, // angle in radians
const ON_3dVector& // axis of rotation
);
// rotate cylinder about a point and axis
bool Rotate(
double, // sin(angle)
double, // cos(angle)
const ON_3dVector&, // axis of rotation
const ON_3dPoint& // center of rotation
);
bool Rotate(
double, // angle in radians
const ON_3dVector&, // axis of rotation
const ON_3dPoint& // center of rotation
);
bool Translate(
const ON_3dVector&
);
// parameterization of NURBS surface does not match cylinder's transcendental paramaterization
int GetNurbForm( ON_NurbsSurface& ) const; // returns 0=failure, 2=success
/*
Description:
Creates a surface of revolution definition of the cylinder.
Parameters:
srf - [in] if not nullptr, then this srf is used.
Result:
A surface of revolution or nullptr if the cylinder is not
valid or is infinite.
*/
ON_RevSurface* RevSurfaceForm( ON_RevSurface* srf = nullptr ) const;
public: // members left public
// base circle
ON_Circle circle;
// If height[0] = height[1], the cylinder is infinite,
// Otherwise, height[0] < height[1] and the center of
// the "bottom" cap is
//
// circle.plane.origin + height[0]*circle.plane.zaxis,
//
// and the center of the top cap is
//
// circle.plane.origin + height[1]*circle.plane.zaxis.
double height[2];
};
#endif
+108
View File
@@ -0,0 +1,108 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2013 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_DATE_INC_)
#define OPENNURBS_DATE_INC_
/*
Description:
Get the day of the year from the year, month and day_of_month.
Parameters:
year - [in]
>= 1582
month - [in]
>= 1 and <= 12
day_of_month - [in]
>= 1 and <= last valid day_of_month of the month
Returns:
0: Invalid input
1 to 366: Day of Gregorian year.
*/
ON_DECL
unsigned int ON_DayOfGregorianYear(
unsigned int year,
unsigned int month,
unsigned int day_of_month
);
/*
Parameters:
year - [in]
>= 1582
Returns:
0: Invalid input
365: If the year is a common year in the Gregorian calendar
366: If the year is a leap year in the Gregorian calendar
*/
ON_DECL
unsigned int ON_DaysInGregorianYear(
unsigned int year
);
/*
Description:
Get the number of days in a Gregorian month.
Parameters:
year - [in]
>= 1582
month - [in]
>= 1 and <= 12
Returns:
0: Invalid input
28, 29, 30 or 31: number of days in the specified month.
*/
ON_DECL
unsigned int ON_DaysInMonthOfGregorianYear(
unsigned int year,
unsigned int month
);
/*
Description:
Get the month and day_of_month from the year and day of year.
Parameters:
year - [in]
>= 1582
day_of_year
>= 1 and <= (ON_IsGregorianLeapYear(year) ? 366 : 365)
month - [out]
>= 1 and <= 12, when input parameters are valid, otherwise 0.
day_of_month - [out]
>= 1 and <= ON_DaysInMonthOfGregorianYear(year,month),
when input parameters are valid, otherwise 0.
Returns:
true: month and day_of_month returned.
false: invalid input. Output values are zero.
*/
ON_DECL
bool ON_GetGregorianMonthAndDayOfMonth(
unsigned int year,
unsigned int day_of_year,
unsigned int* month,
unsigned int* day_of_month
);
/*
Parameters:
year - [in]
Returns:
true if the year is a leap year in the Gregorian calendar.
*/
ON_DECL
bool ON_IsGregorianLeapYear(
unsigned int year
);
#endif
File diff suppressed because it is too large Load Diff
+95
View File
@@ -0,0 +1,95 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(ON_DETAIL_OBJECTY_INC_)
#define ON_DETAIL_OBJECTY_INC_
class ON_CLASS ON_DetailView : public ON_Geometry
{
ON_OBJECT_DECLARE(ON_DetailView);
public:
ON_DetailView();
~ON_DetailView();
// C++ defaults for copy constructor and
// operator= work fine.
//////////////////////////////////////////////////////
//
// virtual ON_Object overrides
//
void MemoryRelocate() override;
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
void Dump( ON_TextLog& ) const override;
unsigned int SizeOf() const override;
bool Write(
ON_BinaryArchive& binary_archive
) const override;
bool Read(
ON_BinaryArchive& binary_archive
) override;
ON::object_type ObjectType() const override; // returns ON::detail_object
//////////////////////////////////////////////////////
//
// virtual ON_Geometry overrides
// The m_boundary determines all bounding boxes
//
int Dimension() const override;
// virtual ON_Geometry GetBBox override
bool GetBBox( double* boxmin, double* boxmax, bool bGrowBox = false ) const override;
// virtual ON_Geometry GetTightBoundingBox override
bool GetTightBoundingBox( class ON_BoundingBox& tight_bbox, bool bGrowBox = false, const class ON_Xform* xform = nullptr ) const override;
bool Transform( const ON_Xform& xform ) override;
// m_page_per_model_ratio is the ratio of page length / model length
// where both lengths are in the same unit system
// (ex. 1/4" on page = 1' in model = 0.25/12 = 0.02083)
// ( 1mm on page = 1m in model = 1/1000 = 0.001)
// If m_page_per_model_ratio > 0.0, then the detail
// is drawn using the specified scale.
double m_page_per_model_ratio;
// A view with ON_3dmView::m_view_type = ON::nested_view_type
// This field is used for IO purposes only. Runtime detail
// view projection information is on CRhDetailViewObject.
ON_3dmView m_view;
// 2d curve in page layout coordinates in mm
// (0,0) = lower left corner of page
ON_NurbsCurve m_boundary;
// Update frustum to match bounding box and detail scale
bool UpdateFrustum(
ON::LengthUnitSystem model_units,
ON::LengthUnitSystem paper_units
);
};
#endif
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,87 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
// ON_Table class
#ifndef OPENNURBS_NUMBERFORMAT_H_INCLUDED
#define OPENNURBS_NUMBERFORMAT_H_INCLUDED
class ON_NumberFormatter
{
ON_NumberFormatter();
public:
static bool bFormatIsAccurate;
static void Fraction(
double value,
int& wholenumber,
int& numerator,
int& denominator,
int precision);
static double RoundOff(
double number,
double round_off);
static void SuppressZeros(
ON_wString& dist,
ON_DimStyle::suppress_zero sz);
// When FormatNumber() or FormatLength() is called with
// output_lengthformat == ON_DimStyle::OBSOLETE_length_format::FeetInches
// distance must be in decimal feet units to get the right answer.
static bool FormatNumber(
double distance,
ON_DimStyle::OBSOLETE_length_format output_lengthformat, // dec, frac, ft-in
double round_off,
int resolution,
ON_DimStyle::suppress_zero zero_suppress,
bool bracket_fractions,
ON_wString& output);
// When FormatNumber() or FormatLength() is called with
// output_lengthformat == ON_DimStyle::LengthDisplay::FeetAndInches
// distance must be in decimal feet units to get the right answer.
static bool FormatLength(
double distance,
ON_DimStyle::LengthDisplay output_lengthdisplay,
double round_off,
int resolution,
ON_DimStyle::suppress_zero zero_suppress,
bool bracket_fractions,
ON_wString& output);
static bool FormatAngleStringDMS(
double angle_radians,
int resolution,
ON_wString& formatted_string);
static bool FormatAngleStringDMS(
double angle_degrees,
ON_wString& formatted_string);
static bool FormatAngleStringDecimal(
double angle_radians,
int resolution,
double roundoff,
ON_DimStyle::suppress_zero zero_suppression,
ON_wString& formatted_string);
};
#endif
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,14 @@
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by opennurbs.rc
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
+135
View File
@@ -0,0 +1,135 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_ELLIPSE_INC_)
#define OPENNURBS_ELLIPSE_INC_
class ON_Ellipse;
class ON_Plane;
class ON_CLASS ON_Ellipse
{
public:
ON_Ellipse(); // zeros all fields - plane is invalid
ON_Ellipse(
const ON_Plane&,
double, double // radii for x and y vectors
);
ON_Ellipse(
const ON_Circle&
);
~ON_Ellipse();
ON_Ellipse& operator=(const ON_Circle&);
bool Create(
const ON_Plane&, // point on the plane
double, double // radii for x and y vectors
);
bool Create(
const ON_Circle&
);
bool IsValid() const; // returns true if all fields contain reasonable
// information and equation jibes with point and Z.
bool IsCircle() const; // returns true is ellipse is a circle
double Radius(
int // 0 = x axis radius, 1 = y axis radius
) const;
const ON_3dPoint& Center() const;
const ON_3dVector& Normal() const;
const ON_Plane& Plane() const; // plane containing ellipse
/*
Returns:
Distance from the center to a focus, commonly called "c".
*/
double FocalDistance() const;
bool GetFoci( ON_3dPoint& F1, ON_3dPoint& F2 ) const;
// Evaluation uses the trigonometrix parameterization
// t -> plane.origin + cos(t)*radius[0]*plane.xaxis + sin(t)*radius[1]*plane.yaxis
// evaluate parameters and return point
ON_3dPoint PointAt( double ) const;
ON_3dVector DerivativeAt(
int, // desired derivative ( >= 0 )
double // parameter
) const;
ON_3dVector TangentAt( double ) const; // returns unit tangent
ON_3dVector CurvatureAt( double ) const; // returns curvature vector
// returns parameters of point on ellipse that is closest to given point
bool ClosestPointTo(
const ON_3dPoint&,
double*
) const;
// returns point on ellipse that is closest to given point
ON_3dPoint ClosestPointTo(
const ON_3dPoint&
) const;
// evaluate ellipse's implicit equation in plane
double EquationAt( const ON_2dPoint& ) const;
ON_2dVector GradientAt( const ON_2dPoint& ) const;
// rotate ellipse about its center
bool Rotate(
double, // sin(angle)
double, // cos(angle)
const ON_3dVector& // axis of rotation
);
bool Rotate(
double, // angle in radians
const ON_3dVector& // axis of rotation
);
// rotate ellipse about a point and axis
bool Rotate(
double, // sin(angle)
double, // cos(angle)
const ON_3dVector&, // axis of rotation
const ON_3dPoint& // center of rotation
);
bool Rotate(
double, // angle in radians
const ON_3dVector&, // axis of rotation
const ON_3dPoint& // center of rotation
);
bool Translate(
const ON_3dVector&
);
// parameterization of NURBS curve does not match ellipse's transcendental paramaterization
int GetNurbForm( ON_NurbsCurve& ) const; // returns 0=failure, 2=success
public: // members left public
// The center of the ellipse is at the plane's origin. The axes of the
// ellipse are the plane's x and y axes. The equation of the ellipse
// with respect to the plane is (x/m_r[0])^2 + (y/m_r[1])^2 = 1;
ON_Plane plane;
double radius[2]; // radii for x and y axes (both must be > 0)
};
#endif
+272
View File
@@ -0,0 +1,272 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_ERROR_INC_)
#define OPENNURBS_ERROR_INC_
/*
// Macros used to log errors and warnings. The ON_Warning() and ON_Error()
// functions are defined in opennurbs_error.cpp.
*/
#define ON_ERROR(msg) ON_ErrorEx(__FILE__,__LINE__,OPENNURBS__FUNCTION__,msg)
#define ON_WARNING(msg) ON_WarningEx(__FILE__,__LINE__,OPENNURBS__FUNCTION__,msg)
#define ON_ASSERT_OR_RETURN(cond,returncode) do{if (!(cond)) {ON_ErrorEx(__FILE__,__LINE__,OPENNURBS__FUNCTION__, #cond " is false");return(returncode);}}while(0)
#define ON_ASSERT_OR_RETURNVOID(cond) do{if (!(cond)) {ON_ErrorEx(__FILE__,__LINE__,OPENNURBS__FUNCTION__, #cond " is false");return;}}while(0)
// Do not use ON_ASSERT. If a condition can be checked by ON_ASSERT, then the
// code must be written detect and respond to that condition. This define will
// be deleted ASAP. It is being used to detect situations where a crash will
// occur and then letting the crash occur.
#define ON_ASSERT(cond) ON_REMOVE_ASAP_AssertEx(cond,__FILE__,__LINE__,OPENNURBS__FUNCTION__, #cond " is false")
ON_BEGIN_EXTERNC
/*
// All error/warning messages are sent to ON_ErrorMessage(). Replace the
// default handler (defined in opennurbs_error_message.cpp) with something
// that is appropriate for debugging your application.
*/
ON_DECL
void ON_ErrorMessage(
int, /* 0 = warning message, 1 = serious error message, 2 = assert failure */
const char*
);
/*
Returns:
Number of opennurbs errors since program started.
*/
ON_DECL
int ON_GetErrorCount(void);
/*
Returns:
Number of opennurbs warnings since program started.
*/
ON_DECL
int ON_GetWarningCount(void);
/*
Returns:
Number of math library or floating point errors that have
been handled since program started.
*/
ON_DECL
int ON_GetMathErrorCount(void);
ON_DECL
int ON_GetDebugErrorMessage(void);
ON_DECL
void ON_EnableDebugErrorMessage( int bEnableDebugErrorMessage );
ON_DECL
void ON_VARGS_FUNC_CDECL ON_Error(
const char* file_name, /* __FILE__ will do fine */
int line_number, /* __LINE__ will do fine */
const char* format, /* format string */
... /* format ags */
);
ON_DECL
void ON_VARGS_FUNC_CDECL ON_ErrorEx(
const char* file_name, /* __FILE__ will do fine */
int line_number, /* __LINE__ will do fine */
const char* function_name, /* OPENNURBS__FUNCTION__ will do fine */
const char* format, /* format string */
... /* format ags */
);
ON_DECL
void ON_VARGS_FUNC_CDECL ON_Warning(
const char* file_name, /* __FILE__ will do fine */
int line_number, /* __LINE__ will do fine */
const char* format, /* format string */
... /* format ags */
);
ON_DECL
void ON_VARGS_FUNC_CDECL ON_WarningEx(
const char* file_name, /* __FILE__ will do fine */
int line_number, /* __LINE__ will do fine */
const char* function_name, /*OPENNURBS__FUNCTION__ will do fine */
const char* format, /* format string */
... /* format ags */
);
// Ideally - these "assert" functions will be deleted when the SDK can be changed.
ON_DECL
void ON_VARGS_FUNC_CDECL ON_REMOVE_ASAP_AssertEx(
int, // if false, error is flagged
const char* file_name, /* __FILE__ will do fine */
int line_number, /* __LINE__ will do fine */
const char* function_name, /* OPENNURBS__FUNCTION__ will do fine */
const char* format, /* format string */
... /* format ags */
);
ON_DECL
void ON_MathError(
const char*, /* sModuleName */
const char*, /* sErrorType */
const char* /* sFunctionName */
);
ON_END_EXTERNC
#if defined(ON_CPLUSPLUS)
class ON_CLASS ON_ErrorEvent
{
public:
enum class Type : unsigned char
{
Unset = 0,
Warning = 1, // call to ON_WARNING / ON_Warning / ON_WarningEx
Error = 2, // call to ON_ERROR / ON_Error / ON_ErrorEx
Assert = 3, // ON_ASSERT (do not use ON_ASSERT - write code that handles errors and calls ON_ERROR)
Custom = 4,
SubDError = 5, // call to ON_SubDIncrementErrorCount()
BrepError = 6, // call to ON_BrepIncrementErrorCount()
NotValid = 7 // call to ON_IsNotValid()
};
static const char* TypeToString(
ON_ErrorEvent::Type event_type
);
const ON_String ToString() const;
public:
ON_ErrorEvent() = default;
~ON_ErrorEvent() = default;
ON_ErrorEvent(const ON_ErrorEvent&);
ON_ErrorEvent& operator=(const ON_ErrorEvent&);
ON_ErrorEvent(
ON_ErrorEvent::Type event_type,
const char* file_name,
unsigned int line_number,
const char* function_name,
const char* description
);
static const ON_ErrorEvent Create(
ON_ErrorEvent::Type event_type,
const char* file_name,
unsigned int line_number,
const char* function_name,
const char* description
);
static const ON_ErrorEvent Unset;
const char* FileName() const;
const char* FunctionName() const;
const char* Description() const;
unsigned int LineNumber() const;
ON_ErrorEvent::Type EventType() const;
void Dump(
class ON_TextLog& text_log
) const;
private:
friend class ON_ErrorLog;
ON_ErrorEvent::Type m_event_type = ON_ErrorEvent::Type::Unset;
unsigned char m_reserved1 = 0;
unsigned short m_reserved2 = 0;
unsigned int m_line_number = 0;
const char* m_file_name = nullptr;
const char* m_function_name = nullptr;
const char* m_description = nullptr;
char m_buffer[128] = {};
void Internal_CopyFrom(const ON_ErrorEvent& src);
};
class ON_CLASS ON_ErrorLog
{
public:
enum : unsigned int
{
MaximumEventCount = 32
};
public:
ON_ErrorLog() = default;
virtual ~ON_ErrorLog();
ON_ErrorLog(const ON_ErrorLog&) = default;
ON_ErrorLog& operator=(const ON_ErrorLog&) = default;
/*
Parameters:
error_event - [in]
event to add
Returns:
0: Event not added because maximum capacity reached.
>0: Number of events after adding error_event.
*/
virtual
unsigned int Append(
const ON_ErrorEvent& error_event
);
/*
Returns:
Total number of error events.
*/
unsigned int Count() const;
/*
Parameters:
i - [in]
zero based event index.
Returns
Event at specified index or ON_ErrorEvent::Unset if the index is out of range.
*/
const ON_ErrorEvent& Event(unsigned int i) const;
void Clear();
/*
Returns:
True if up to ON_ErrorLog::MaximumErrorCount error events will be saved in this to this error log.
False if another error log is active.
*/
bool EnableLogging();
/*
Description:
Stop logging errors to this error log.
*/
void DisableLogging();
void Dump(
class ON_TextLog& text_log
) const;
protected:
unsigned int m_event_count = 0;
ON_ErrorEvent m_events[ON_ErrorLog::MaximumEventCount];
};
#endif
#endif
@@ -0,0 +1,461 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(ON_EVALUATE_NURBS_INC_)
#define ON_EVALUATE_NURBS_INC_
ON_DECL
bool ON_IncreaseBezierDegree(
int, // dimension
bool, // true if Bezier is rational
int, // order (>=2)
int, // cv_stride (>=dim+1)
double* // cv[(order+1)*cv_stride] array
);
ON_DECL
bool ON_RemoveBezierSingAt0( // input bezier is rational with 0/0 at start
int, // dimension
int, // order (>=2)
int, // cv_stride (>=dim+1)
double* // cv[order*cv_stride] array
);
ON_DECL
bool ON_RemoveBezierSingAt1( // input bezier is rational with 0/0 at end
int, // dimension
int, // order (>=2)
int, // cv_stride (>=dim+1)
double* // cv[order*cv_stride] array
);
ON_DECL
double ON_EvaluateBernsteinBasis( // returns (i choose d)*(1-t)^(d-i)*t^i
int, // degree,
int, // 0 <= i <= degree
double // t
);
ON_DECL
void ON_EvaluatedeCasteljau(
int, // dim
int, // order
int, // side <= 0 return left side of bezier in cv array
// > 0 return right side of bezier in cv array
int, // cv_stride
double*, // cv
double // t 0 <= t <= 1
);
ON_DECL
bool ON_EvaluateBezier(
int, // dimension
bool, // true if Bezier is rational
int, // order (>=2)
int, // cv_stride >= (is_rat)?dim+1:dim
const double*, // cv[order*cv_stride] array
double, double, // t0,t1 = domain of bezier
int, // number of derivatives to compute (>=0)
double, // evaluation parameter
int, // v_stride (>=dimension)
double* // v[(der_count+1)*v_stride] array
);
/*
Description:
Evaluate B-spline basis functions
Parameters:
order - [in]
order >= 1
d = degree = order - 1
knot - [in]
array of length 2*d.
Generally, knot[0] <= ... <= knot[d-1] < knot[d] <= ... <= knot[2*d-1].
These are the knots that are active for the span being evaluated.
t - [in]
Evaluation parameter.
Typically knot[d-1] <= t <= knot[d].
In general t may be outside the interval knot[d-1],knot[d]. This can happen
when some type of extrapolation is being used and is almost always a bad
idea in practical situations.
N - [out]
double array with capacity order*order.
The returned values are:
If "N" were declared as double N[order][order], then
k
N[d-k][i] = N (t) = value of i-th degree k basis function at t.
i
where 0 <= k <= d and k <= i <= d.
In particular, N[0], ..., N[d] - values of degree d basis functions.
The "lower left" triangle is not initialized.
Actually, the above is true when knot[d-1] <= t < knot[d]. Otherwise, the
value returned is the value of the polynomial that agrees with N_i^k on the
half open domain [ knot[d-1], knot[d] )
COMMENTS:
If a degree d NURBS has n control points, then the OpenNURBS knot vector
for the entire NURBS curve has length d+n-1. The knot[] paramter to this
function points to the 2*d knots active for the span being evaluated.
Most literature, including DeBoor and The NURBS Book,
duplicate the Opennurbs start and end knot values and have knot vectors
of length d+n+1. The extra two knot values are completely superfluous
when degree >= 1.
Assume C is a B-spline of degree d (order=d+1) with n control vertices
(n>=d+1) and knot[] is its knot vector. Then
C(t) = Sum( 0 <= i < n, N_{i}(t) * C_{i} )
where N_{i} are the degree d b-spline basis functions and C_{i} are the control
vertices. The knot[] array length d+n-1 and satisfies
knot[0] <= ... <= knot[d-1] < knot[d]
knot[n-2] < knot[n-1] <= ... <= knot[n+d-2]
knot[i] < knot[d+i] for 0 <= i < n-1
knot[i] <= knot[i+1] for 0 <= i < n+d-2
The domain of C is [ knot[d-1], knot[n-1] ].
The support of N_{i} is [ knot[i-1], knot[i+d] ).
If d-1 <= k < n-1 and knot[k] <= t < knot[k+1], then
N_{i}(t) = 0 if i <= k-d
= 0 if i >= k+2
= B[i-k+d-1] if k-d+1 <= i <= k+1, where B[] is computed by the call
ON_EvaluateNurbsBasis( d+1, knot+k-d+1, t, B );
If 0 <= j < n-d, 0 <= m <= d, knot[j+d-1] <= t < knot[j+d], and B[] is
computed by the call
ON_EvaluateNurbsBasis( d+1, knot+j, t, B ),
then
N_{j+m}(t) = B[m].
*/
ON_DECL
bool ON_EvaluateNurbsBasis(
int order,
const double* knot,
double t,
double* N
);
/*
Description:
Calculate derivatives of B-spline basis functions.
INPUT:
order - [in]
order >= 1
d = degree = order - 1
knot - [in]
array of length 2*d.
Generally, knot[0] <= ... <= knot[d-1] < knot[d] <= ... <= knot[2*d-1].
These are the knots that are active for the span being evaluated.
der_count - [in]
1 <= der_count < order
Number of derivatives.
Note all B-spline basis derivatives with der_coutn >= order are identically zero.
N - [in]
The input value of N[] should be the results of the call
ON_EvaluateNurbsBasis( order, knot, t, N );
N - [out]
If "N" were declared as double N[order][order], then
d
N[d-k][i] = k-th derivative of N (t)
i
where 0 <= k <= d and 0 <= i <= d.
In particular,
N[0], ..., N[d] - values of degree d basis functions.
N[order], ..., N[order_d] - values of first derivative.
*/
ON_DECL
bool ON_EvaluateNurbsBasisDerivatives(
int order,
const double* knot,
int der_count,
double* N
);
/*
Description:
Evaluate a NURBS curve span.
Parameters:
dim - [in]
dimension (> 0).
is_rat - [in]
true or false.
order - [in]
order=degree+1 (order>=2)
knot - [in] NURBS knot vector.
NURBS knot vector with 2*(order-1) knots, knot[order-2] != knot[order-1]
cv_stride - [in]
cv - [in]
For 0 <= i < order the i-th control vertex is
cv[n],...,cv[n+(is_rat?dim:dim+1)],
where n = i*cv_stride. If is_rat is true the cv is
in homogeneous form.
der_count - [in]
number of derivatives to evaluate (>=0)
t - [in]
evaluation parameter
v_stride - [in]
v - [out]
An array of length v_stride*(der_count+1). The evaluation
results are returned in this array.
P = v[0],...,v[m_dim-1]
Dt = v[v_stride],...
Dtt = v[2*v_stride],...
...
In general, Dt^i returned in v[n],...,v[n+m_dim-1], where
n = v_stride*i.
Returns:
True if successful.
See Also:
ON_NurbsCurve::Evaluate
ON_EvaluateNurbsSurfaceSpan
ON_EvaluateNurbsCageSpan
*/
ON_DECL
bool ON_EvaluateNurbsSpan(
int dim,
bool is_rat,
int order,
const double* knot,
int cv_stride,
const double* cv,
int der_count,
double t,
int v_stride,
double* v
);
/*
Description:
Evaluate a NURBS surface bispan.
Parameters:
dim - [in] >0
is_rat - [in] true of false
order0 - [in] >= 2
order1 - [in] >= 2
knot0 - [in]
NURBS knot vector with 2*(order0-1) knots, knot0[order0-2] != knot0[order0-1]
knot1 - [in]
NURBS knot vector with 2*(order1-1) knots, knot1[order1-2] != knot1[order1-1]
cv_stride0 - [in]
cv_stride1 - [in]
cv - [in]
For 0 <= i < order0 and 0 <= j < order1, the (i,j) control vertex is
cv[n],...,cv[n+(is_rat?dim:dim+1)],
where n = i*cv_stride0 + j*cv_stride1. If is_rat is true the cv is
in homogeneous form.
der_count - [in] (>=0)
s - [in]
t - [in] (s,t) is the evaluation parameter
v_stride - [in] (>=dim)
v - [out] An array of length v_stride*(der_count+1)*(der_count+2)/2.
The evaluation results are stored in this array.
P = v[0],...,v[m_dim-1]
Ds = v[v_stride],...
Dt = v[2*v_stride],...
Dss = v[3*v_stride],...
Dst = v[4*v_stride],...
Dtt = v[5*v_stride],...
In general, Ds^i Dt^j is returned in v[n],...,v[n+m_dim-1], where
n = v_stride*( (i+j)*(i+j+1)/2 + j).
Returns:
True if succcessful.
See Also:
ON_NurbsSurface::Evaluate
ON_EvaluateNurbsSpan
ON_EvaluateNurbsCageSpan
*/
ON_DECL
bool ON_EvaluateNurbsSurfaceSpan(
int dim,
bool is_rat,
int order0,
int order1,
const double* knot0,
const double* knot1,
int cv_stride0,
int cv_stride1,
const double* cv,
int der_count,
double s,
double t,
int v_stride,
double* v
);
/*
Description:
Evaluate a NURBS cage trispan.
Parameters:
dim - [in] >0
is_rat - [in] true of false
order0 - [in] >= 2
order1 - [in] >= 2
order2 - [in] >= 2
knot0 - [in]
NURBS knot vector with 2*(order0-1) knots, knot0[order0-2] != knot0[order0-1]
knot1 - [in]
NURBS knot vector with 2*(order1-1) knots, knot1[order1-2] != knot1[order1-1]
knot2 - [in]
NURBS knot vector with 2*(order1-1) knots, knot2[order2-2] != knot2[order2-1]
cv_stride0 - [in]
cv_stride1 - [in]
cv_stride2 - [in]
cv - [in]
For 0 <= i < order0, 0 <= j < order1, and 0 <= k < order2,
the (i,j,k)-th control vertex is
cv[n],...,cv[n+(is_rat?dim:dim+1)],
where n = i*cv_stride0 + j*cv_stride1 *k*cv_stride2.
If is_rat is true the cv is in homogeneous form.
der_count - [in] (>=0)
r - [in]
s - [in]
t - [in] (r,s,t) is the evaluation parameter
v_stride - [in] (>=dim)
v - [out] An array of length v_stride*(der_count+1)*(der_count+2)*(der_count+3)/6.
The evaluation results are stored in this array.
P = v[0],...,v[m_dim-1]
Dr = v[v_stride],...
Ds = v[2*v_stride],...
Dt = v[3*v_stride],...
Drr = v[4*v_stride],...
Drs = v[5*v_stride],...
Drt = v[6*v_stride],...
Dss = v[7*v_stride],...
Dst = v[8*v_stride],...
Dtt = v[9*v_stride],...
In general, Dr^i Ds^j Dt^k is returned in v[n],...,v[n+dim-1], where
d = (i+j+k)
n = v_stride*( d*(d+1)*(d+2)/6 + (j+k)*(j+k+1)/2 + k)
Returns:
True if succcessful.
See Also:
ON_NurbsCage::Evaluate
ON_EvaluateNurbsSpan
ON_EvaluateNurbsSurfaceSpan
*/
ON_DECL
bool ON_EvaluateNurbsCageSpan(
int dim,
bool is_rat,
int order0, int order1, int order2,
const double* knot0,
const double* knot1,
const double* knot2,
int cv_stride0, int cv_stride1, int cv_stride2,
const double* cv,
int der_count,
double t0, double t1, double t2,
int v_stride,
double* v
);
ON_DECL
bool ON_EvaluateNurbsDeBoor( // for expert users only - no support available
int, // cv_dim ( dim+1 for rational cvs )
int, // order (>=2)
int, // cv_stride (>=cv_dim)
double*, // cv array - values changed to result of applying De Boor's algorithm
const double*, // knot array
int, // side,
// -1 return left side of B-spline span in cv array
// +1 return right side of B-spline span in cv array
// -2 return left side of B-spline span in cv array
// Ignore values of knots[0,...,order-3] and assume
// left end of span has a fully multiple knot with
// value "mult_k".
// +2 return right side of B-spline span in cv array
// Ignore values of knots[order,...,2*order-2] and
// assume right end of span has a fully multiple
// knot with value "mult_k".
double, // mult_k - used when side is +2 or -2. See above for usage.
double // t
// If side < 0, then the cv's for the portion of the NURB span to
// the LEFT of t are computed. If side > 0, then the cv's for the
// portion the span to the RIGHT of t are computed. The following
// table summarizes the restrictions on t:
//
// value of side condition t must satisfy
// -2 mult_k < t and mult_k < knots[order-1]
// -1 knots[order-2] < t
// +1 t < knots[order-1]
// +2 t < mult_k and knots[order-2] < mult_k
);
ON_DECL
bool ON_EvaluateNurbsBlossom(int, // cvdim,
int, // order,
int, // cv_stride,
const double*, //CV, size cv_stride*order
const double*, //knot, nondecreasing, size 2*(order-1)
// knot[order-2] != knot[order-1]
const double*, //t, input parameters size order-1
double* // P
// DeBoor algorithm with different input at each step.
// returns false for bad input.
);
ON_DECL
void ON_ConvertNurbSpanToBezier(
int, // cvdim (dim+1 for rational curves)
int, // order,
int, // cvstride (>=cvdim)
double*, // cv array - input has NURBS cvs, output has Bezier cvs
const double*, // (2*order-2) knots for the NURBS span
double, // t0, NURBS span parameter of start point
double // t1, NURBS span parameter of end point
);
#endif
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+122
View File
@@ -0,0 +1,122 @@
/*
//
// Copyright (c) 1993-2017 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_FREETYPE_INC_)
#define OPENNURBS_FREETYPE_INC_
#if defined(OPENNURBS_FREETYPE_SUPPORT)
// Look in opennurbs_system_rumtime.h for the correct place to define OPENNURBS_FREETYPE_SUPPORT.
// Do NOT define OPENNURBS_FREETYPE_SUPPORT here or in your project setting ("makefile").
#if defined(ON_COMPILER_MSC) ||defined(ON_RUNTIME_WIN)
#error FreeType is not used in Windows. It does not work as well as DirectWrite based tools.
#endif
#if defined(ON_RUNTIME_APPLE)
// Freetype is used to get single stroke font outlines.
// For everything else, use the CTFont based tools.
//#error FreeType is not used in MacOS and iOS builds. It does not work as well as CTFont based code.
#endif
/*
Returns:
Units per em in font design units.
*/
ON_DECL
unsigned int ON_FreeTypeGetFontUnitsPerM(
const class ON_Font* font
);
/*
Parameters:
font_unit_font_metrics - [in]
metrics in font units (freetype face loaded with FT_LOAD_NO_SCALE) unless
it is a "tricky" font.
*/
ON_DECL
void ON_FreeTypeGetFontMetrics(
const class ON_Font* font,
class ON_FontMetrics& font_unit_font_metrics
);
/*
Parameters:
glyph_box - [out]
glyph metrics infont units (freetype face loaded with FT_LOAD_NO_SCALE) unless
it is a "tricky" font.
Returns:
0 if box was not set.
>0: font glyph index (or other non-zero value) when box is set
*/
ON_DECL
unsigned int ON_FreeTypeGetGlyphMetrics(
const class ON_FontGlyph* glyph,
class ON_TextBox& glyph_metrics_in_font_design_units
);
/*
Parameters:
glyph - [in]
bSingleStrokeFont - [in]
outline - [out]
outline and metrics in font design units
*/
ON_DECL
bool ON_FreeTypeGetGlyphOutline(
const class ON_FontGlyph* glyph,
ON_OutlineFigure::Type figure_type,
class ON_Outline& outline
);
/*
Parameters:
glyph - [in]
glyph_index - [in]
If known for certain, pass in the glyph index. If not known, pass in 0.
figure_type - [in]
If known for certain, pass in figure_type. Otherwise, pass in ON_OutlineFigure::Type::Unset.
outline - [out]
outline and metrics in font design units
*/
ON_DECL
bool ON_FreeTypeGetGlyphOutline(
const class ON_FontGlyph* glyph,
unsigned int glyph_index,
ON_OutlineFigure::Type figure_type,
class ON_Outline& outline
);
/*
Description:
A wrapper for calculating parameters and calling FreeType library
functions FT_Set_Char_Size() FT_Load_Glyph().
Parameters:
ft_face - [in]
A pointer to and FT_Face. One way to get this value is to call ON_Font::FreeTypeFace()
font_glyph_id - [in]
font glyph id
Returns:
True if glyph is available and loaded.
*/
ON_DECL
bool ON_FreeTypeLoadGlyph(
ON__UINT_PTR ft_face,
unsigned int font_glyph_index,
bool bLoadRenderBitmap
);
#endif
#endif
@@ -0,0 +1,293 @@
/*
//
// Copyright (c) 1993-2017 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
// opennurbs uses FreeType to calculate font metric, glyph metric, and glyph outline information.
// FreeType Licensing:
//
//// Retrieved March 22, 2017
//// https://www.freetype.org/freetype2/docs/index.html
////What is FreeType?
////
////FreeType is a software font engine that is designed to be small, efficient,
////highly customizable, and portable while capable of producing high-quality
////output (glyph images). It can be used in graphics libraries, display servers,
////font conversion tools, text image generation tools, and many other products as well.
////
////Note that FreeType is a font service and doesn't provide APIs to perform
////higher-level features like text layout or graphics processing
////(e.g., colored text rendering, hollowing, etc.). However, it greatly
////simplifies these tasks by providing a simple, easy to use, and uniform
////interface to access the content of font files.
////
////FreeType is released under two open-source licenses: our own BSD-like
////FreeType License and the GNU Public License, Version 2. It can thus
////be used by any kind of projects, be they proprietary or not.
////
////Please note that FreeType is also called FreeType 2, to
////distinguish it from the old, deprecated FreeType 1 library,
////a predecessor no longer maintained and supported.
////
//// http://git.savannah.gnu.org/cgit/freetype/freetype2.git/tree/docs/FTL.TXT
////
//// The FreeType Project LICENSE
//// ----------------------------
////
//// 2006-Jan-27
////
//// Copyright 1996-2002, 2006 by
//// David Turner, Robert Wilhelm, and Werner Lemberg
////
////
////
////Introduction
////============
////
//// The FreeType Project is distributed in several archive packages;
//// some of them may contain, in addition to the FreeType font engine,
//// various tools and contributions which rely on, or relate to, the
//// FreeType Project.
////
//// This license applies to all files found in such packages, and
//// which do not fall under their own explicit license. The license
//// affects thus the FreeType font engine, the test programs,
//// documentation and makefiles, at the very least.
////
//// This license was inspired by the BSD, Artistic, and IJG
//// (Independent JPEG Group) licenses, which all encourage inclusion
//// and use of free software in commercial and freeware products
//// alike. As a consequence, its main points are that:
////
//// o We don't promise that this software works. However, we will be
//// interested in any kind of bug reports. (`as is' distribution)
////
//// o You can use this software for whatever you want, in parts or
//// full form, without having to pay us. (`royalty-free' usage)
////
//// o You may not pretend that you wrote this software. If you use
//// it, or only parts of it, in a program, you must acknowledge
//// somewhere in your documentation that you have used the
//// FreeType code. (`credits')
////
//// We specifically permit and encourage the inclusion of this
//// software, with or without modifications, in commercial products.
//// We disclaim all warranties covering The FreeType Project and
//// assume no liability related to The FreeType Project.
////
////
//// Finally, many people asked us for a preferred form for a
//// credit/disclaimer to use in compliance with this license. We thus
//// encourage you to use the following text:
////
//// """
//// Portions of this software are copyright © <year> The FreeType
//// Project (www.freetype.org). All rights reserved.
//// """
////
//// Please replace <year> with the value from the FreeType version you
//// actually use.
////
////
////Legal Terms
////===========
////
////0. Definitions
////--------------
////
//// Throughout this license, the terms `package', `FreeType Project',
//// and `FreeType archive' refer to the set of files originally
//// distributed by the authors (David Turner, Robert Wilhelm, and
//// Werner Lemberg) as the `FreeType Project', be they named as alpha,
//// beta or final release.
////
//// `You' refers to the licensee, or person using the project, where
//// `using' is a generic term including compiling the project's source
//// code as well as linking it to form a `program' or `executable'.
//// This program is referred to as `a program using the FreeType
//// engine'.
////
//// This license applies to all files distributed in the original
//// FreeType Project, including all source code, binaries and
//// documentation, unless otherwise stated in the file in its
//// original, unmodified form as distributed in the original archive.
//// If you are unsure whether or not a particular file is covered by
//// this license, you must contact us to verify this.
////
//// The FreeType Project is copyright (C) 1996-2000 by David Turner,
//// Robert Wilhelm, and Werner Lemberg. All rights reserved except as
//// specified below.
////
////1. No Warranty
////--------------
////
//// THE FREETYPE PROJECT IS PROVIDED `AS IS' WITHOUT WARRANTY OF ANY
//// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
//// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//// PURPOSE. IN NO EVENT WILL ANY OF THE AUTHORS OR COPYRIGHT HOLDERS
//// BE LIABLE FOR ANY DAMAGES CAUSED BY THE USE OR THE INABILITY TO
//// USE, OF THE FREETYPE PROJECT.
////
////2. Redistribution
////-----------------
////
//// This license grants a worldwide, royalty-free, perpetual and
//// irrevocable right and license to use, execute, perform, compile,
//// display, copy, create derivative works of, distribute and
//// sublicense the FreeType Project (in both source and object code
//// forms) and derivative works thereof for any purpose; and to
//// authorize others to exercise some or all of the rights granted
//// herein, subject to the following conditions:
////
//// o Redistribution of source code must retain this license file
//// (`FTL.TXT') unaltered; any additions, deletions or changes to
//// the original files must be clearly indicated in accompanying
//// documentation. The copyright notices of the unaltered,
//// original files must be preserved in all copies of source
//// files.
////
//// o Redistribution in binary form must provide a disclaimer that
//// states that the software is based in part of the work of the
//// FreeType Team, in the distribution documentation. We also
//// encourage you to put an URL to the FreeType web page in your
//// documentation, though this isn't mandatory.
////
//// These conditions apply to any software derived from or based on
//// the FreeType Project, not just the unmodified files. If you use
//// our work, you must acknowledge us. However, no fee need be paid
//// to us.
////
////3. Advertising
////--------------
////
//// Neither the FreeType authors and contributors nor you shall use
//// the name of the other for commercial, advertising, or promotional
//// purposes without specific prior written permission.
////
//// We suggest, but do not require, that you use one or more of the
//// following phrases to refer to this software in your documentation
//// or advertising materials: `FreeType Project', `FreeType Engine',
//// `FreeType library', or `FreeType Distribution'.
////
//// As you have not signed this license, you are not required to
//// accept it. However, as the FreeType Project is copyrighted
//// material, only this license, or another one contracted with the
//// authors, grants you the right to use, distribute, and modify it.
//// Therefore, by using, distributing, or modifying the FreeType
//// Project, you indicate that you understand and accept all the terms
//// of this license.
////
////4. Contacts
////-----------
////
//// There are two mailing lists related to FreeType:
////
//// o freetype@nongnu.org
////
//// Discusses general use and applications of FreeType, as well as
//// future and wanted additions to the library and distribution.
//// If you are looking for support, start in this list if you
//// haven't found anything to help you in the documentation.
////
//// o freetype-devel@nongnu.org
////
//// Discusses bugs, as well as engine internals, design issues,
//// specific licenses, porting, etc.
////
//// Our home page can be found at
////
//// http://www.freetype.org
////
////--- end of FTL.TXT ---
#if !defined(OPENNURBS_FREETYPE_INCLUDE_INC_)
#define OPENNURBS_FREETYPE_INCLUDE_INC_
// NOTE:
// This header file is not included in opennurbs.h because
// FreeType 2.6.3 has deeply nested includes and uses angle brackets
// in its include files (instead of double quotes and relative paths like opennurbs),
// the directory ./freetype263/include must be in the "system" includes path.
// It is not feasable or reasonable for all projects that include opennurbs.h to have the
// freetype includes directory in the system includes path.
#if defined(OPENNURBS_FREETYPE_SUPPORT)
// Look in opennurbs_system_rumtime.h for the correct place to define OPENNURBS_FREETYPE_SUPPORT.
// Do NOT define OPENNURBS_FREETYPE_SUPPORT here or in your project setting ("makefile").
// Angle brackets are used on #include <ft2build.h> because if it fails,
// the following #include FT_FREETYPE_H will fail, but in more mysterious ways.
#if defined(OPENNURBS_EXPORTS) || defined(OPENNURBS_IMPORTS)
// WHen opennurbs is a DLL, freetype is linked as a DLL
#if defined(ON_COMPILER_MSC)
/* Windows DLL */
#define OPENNURBS_FREETYPE_DECL __declspec(dllimport)
#elif defined(ON_COMPILER_CLANG)
/* Apple shared library */
#define OPENNURBS_FREETYPE_DECL __attribute__ ((visibility ("default")))
#endif
#endif
#pragma ON_PRAGMA_WARNING_BEFORE_DIRTY_INCLUDE
// Angle brackets must be used in the ft2build.h include because
// that's what the freetype defined includes like FT_FREETYPE_H
// use and they must work. If you get a compiler (CLang) error telling you
// to use "quotes" instead,
// ignore it and include the freetype directory in the header search
// path for opennurbs_freetype.cpp.
#include <ft2build.h>
#include FT_FREETYPE_H
#pragma ON_PRAGMA_WARNING_AFTER_DIRTY_INCLUDE
#if defined(ON_COMPILER_MSC)
#if !defined(OPENNURBS_FREETYPE_LIB_DIR)
#include "opennurbs_input_libsdir.h"
#if defined(OPENNURBS_INPUT_LIBS_DIR)
// Typically, OPENNURBS_LIB_DIR is defined in opennurbs_msbuild.Cpp.props
#define OPENNURBS_FREETYPE_LIB_DIR OPENNURBS_INPUT_LIBS_DIR
#else
// Define OPENNURBS_FREETYPE_LIB_DIR to be the directory containing freetype263.lib
#error You must define OPENNURBS_FREETYPE_LIB_DIR
#endif
#endif
#if defined(_LIB) && !defined(OPENNURBS_IMPORTS) && !defined(OPENNURBS_EXPORTS)
// Microsoft static library
#if defined(_MT) && !defined(_DLL)
// Microsoft dynamic library freetype263_mt.lib used multithreaded static C-runtime
#pragma message ( "Linking with freetype263_mt.lib in " OPENNURBS_PP2STR(OPENNURBS_FREETYPE_LIB_DIR) )
#pragma comment(lib, "\"" OPENNURBS_FREETYPE_LIB_DIR "/" "freetype263_mt.lib" "\"")
#else
// Microsoft dynamic library freetype263_staticlib.lib uses DLL C-runtime
#pragma message ( "Linking with freetype263_staticlib.lib in " OPENNURBS_PP2STR(OPENNURBS_FREETYPE_LIB_DIR) )
#pragma comment(lib, "\"" OPENNURBS_FREETYPE_LIB_DIR "/" "freetype263_staticlib.lib" "\"")
#endif
#else
// Microsoft dynamic library freetype263.lib + freetype263.dll
#pragma message ( "Linking with freetype263.lib in " OPENNURBS_PP2STR(OPENNURBS_FREETYPE_LIB_DIR) )
#pragma comment(lib, "\"" OPENNURBS_FREETYPE_LIB_DIR "/" "freetype263.lib" "\"")
#endif
#endif
#endif
#endif
+920
View File
@@ -0,0 +1,920 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_FSP_INC_)
#define OPENNURBS_FSP_INC_
class ON_CLASS ON_FixedSizePoolElement
{
private:
// ON_FixedSizePoolElement is never instantiated
ON_FixedSizePoolElement() = delete;
~ON_FixedSizePoolElement() = delete;
ON_FixedSizePoolElement(const ON_FixedSizePoolElement&) = delete;
ON_FixedSizePoolElement operator=(const ON_FixedSizePoolElement&) = delete;
public:
// next element - intentionally not initialized because instantiation is not permitted.
ON_FixedSizePoolElement* m_next;
};
class ON_CLASS ON_FixedSizePool
{
public:
ON_FixedSizePool();
~ON_FixedSizePool();
#if defined(ON_HAS_RVALUEREF)
ON_FixedSizePool(ON_FixedSizePool&&);
ON_FixedSizePool& operator=(ON_FixedSizePool&&);
#endif
/*
Description:
Create a fixed size memory pool.
Parameters:
sizeof_element - [in]
number of bytes in each element. This parameter must be greater than zero.
In general, use sizeof(element type). If you pass a "raw" number as
sizeof_element, then be certain that it is the right size to insure the
fields in your elements will be properly aligned.
Remarks:
You must call Create() on an unused ON_FixedSizePool or call Destroy()
before calling create.
Returns:
True if successful and the pool can be used.
See Also
CreateForExperts().
*/
bool Create(
size_t sizeof_element
);
/*
Description:
Create a fixed size memory pool.
If you have a decent estimate of how many elements you need,
CreateForExperts() is a typically a better choice.
Otherwise, Create(sizeof_element) is typically the best option.
Parameters:
sizeof_element - [in]
number of bytes in each element. This parameter must be greater than zero.
In general, use sizeof(element type). If you pass a "raw" number as
sizeof_element, then be certain that it is the right size to insure the
fields in your elements will be properly aligned.
element_count_estimate - [in] (0 = good default)
If you know how many elements you will need, pass that number here.
It is better to slightly overestimate than to slightly underestimate.
If you do not have a good estimate, then use zero.
block_element_capacity - [in] (0 = good default)
If block_element_capacity is zero, Create() will calculate a block
size that is efficent for most applications. If you are an expert
user and want to specify the number of elements per block,
then pass the number of elements per block here. When
block_element_capacity > 0 and element_count_estimate > 0, the first
block will have a capacity of at least element_count_estimate; in this
case do not ask for extraordinarly large amounts of contiguous heap.
Remarks:
You must call Create() on an unused ON_FixedSizePool or call Destroy()
before calling create.
Returns:
True if successful and the pool can be used.
*/
bool Create(
size_t sizeof_element,
size_t element_count_estimate,
size_t block_element_capacity
);
/*
Description:
Create a fixed size memory pool.
Parameters:
sizeof_element - [in]
number of bytes in each element. This parameter must be greater than zero.
In general, use sizeof(element type). If you pass a "raw" number as
sizeof_element, then be certain that it is the right size to insure the
fields in your elements will be properly aligned.
maximum_element_count_estimate - [in] (0 = good default)
If you have a tight upper bound on the number of elements you need
from this fixed size pool, call Create(sizeof_element) instead.
If the description of this parameter is confusing to you,
call Create(sizeof_element) instead.
If you have a tight upper bound on how many elements you will need,
pass that number here. When maximum_element_count_estimate > 0, the
initial memory blocks in the fixed size pool will be sized to efficiently
deliver maximum_element_count_estimate elements.
The fixed block pool can become inefficient when maximum_element_count_estimate
is a gross overestimate or a slight underestimate of the actual number of
elements that get allocated.
minimum_block2_element_capacity - [in] (0 = good default)
If the description below is confusing, pass 0.
If maximum_element_count_estimate = 0, this parameter is ignored.
If maximum_element_count_estimate > 0 and you have an excellent choice
for a lower bound on the number of elements per block for unexpected allocations
of more than maximum_element_count_estimate elements, then pass that value for
minimum_block2_element_capacity.
Remarks:
You must call Create() or CreateEx() on an unused ON_FixedSizePool or call Destroy()
before calling create.
Returns:
True if successful and the pool can be used.
*/
bool CreateForExperts(
size_t sizeof_element,
size_t maximum_element_count_estimate,
size_t minimum_block2_element_capacity
);
static size_t DefaultElementCapacityFromSizeOfElement(size_t sizeof_element);
/*
Description:
Tool for debugging pool use when tuning block size and block capacity.
Returns:
Total operating system heap memory (in bytes) used by this ON_FixedSizePool.
Remarks:
SizeOfPool() = SizeOfAllocatedElements() + SizeOfUnusedElements().
*/
size_t SizeOfPool() const;
/*
Description:
Tool for debugging pool use when tuning block size and block capacity.
Returns:
Operating system heap memory (in bytes) that are used by active pool elements.
Remarks:
SizeOfPool() = SizeOfActiveElements() + SizeOfUnusedElements().
*/
size_t SizeOfActiveElements() const;
/*
Description:
Tool for debugging pool use when tuning block size and block capacity.
Returns:
Operating system heap memory (in bytes) that has been reserved but is not
currently used by active elements.
Remarks:
SizeOfPool() = SizeOfActiveElements() + SizeOfUnusedElements().
*/
size_t SizeOfUnusedElements() const;
/*
Returns:
Size of the elements in this pool.
*/
size_t SizeofElement() const;
/*
Returns:
A pointer to sizeof_element bytes. The memory is zeroed.
Remarks:
If multiple threads are using this pool, then use ThreadSafeAllocateElement().
*/
void* AllocateElement();
/*
Returns:
A pointer to sizeof_element bytes. The values in the returned block are undefined.
Remarks:
If multiple threads are using this pool, then use ThreadSafeAllocateDirtyElement().
*/
void* AllocateDirtyElement();
/*
Description:
Return an element to the pool.
Parameters:
p - [in]
A pointer returned by AllocateElement().
It is critical that p be from this pool and that
you return a pointer no more than one time.
Remarks:
If multiple threads are using this pool, then use ThreadSafeReturnElement().
If you find the following remarks confusing, but you really want to use
ReturnElement(), then here are some simple guidelines.
1) SizeofElement() must be >= 16
2) SizeofElement() must be a multiple of 8.
3) Do not use FirstElement() and NextElement() to iterate through
the pool.
If 1 to 3 don't work for you, then you need to understand the following
information before using ReturnElement().
ON_FixedMemoryPool uses the first sizeof(void*) bytes of the
returned element for bookkeeping purposes. Therefore, if you
are going to use ReturnElement(), then SizeofElement() must be
at least sizeof(void*). If you are using a platform that requires
pointers to be aligned on sizeof(void*) boundaries, then
SizeofElement() must be a multiple of sizeof(void*).
If you are going to use ReturnElement() and then use FirstElement()
and NextElement() to iterate through the list of elements, then you
need to set a value in the returned element to indicate that it
needs to be skipped during the iteration. This value cannot be
located in the fist sizeof(void*) bytes of the element. If the
element is a class with a vtable, you cannot call a virtual
function on a returned element because the vtable pointer is
trashed when ReturnElement() modifies the fist sizeof(void*) bytes.
*/
void ReturnElement(void* p);
/*
Description:
Thread safe version of AllocateElement().
Returns:
A pointer to sizeof_element bytes. The memory is zeroed.
*/
void* ThreadSafeAllocateElement();
/*
Description:
Thread safe version of AllocateDirtyElement().
Returns:
A pointer to sizeof_element bytes. The values in the returned block are undefined.
*/
void* ThreadSafeAllocateDirtyElement();
/*
Description:
Thread safe version of ReturnElement().
*/
void ThreadSafeReturnElement(void* p);
/*
Description:
Return all allocated elements to the pool. No heap is freed and
the pool remains initialized and ready for AllocateElement()
to be called.
*/
void ReturnAll();
/*
Description:
Destroy the pool and free all the heap. The pool cannot be used again
until Create() is called.
*/
void Destroy();
/*
Returns:
Number of active elements. (Elements that have been returned are not active.)
*/
size_t ActiveElementCount() const;
/*
Returns:
Total number of elements = number of active elements + number of returned elements.
*/
size_t TotalElementCount() const;
/*
Description:
Get the i-th elment in the fixed size pool.
Parameters:
element_index - [in]
Returns:
A pointer to the element with the specified index.
The first element has element_index = 0 and is the element
returned by the first call to AllocateElement().
The last element has element_index = ElementCount()-1.
If element_index is out of range, nullptr is returned.
Remarks:
It is faster to use ON_FixedSizePoolIterator.FirstElement() and
ON_FixedSizePoolIterator.NextElement() to iterate through the
entire list of elements. This function is relatively
efficient when there are a few large blocks in the pool
or element_index is small compared to the number of elements
in the first few blocks.
If ReturnElement() is not used or no AllocateElement() calls
are made after any use of ReturnElement(), then the i-th
element is the one returned by the (i+1)-th call to
AllocateElement()
*/
void* Element(
size_t element_index
) const;
/*
Description:
Get the fixed size pool index of an element.
Parameters:
element_pointer - [in]
Returns:
An index >= 0 and < ON_MAX_SIZE_T if the element_pointer
points to an element managed by the this fixed size pool.
ON_MAX_SIZE_T otherwise.
Remarks:
It is faster to use ON_FixedSizePoolIterator.FirstElement() and
ON_FixedSizePoolIterator.NextElement() to iterate through the
entire list of elements. This function is relatively
efficient when there are a few large blocks in the pool
or element_pointer is an element in the first few blocks.
If ReturnElement() is not used or no AllocateElement() calls
are made after any use of ReturnElement(), then the i-th
element is the one returned by the (i+1)-th call to
AllocateElement().
*/
size_t ElementIndex(
const void* element_pointer
) const;
/*
Parameters:
p - [in]
pointer to test
Returns:
True if p points to memory in this pool.
*/
bool InPool(
const void* pointer
) const;
/*
Description:
If you are certain that all elements in the pool (active and returned)
have an unsigned 32-bit id that is unique and increasing, then you may use
this function to find them.
Parameters:
id_offset - [in]
offset into the element where the id is stored.
id - [in]
id to search for
*/
void* ElementFromId(
size_t id_offset,
unsigned int id
) const;
/*
Description:
If you are certain that all elements in the pool (active and returned)
have an unsigned 32-bit id that is unique and increasing, then you may use
this function to find the maximum assigned id.
Parameters:
id_offset - [in]
offset into the element where the id is stored.
Returns:
maximum id in all elements (active and returned).
*/
unsigned int MaximumElementId(
size_t id_offset
) const;
bool ElementIdIsIncreasing(
size_t id_offset
) const;
/*
Returns:
If successful, (1 + maximum assigned id value) is returned.
Otherwise 0 is returned.
*/
unsigned int ResetElementId(
size_t id_offset,
unsigned int initial_id
);
public:
// Primarily used for debugging
bool IsValid() const;
private:
friend class ON_FixedSizePoolIterator;
void* m_first_block = nullptr;
// ReturnElement() adds to the m_al_element stack.
// AllocateElement() will use the stack before using m_al_element_array[]
void* m_al_element_stack = nullptr;
void* m_al_block = nullptr; // current element allocation block.
// m_al_element_array[] is in m_al_block and has length m_al_count.
void* m_al_element_array = nullptr;
size_t m_al_count = 0;
size_t m_sizeof_element = 0;
size_t m_block_element_count = 0; // block element count
//size_t m_active_element_count = 0; // number of active elements
//size_t m_total_element_count = 0; // total number of elements (active + returned)
unsigned int m_active_element_count = 0; // number of active elements
unsigned int m_total_element_count = 0; // total number of elements (active + returned)
private:
// Used by The ThreadSafe...() functions and for expert users
// to use when managing memory controlled by this pool. Best
// to ingnore this unless you have a very clear idea of what
// you are doing, why you are doing it, and when you are doing it.
// Otherwise, you'll find yourself waiting forever on a nested
// access request.
friend class ON_SleepLockGuard;
ON_SleepLock m_sleep_lock;
private:
unsigned int m_reserved0 = 0;
private:
// returns capacity of elements in existing block
size_t BlockElementCapacity( const void* block ) const;
// returns number of allocated of elements in existing block
size_t BlockElementCount( const void* block ) const;
private:
// prohibit copy construction and operator=.
ON_FixedSizePool(const ON_FixedSizePool&) = delete;
ON_FixedSizePool& operator=(const ON_FixedSizePool&) = delete;
};
class ON_CLASS ON_FixedSizePoolIterator
{
public:
ON_FixedSizePoolIterator();
ON_FixedSizePoolIterator( const class ON_FixedSizePool& fsp );
const class ON_FixedSizePool* FixedSizePool();
void Create(const ON_FixedSizePool* fsp);
/*
Description:
Get the first element when iterating through the list of elements.
Parameters:
element_index - [in]
If you use the version of FirstElement() that has an
element_index parameter, then the iteration begins at
that element.
Example:
The loop will iteratate through all the elements returned from
AllocateElement(), including any that have be returned to the pool
using ReturnElement().
// iterate through all elements in the pool
// This iteration will go through TotalElements() items.
for ( void* p = FirstElement(); 0 != p; p = NextElement() )
{
// If you are not using ReturnElement(), then you may process
// "p" immediately. If you have used ReturnElement(), then you
// must check some value in p located after the first sizeof(void*)
// bytes to see if p is active.
if ( p is not active )
continue;
... process p
}
Returns:
The first element when iterating through the list of elements.
Remarks:
FirstElement() and NextElement() will return elements that have
been returned to the pool using ReturnElement(). If you use
ReturnElement(), then be sure to mark the element so it can be
identified and skipped.
Do not make any calls to FirstBlock() or NextBlock() when using
FirstElement() and NextElement() to iteratate through elements.
*/
void* FirstElement();
void* FirstElement( size_t element_index );
/*
Description:
Get the next element when iterating through the list of elements.
If FirstElement() is not called, then the first call to
NextElement() returns the first element.
Example:
See the FirstElement() documentation.
Returns:
The next element when iterating through the list of elements.
Remarks:
FirstElement() and NextElement() will return elements that have
been returned to the pool using ReturnElement(). If you use
ReturnElement(), then be sure to mark the element so it can be
identified and skipped.
Do not make any calls to FirstBlock() or NextBlock() when using
FirstElement() and NextElement() to iteratate through elements.
*/
void* NextElement();
/*
Returns:
The most recently returned value from a call to FirstElement()
or NextElement().
Remarks:
Do not make any calls to FirstBlock() or NextBlock() when using
FirstElement() and NextElement() to iteratate through elements.
*/
void* CurrentElement() const;
/*
Description:
Sets the state of the iterator to the initial state that
exists after construction. This is useful if the iterator
has been used the get one or more elements and then
the referenced fixed size pool is modified or code wants
to begin iteration again a used a call to NextElement()
to return the first element.
*/
void Reset();
/*
Description:
Get a pointer to the first element in the first block.
Parameters:
block_element_count - [out] (can be null)
If not null, the number of elements allocated from the
first block is returned in block_element_count.
Note that if you have used ReturnElement(), some
of these elemements may have been returned.
Example:
The loop will iteratate through all the blocks.
// iterate through all blocks in the pool
size_t block_element_count = 0;
for ( void* p = FirstBlock(&block_element_count);
0 != p;
p = NextBlock(&block_element_count)
)
{
ElementType* e = (ElementType*)p;
for ( size_t i = 0;
i < block_element_count;
i++, e = ((const char*)e) + SizeofElement()
)
{
...
}
}
Returns:
The first block when iterating the list of blocks.
Remarks:
The heap for a fixed size memory pool is simply a linked
list of blocks. FirstBlock() and NextBlock() can be used
to iterate through the list of blocks.
Do not make any calls to FirstElement() or NextElement() when using
FirstBlock() and NextBlock() to iteratate through blocks.
*/
void* FirstBlock( size_t* block_element_count );
/*
Description:
Get the next block when iterating through the blocks.
Parameters:
block_element_count - [out] (can be null)
If not null, the number of elements allocated from the
block is returned in block_element_count. Note that if
you have used ReturnElement(), some of these elemements
may have been returned.
Example:
See the FirstBlock() documentation.
Returns:
The next block when iterating through the blocks.
Remarks:
Do not make any calls to FirstElement() or NextElement() when using
FirstBlock() and NextBlock() to iteratate through blocks.
*/
void* NextBlock( size_t* block_element_count );
private:
const class ON_FixedSizePool* m_fsp;
void* m_it_block;
void* m_it_element;
};
template <class T> class ON_SimpleFixedSizePool : private ON_FixedSizePool
{
public:
// construction ////////////////////////////////////////////////////////
ON_SimpleFixedSizePool();
~ON_SimpleFixedSizePool();
/*
Description:
Create a fixed size memory pool.
Parameters:
element_count_estimate - [in] (0 = good default)
If you know how many elements you will need, pass that number here.
It is better to slightly overestimate than to slightly underestimate.
If you do not have a good estimate, then use zero.
block_element_count - [in] (0 = good default)
If block_element_count is zero, Create() will calculate a block
size that is efficent for most applications. If you are an expert
user and want to specify the number of blocks, then pass the number
of elements per block here. When block_element_count > 0 and
element_count_estimate > 0, the first block will be large enough
element_count_estimate*sizeof(T) bytes; in this case do not
ask for extraordinarly large amounts of contiguous heap.
Remarks:
You must call Create() on an unused ON_FixedSizePool or call Destroy()
before calling create.
Returns:
True if successful and the pool can be used.
*/
bool Create(
size_t element_count_estimate,
size_t block_element_count
);
/*
Returns:
Size of the elements in this pool.
*/
size_t SizeofElement() const;
/*
Returns:
A pointer to sizeof_element bytes. The memory is zeroed.
*/
T* AllocateElement();
/*
Description:
Return an element to the pool.
Parameters:
p - [in]
A pointer returned by AllocateElement().
It is critical that p be from this pool and that
you return a pointer no more than one time.
Remarks:
If you find the following remarks confusing, but you really want to use
ReturnElement(), then here are some simple guidelines.
1) SizeofElement() must be >= 16
2) SizeofElement() must be a multiple of 8.
3) Do not use FirstElement() and NextElement() to iterate through
the pool.
If 1 to 3 don't work for you, then you need to understand the following
information before using ReturnElement().
ON_FixedMemoryPool uses the first sizeof(void*) bytes of the
returned element for bookkeeping purposes. Therefore, if you
are going to use ReturnElement(), then SizeofElement() must be
at least sizeof(void*). If you are using a platform that requires
pointers to be aligned on sizeof(void*) boundaries, then
SizeofElement() must be a multiple of sizeof(void*).
If you are going to use ReturnElement() and then use FirstElement()
and NextElement() to iterate through the list of elements, then you
need to set a value in the returned element to indicate that it
needs to be skipped during the iteration. This value cannot be
located in the fist sizeof(void*) bytes of the element. If the
element is a class with a vtable, you cannot call a virtual
function on a returned element because the vtable pointer is
trashed when ReturnElement() modifies the fist sizeof(void*) bytes.
*/
void ReturnElement(T* p);
/*
Description:
Return all allocated elements to the pool. No heap is freed and
the pool remains initialized and ready for AllocateElement()
to be called.
*/
void ReturnAll();
/*
Description:
Destroy the pool and free all the heap. The pool cannot be used again
until Create() is called.
*/
void Destroy();
/*
Returns:
Number of active elements. (Elements that have been returned are not active.)
*/
size_t ActiveElementCount() const;
/*
Returns:
Total number of elements = number of active elements + number of returned elements.
*/
size_t TotalElementCount() const;
/*
Description:
Get the i-th elment in the pool.
Parameters:
element_index - [in]
Returns:
A pointer to the i-th element. The first element has index = 0
and is the element returned by the first call to AllocateElement().
The last element has index = ElementCount()-1.
If i is out of range, null is returned.
Remarks:
It is faster to use FirstElement() and NextElement() to iterate
through the entire list of elements. This function is relatively
efficient when there are a few large blocks in the pool
or element_index is small compared to the number of elements
in the first few blocks.
If ReturnElement() is not used or AllocateElement() calls to
are made after any use of ReturnElement(), then the i-th
element is the one returned by the (i+1)-th call to
AllocateElement().
*/
T* Element(size_t element_index) const;
size_t ElementIndex(
T*
) const;
private:
// prohibit copy construction and operator=.
ON_SimpleFixedSizePool(const ON_SimpleFixedSizePool<T>&);
ON_SimpleFixedSizePool<T>& operator=(const ON_SimpleFixedSizePool<T>&);
};
template <class T> class ON_SimpleFixedSizePoolIterator : private ON_FixedSizePoolIterator
{
public:
ON_SimpleFixedSizePoolIterator( const class ON_SimpleFixedSizePool<T>& fsp );
ON_SimpleFixedSizePoolIterator(const class ON_SimpleFixedSizePoolIterator<T>&);
/*
Description:
Get the first element when iterating through the list of elements.
Parameters:
element_index - [in]
If you use the version of FirstElement() that has an
element_index parameter, then the iteration begins at
that element.
Example:
The loop will iteratate through all the elements returned from
AllocateElement(), including any that have be returned to the pool
using ReturnElement().
// iterate through all elements in the pool
// This iteration will go through TotalElements() items.
for ( void* p = FirstElement(); 0 != p; p = NextElement() )
{
// If you are not using ReturnElement(), then you may process
// "p" immediately. If you have used ReturnElement(), then you
// must check some value in p located after the first sizeof(void*)
// bytes to see if p is active.
if ( p is not active )
continue;
... process p
}
Returns:
The first element when iterating through the list of elements.
Remarks:
FirstElement() and NextElement() will return elements that have
been returned to the pool using ReturnElement(). If you use
ReturnElement(), then be sure to mark the element so it can be
identified and skipped.
Do not make any calls to FirstBlock() or NextBlock() when using
FirstElement() and NextElement() to iteratate through elements.
*/
T* FirstElement();
T* FirstElement( size_t element_index );
/*
Description:
Get the next element when iterating through the list of elements.
If FirstElement() is not called, then the first call to
NextElement() returns the first element.
Example:
See the FirstElement() documentation.
Returns:
The next element when iterating through the list of elements.
Remarks:
FirstElement() and NextElement() will return elements that have
been returned to the pool using ReturnElement(). If you use
ReturnElement(), then be sure to mark the element so it can be
identified and skipped.
Do not make any calls to FirstBlock() or NextBlock() when using
FirstElement() and NextElement() to iteratate through elements.
*/
T* NextElement();
/*
Returns:
The most recently returned value from a call to FirstElement()
or NextElement().
Remarks:
Do not make any calls to FirstBlock() or NextBlock() when using
FirstElement() and NextElement() to iteratate through elements.
*/
T* CurrentElement();
/*
Description:
Sets the state of the iterator to the initail state that
exists after construction. This is useful if the iterator
has been used the get one or more elements and then
the referenced fixed size pool is modified or code wants
to begin iteration again a used a call to NextElement()
to return the first element.
*/
void Reset();
/*
Description:
Get a pointer to the first element in the first block.
Parameters:
block_element_count - [out] (can be null)
If not null, the number of elements allocated from the
first block is returned in block_element_count.
Note that if you have used ReturnElement(), some
of these elemements may have been returned.
Example:
The loop will iteratate through all the blocks.
// iterate through all blocks in the pool
size_t block_element_count = 0;
for ( void* p = FirstBlock(&block_element_count);
0 != p;
p = NextBlock(&block_element_count)
)
{
ElementType* e = (ElementType*)p;
for ( size_t i = 0;
i < block_element_count;
i++, e = ((const char*)e) + SizeofElement()
)
{
...
}
}
Returns:
The first block when iterating the list of blocks.
Remarks:
The heap for a fixed size memory pool is simply a linked
list of blocks. FirstBlock() and NextBlock() can be used
to iterate through the list of blocks.
Do not make any calls to FirstElement() or NextElement() when using
FirstBlock() and NextBlock() to iteratate through blocks.
*/
T* FirstBlock( size_t* block_element_count );
/*
Description:
Get the next block when iterating through the blocks.
Parameters:
block_element_count - [out] (can be null)
If not null, the number of elements allocated from the
block is returned in block_element_count. Note that if
you have used ReturnElement(), some of these elemements
may have been returned.
Example:
See the FirstBlock() documentation.
Returns:
The next block when iterating through the blocks.
Remarks:
Do not make any calls to FirstElement() or NextElement() when using
FirstBlock() and NextBlock() to iteratate through blocks.
*/
T* NextBlock( size_t* block_element_count );
private:
// no implementation (you can use a copy construtor)
class ON_SimpleFixedSizePoolIterator<T>& operator=(const class ON_SimpleFixedSizePoolIterator<T>&);
};
// definitions of the template functions are in a different file
// so that Microsoft's developer studio's autocomplete utility
// will work on the template functions.
#include "opennurbs_fsp_defs.h"
#endif
+148
View File
@@ -0,0 +1,148 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(ON_FSP_DEFS_INC_)
#define ON_FSP_DEFS_INC_
template <class T>
ON_SimpleFixedSizePool<T>::ON_SimpleFixedSizePool()
: ON_FixedSizePool()
{}
template <class T>
ON_SimpleFixedSizePool<T>::~ON_SimpleFixedSizePool()
{
ON_FixedSizePool::Destroy();
}
template <class T>
bool ON_SimpleFixedSizePool<T>::Create(
size_t element_count_estimate,
size_t block_element_count
)
{
return ON_FixedSizePool::Create(sizeof(T),element_count_estimate,block_element_count);
}
template <class T>
size_t ON_SimpleFixedSizePool<T>::SizeofElement() const
{
return ON_FixedSizePool::SizeofElement();
}
template <class T>
T* ON_SimpleFixedSizePool<T>::AllocateElement()
{
return (T *)ON_FixedSizePool::AllocateElement();
}
template <class T>
void ON_SimpleFixedSizePool<T>::ReturnElement(T* p)
{
ON_FixedSizePool::ReturnElement(p);
}
template <class T>
void ON_SimpleFixedSizePool<T>::ReturnAll()
{
ON_FixedSizePool::ReturnAll();
}
template <class T>
void ON_SimpleFixedSizePool<T>::Destroy()
{
ON_FixedSizePool::Destroy();
}
template <class T>
size_t ON_SimpleFixedSizePool<T>::ActiveElementCount() const
{
return ON_FixedSizePool::ActiveElementCount();
}
template <class T>
size_t ON_SimpleFixedSizePool<T>::TotalElementCount() const
{
return ON_FixedSizePool::TotalElementCount();
}
template <class T>
T* ON_SimpleFixedSizePool<T>::Element(size_t element_index) const
{
return (T *)ON_FixedSizePool::Element(element_index);
}
template <class T>
size_t ON_SimpleFixedSizePool<T>::ElementIndex(T* element_ptr) const
{
return ON_FixedSizePool::ElementIndex(element_ptr);
}
template <class T>
ON_SimpleFixedSizePoolIterator<T>::ON_SimpleFixedSizePoolIterator(const class ON_SimpleFixedSizePool<T>& fsp)
: ON_FixedSizePoolIterator((ON_FixedSizePool&)fsp)
{}
template <class T>
ON_SimpleFixedSizePoolIterator<T>::ON_SimpleFixedSizePoolIterator(const class ON_SimpleFixedSizePoolIterator<T>& fsp_it)
: ON_FixedSizePoolIterator(fsp_it)
{}
template <class T>
T* ON_SimpleFixedSizePoolIterator<T>::FirstElement()
{
return (T *)ON_FixedSizePoolIterator::FirstElement();
}
template <class T>
T* ON_SimpleFixedSizePoolIterator<T>::FirstElement(size_t element_index)
{
return (T *)ON_FixedSizePoolIterator::FirstElement(element_index);
}
template <class T>
T* ON_SimpleFixedSizePoolIterator<T>::NextElement()
{
return (T *)ON_FixedSizePoolIterator::NextElement();
}
template <class T>
T* ON_SimpleFixedSizePoolIterator<T>::CurrentElement()
{
return (T *)ON_FixedSizePoolIterator::CurrentElement();
}
template <class T>
void ON_SimpleFixedSizePoolIterator<T>::Reset()
{
ON_FixedSizePoolIterator::Reset();
}
template <class T>
T* ON_SimpleFixedSizePoolIterator<T>::FirstBlock( size_t* block_element_count )
{
return (T *)ON_FixedSizePoolIterator::FirstBlock(block_element_count);
}
template <class T>
T* ON_SimpleFixedSizePoolIterator<T>::NextBlock( size_t* block_element_count )
{
return (T *)ON_FixedSizePoolIterator::NextBlock(block_element_count);
}
#endif
+132
View File
@@ -0,0 +1,132 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2013 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_FUNCTION_LIST_INC_)
#define OPENNURBS_FUNCTION_LIST_INC_
class ON_CLASS ON_FunctionList
{
public:
/*
Parameters:
function_count_estimate - [in]
An estimate of the maximum number of functions that will
be in the list at any one time. Pass 0 if you don't know.
*/
ON_FunctionList(
size_t function_count_estimate
);
~ON_FunctionList();
/*
Description:
Unconditionally add a function to the list.
Parameters:
function - [in]
A function that takes a single ON__UINT_PTR parameter.
function_parameter - [in]
Returns:
0: list in use
1: function added
2: invalid input
*/
unsigned int AddFunction(
void (*function)(ON__UINT_PTR),
ON__UINT_PTR function_parameter
);
/*
Returns:
0: list in use
1: function removed
2: matching function not in the list
*/
unsigned int RemoveFunction(
void (*function)(ON__UINT_PTR)
);
/*
Returns:
0: list in use
1: function removed
2: matching function not in the list
*/
unsigned int RemoveFunction(
void (*function)(ON__UINT_PTR),
ON__UINT_PTR function_parameter
);
/*
Returns:
0: Matching function and parameter are not in the list.
1: Matching function and parameter are in the list.
2: list in use
*/
unsigned int IsInList(
void (*function)(ON__UINT_PTR),
ON__UINT_PTR function_parameter
) const;
/*
Returns:
0: list in use
1: Matching function is in the list.
2: Matching function is not in the list.
*/
unsigned int IsInList(
void (*function)(ON__UINT_PTR)
) const;
/*
Returns:
0: list in use
1: list was emptied
*/
bool EmptyList();
/*
Description:
Call all the functions in the function list.
Parameters:
bFirstToLast - [in]
true - function are called in the order added
false - functions are called in the reverse order added
Returns:
True if the functions were called or the list is empty.
False if the list is in use.
*/
bool CallFunctions(
bool bFirstToLast
);
/*
Returns:
True if the list is in use.
*/
bool InUse() const;
unsigned int FunctionCount() const;
private:
ON_FixedSizePool m_fsp;
void* m_head = nullptr;
void* m_tail = nullptr;
mutable ON_Lock m_lock;
};
#endif
+398
View File
@@ -0,0 +1,398 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
////////////////////////////////////////////////////////////////
//
// virtual base class for all geomtric objects
//
////////////////////////////////////////////////////////////////
#if !defined(OPENNURBS_GEOMETRY_INC_)
#define OPENNURBS_GEOMETRY_INC_
class ON_Brep;
////////////////////////////////////////////////////////////////
// Description:
// Base class for all geometry classes that must
// provide runtime class id. Provides interface
// for common geometric operations like finding bounding
// boxes and transforming.
//
class ON_CLASS ON_Geometry : public ON_Object
{
// Any object derived from ON_Geometry should have a
// ON_OBJECT_DECLARE(ON_...);
// as the last line of its class definition and a
// ON_OBJECT_IMPLEMENT( ON_..., ON_baseclass );
// in a .cpp file.
//
// See the definition of ON_Object for details.
ON_OBJECT_DECLARE(ON_Geometry);
public:
const static ON_Geometry Unset;
public:
ON_Geometry() = default;
~ON_Geometry() = default;
ON_Geometry(const ON_Geometry&) = default;
ON_Geometry& operator=(const ON_Geometry&) = default;
#if defined(ON_HAS_RVALUEREF)
// rvalue copy constructor
ON_Geometry( ON_Geometry&& ) ON_NOEXCEPT;
// The rvalue assignment operator calls ON_Object::operator=(ON_Object&&)
// which could throw exceptions. See the implementation of
// ON_Object::operator=(ON_Object&&) for details.
ON_Geometry& operator=( ON_Geometry&& );
#endif
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
// Description:
// Get object's 3d axis aligned bounding box.
// Returns:
// 3d bounding box.
// Remarks:
// Uses virtual GetBBox() function to calculate the result.
ON_BoundingBox BoundingBox() const;
// Description:
// Get object's 3d axis aligned bounding box or the
// union of the input box with the object's bounding box.
// Parameters:
// bbox - [in/out] 3d axis aligned bounding box
// bGrowBox - [in] (default=false)
// If true, then the union of the input bbox and the
// object's bounding box is returned in bbox.
// If false, the object's bounding box is returned in bbox.
// Returns:
// true if object has bounding box and calculation was successful.
// Remarks:
// Uses virtual GetBBox() function to calculate the result.
bool GetBoundingBox(
ON_BoundingBox& bbox,
bool bGrowBox = false
) const;
// Description:
// Get corners of object's 3d axis aligned bounding box
// or the union of the input box with the object's bounding
// box.
// Parameters:
// bbox_min - [in/out] minimum corner of the 3d bounding box
// bbox_max - [in/out] maximum corner of the 3d bounding box
// bGrowBox - [in] (default=false)
// If true, then the union of the input bbox and the
// object's bounding box is returned.
// If false, the object's bounding box is returned.
// Returns:
// true if successful.
bool GetBoundingBox(
ON_3dPoint& bbox_min,
ON_3dPoint& bbox_max,
bool bGrowBox = false
) const;
// Description:
// Rotates the object about the specified axis. A positive
// rotation angle results in a counter-clockwise rotation
// about the axis (right hand rule).
// Parameters:
// sin_angle - [in] sine of rotation angle
// cos_angle - [in] sine of rotation angle
// rotation_axis - [in] direction of the axis of rotation
// rotation_center - [in] point on the axis of rotation
// Returns:
// true if object successfully rotated
// Remarks:
// Uses virtual Transform() function to calculate the result.
bool Rotate(
double sin_angle,
double cos_angle,
const ON_3dVector& rotation_axis,
const ON_3dPoint& rotation_center
);
// Description:
// Rotates the object about the specified axis. A positive
// rotation angle results in a counter-clockwise rotation
// about the axis (right hand rule).
// Parameters:
// rotation_angle - [in] angle of rotation in radians
// rotation_axis - [in] direction of the axis of rotation
// rotation_center - [in] point on the axis of rotation
// Returns:
// true if object successfully rotated
// Remarks:
// Uses virtual Transform() function to calculate the result.
bool Rotate(
double rotation_angle,
const ON_3dVector& rotation_axis,
const ON_3dPoint& rotation_center
);
// Description:
// Translates the object along the specified vector.
// Parameters:
// translation_vector - [in] translation vector
// Returns:
// true if object successfully translated
// Remarks:
// Uses virtual Transform() function to calculate the result.
bool Translate(
const ON_3dVector& translation_vector
);
// Description:
// Scales the object by the specified facotor. The scale is
// centered at the origin.
// Parameters:
// scale_factor - [in] scale factor
// Returns:
// true if object successfully scaled
// Remarks:
// Uses virtual Transform() function to calculate the result.
bool Scale(
double scale_factor
);
// Description:
// Dimension of the object.
// Returns:
// Dimension of the object.
// Remarks:
// The dimension is typically three. For parameter space trimming
// curves the dimension is two. In rare cases the dimension can
// be one or greater than three.
virtual int Dimension() const;
// Description:
// This is the virtual function that actually calculates axis
// aligned bounding boxes.
// Parameters:
// boxmin - [in/out] array of Dimension() doubles
// boxmax - [in/out] array of Dimension() doubles
// bGrowBox - [in] (default=false)
// If true, then the union of the input bbox and the
// object's bounding box is returned in bbox.
// If false, the object's bounding box is returned in bbox.
// Returns:
// true if object has bounding box and calculation was successful
virtual bool GetBBox(
double* boxmin,
double* boxmax,
bool bGrowBox = false
) const;
/*
Description:
Get tight bounding box.
Parameters:
tight_bbox - [in/out] tight bounding box
bGrowBox -[in] (default=false)
If true and the input tight_bbox is valid, then returned
tight_bbox is the union of the input tight_bbox and the
curve's tight bounding box.
xform -[in] (default=nullptr)
If not nullptr, the tight bounding box of the transformed
geometry is calculated. The geometry is not modified.
Returns:
True if a valid tight_bbox is returned.
Remarks:
In general, GetTightBoundingBox is slower that BoundingBox,
especially when xform is not null.
*/
virtual bool GetTightBoundingBox(
class ON_BoundingBox& tight_bbox,
bool bGrowBox = false,
const class ON_Xform* xform = nullptr
) const;
// Description:
// Some objects cache bounding box information.
// If you modify an object, then call ClearBoundingBox()
// to inform the object that any cached bounding boxes
// are invalid.
//
// Remarks:
// Generally, ClearBoundingBox() overrides
// simply invalidate a cached bounding box and then wait
// for a call to GetBBox() before recomputing the bounding box.
//
// The default implementation does nothing.
virtual void ClearBoundingBox();
/*
Description:
Transforms the object.
Parameters:
xform - [in] transformation to apply to object.
If xform.IsSimilarity() is zero, then you may
want to call MakeSquishy() before calling
Transform.
Remarks:
When overriding this function, be sure to include a call
to ON_Object::TransformUserData() which takes care of
transforming any ON_UserData that may be attached to
the object.
See Also:
ON_Geometry::IsDeformable();
Remarks:
Classes derived from ON_Geometry should call
ON_Geometry::Transform() to handle user data
transformations and then transform their
definition.
*/
virtual
bool Transform(
const ON_Xform& xform
);
/*
Returns:
True if object can be accuratly modified with
"squishy" transformations like projections,
shears, an non-uniform scaling.
See Also:
ON_Geometry::MakeDeformable();
*/
virtual
bool IsDeformable() const;
/*
Description:
If possible, converts the object into a form that can
be accuratly modified with "squishy" transformations
like projections, shears, an non-uniform scaling.
Returns:
False if object cannot be converted to a deformable
object. True if object was already deformable or
was converted into a deformable object.
See Also:
ON_Geometry::IsDeformable();
*/
virtual
bool MakeDeformable();
// Description:
// Swaps object coordinate values with indices i and j.
//
// Parameters:
// i - [in] coordinate index
// j - [in] coordinate index
//
// Remarks:
// The default implementation uses the virtual Transform()
// function to calculate the result. If you are creating
// an object where Transform() is slow, coordinate swapping
// will be frequently used, and coordinate swapping can
// be quickly accomplished, then override this function.
//
// Example:
//
// ON_Point point(7,8,9);
// point.SwapCoordinates(0,2);
// // point = (9,8,7)
virtual
bool SwapCoordinates(
int i,
int j
);
/*
Description:
Query an object to see if it has an ON_Brep form.
Result:
Returns true if the virtual ON_Geometry::BrepForm can compute
an ON_Brep representation of this object.
Remarks:
The default implementation of ON_Geometry::BrepForm returns
false.
See Also
ON_Geometry::BrepForm
*/
virtual
bool HasBrepForm() const;
/*
Description:
If possible, BrepForm() creates a brep form of the
ON_Geometry.
Parameters:
brep - [in] if not nullptr, brep is used to store the brep
form of the geometry.
Result:
Returns a pointer to on ON_Brep or nullptr. If the brep
parameter is not nullptr, then brep is returned if the
geometry has a brep form and nullptr is returned if the
geometry does not have a brep form.
Remarks:
The caller is responsible for managing the brep memory.
See Also
ON_Geometry::HasBrepForm
*/
virtual
class ON_Brep* BrepForm(
class ON_Brep* brep = nullptr
) const;
/*
Description:
If this piece of geometry is a component in something
larger, like an ON_BrepEdge in an ON_Brep, then this
function returns the component index.
Returns:
This object's component index. If this object is
not a sub-piece of a larger geometric entity, then
the returned index has
m_type = ON_COMPONENT_INDEX::invalid_type
and
m_index = -1.
*/
virtual
ON_COMPONENT_INDEX ComponentIndex() const;
/*
Description:
Evaluate the location of a point from the object
reference.
Parameters:
objref - [in]
point - [out]
If the evaluation cannot be performed, ON_3dPoint::UnsetPoint
is returned.
Returns:
True if successful.
*/
virtual
bool EvaluatePoint(
const class ON_ObjRef& objref,
ON_3dPoint& P
) const;
};
#endif
+246
View File
@@ -0,0 +1,246 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2011 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
////////////////////////////////////////////////////////////////
//
// Definitions of ON_GL() functions that demonstrate how to
// use GL to display OpenNURBS objects.
//
////////////////////////////////////////////////////////////////
#include "opennurbs.h"
#if defined(ON_COMPILER_MSC)
// Tested compilers:
// Microsoft Developer Studio 6.0
// Microsoft Visual Studio 2005
// Support for other Windows compilers is not available.
// Windows Open GL files require windows.h to be included before the
// Open GL header files.
#pragma ON_PRAGMA_WARNING_PUSH
#include <windows.h>
#include <GL/gl.h> // Open GL basic definitions
#include <GL/glu.h> // Open GL utilities (for GL NURBS stuff)
#pragma ON_PRAGMA_WARNING_POP
#elif defined(ON_COMPILER_CLANG)
// Tested compilers:
// Apple Xcode 2.4.1
// Support for other Apple compilers is not available.
#include <GLUT/glut.h> // Open GL auxillary functions
#else
// Unsupported compiler:
// Support for other compilers is not available
#include <GL/gl.h> // Open GL basic definitions
#include <GL/glu.h> // Open GL utilities (for GL NURBS stuff)
#endif
#if !defined(OPENNURBS_GL_INC_)
#define OPENNURBS_GL_INC_
// Use ON_GL( const ON_Point, ...) to render single points.
void ON_GL(
const ON_Point&
);
// Use ON_GL( const ON_PointCloud, ...) to render Rhino point sets.
void ON_GL(
const ON_PointCloud&
);
// Use ON_GL( const ON_Mesh&, ...) to render OpenNURBS meshes.
void ON_GL(
const ON_Mesh&
);
// Use ON_GL( const ON_Brep&, ...) to render OpenNURBS b-reps.
void ON_GL(
const ON_Brep&,
GLUnurbsObj*
);
// must be bracketed by calls to glBegin(GL_POINTS) / glEnd()
void ON_GL(
const ON_3dPoint&
);
void ON_GL(
const ON_Curve&, //
GLUnurbsObj*, // created with gluNewNurbsRenderer
GLenum = 0, // type of curve (if 0, type is automatically set)
double[][4] = nullptr // optional transformation applied to curve
);
// must be bracketed by calls to gluBeginSurface( nobj )/gluEndSurface( nobj )
void ON_GL(
const ON_Surface&, //
GLUnurbsObj* // created with gluNewNurbsRenderer
);
// Use ON_GL( const ON_NurbsCurve&,...) in place of
// gluNurbsCurve(). See your system's gluNurbsCurve() documentation
// for details. In particular, for 3d curves the call to
// ON_GL( const ON_NurbsCurve&, nobj,...) should appear inside
// of a gluBeginCurve( nobj )/gluEndCurve( nobj ) pair.
// Generally, the GL "type" should be set using the formula
// ON_NurbsCurve:IsRational()
// ? GL_MAP1_VERTEX_4
// : GL_MAP1_VERTEX_3;
void ON_GL(
const ON_NurbsCurve&, //
GLUnurbsObj*, // created with gluNewNurbsRenderer
GLenum = 0, // type of curve (if 0, type is automatically set)
int = 1, // bPermitKnotScaling - If true, curve knots may
// be rescaled to avoid knot vectors GL cannot handle.
double* = nullptr, // knot_scale[2] - If not nullptr and bPermitKnotScaling,
// the scaling applied to the knot vector is
// returned here.
double[][4] = nullptr // optional transformation applied to curve
);
void ON_GL( // low level NURBS curve renderer
int, int, int, int, // dim, is_rat, cv_count, order
const double*, // knot_vector[]
int, // cv_stride
const double*, // cv
GLUnurbsObj*, // created with gluNewNurbsRenderer
GLenum = 0, // type of curve (if 0, type is automatically set)
int = 1, // bPermitKnotScaling - If true, curve knots may
// be rescaled to avoid knot vectors GL cannot handle.
double* = nullptr, // knot_scale[2] - If not nullptr and bPermitKnotScaling,
// the scaling applied to the knot vector is
// returned here.
double[][4] = nullptr // optional transformation applied to curve
);
// Use ON_GL( const ON_NurbsSurface&,...) in place of
// gluNurbsSurface(). See your system's gluNurbsSurface() documentation
// for details. In particular, the call to
// ON_GL( const ON_NurbsSurface&, nobj, ...) should appear inside
// of a gluBeginSurface( nobj )/gluEndSurface( nobj ) pair.
// Generally, the GL "type" should be set using the formula
// ON_NurbsSurface:IsRational()
// ? GL_MAP2_VERTEX_4
// : GL_MAP2_VERTEX_3;
void ON_GL(
const ON_NurbsSurface&, //
GLUnurbsObj*, // created with gluNewNurbsRenderer
GLenum = 0, // type of surface
// (if 0, type is automatically set)
int = 1, // bPermitKnotScaling - If true, surface knots may
// be rescaled to avoid knot vectors GL cannot handle.
double* = nullptr, // knot_scale0[2] - If not nullptr and bPermitKnotScaling,
// the scaleing applied to the first parameter is
// returned here.
double* = nullptr // knot_scale0[2] - If not nullptr and bPermitKnotScaling,
// the scaleing applied to the second parameter is
// returned here.
);
// Use ON_GL( const ON_BrepFace&, nobj ) to render
// the trimmed NURBS surface that defines a ON_Brep face's geometry.
// The call to ON_GL( const ON_BrepFace&, nobj ) should
// appear inside of a gluBeginSurface( nobj )/gluEndSurface( nobj )
// pair.
void ON_GL(
const ON_BrepFace&, //
GLUnurbsObj* // created with gluNewNurbsRenderer
);
// Use ON_GL( const ON_Color ...) to set GL color to OpenNURBS color
void ON_GL( const ON_Color&,
GLfloat[4]
);
void ON_GL( const ON_Color&,
double, // alpha
GLfloat[4]
);
// Use ON_GL( const ON_Material ...) to set GL material to OpenNURBS material
void ON_GL(
const ON_Material&
);
void ON_GL(
const ON_Material* // pass nullptr to get OpenNURBS's default material
);
// Use ON_GL( const ON_Light, ...) to add OpenNURBS spotlights to
// GL lighting model
void ON_GL(
const ON_Light*, // pass nullptr to disable the light
GLenum // GL_LIGHTi where 0 <= i <= GL_MAX_LIGHTS
// See glLight*() documentation for details
);
void ON_GL(
const ON_Light&,
GLenum // GL_LIGHTi where 0 <= i <= GL_MAX_LIGHTS
// See glLight*() documentation for details
);
//////////////////////////////////////////////////////////////////////////
// Use ON_GL( ON_Viewport& ... ) to set the GL projections to match
// those used in the OpenNURBS viewport.
////////////
//
// Use ON_GL( ON_Viewport&, in, int, int, int ) to specify the size of the
// GL window and loads the GL projection matrix (camera to clip
// transformation). If the aspect ratio of the GL window and
// ON_Viewport's frustum do not match, the viewport's frustum is
// adjusted to get things back to 1:1.
//
// For systems where the upper left corner of a window has
// coordinates (0,0) use:
// port_left = 0
// port_right = width-1
// port_bottom = height-1
// port_top = 0
void ON_GL( ON_Viewport&,
int, int, // port_left, port_right (port_left != port_right)
int, int // port_bottom, port_top (port_bottom != port_top)
);
////////////
//
// Use ON_GL( ON_Viewport& ) to load the GL model view matrix (world to
// camera transformation).
void ON_GL( const ON_Viewport& );
// Use ON_GL( order, cv_count, knot, bPermitScaling, glknot )
// to create knot vectors suitable for GL NURBS rendering.
void ON_GL(
const int, // order, ON_NurbsCurve... order
const int, // cv_count, ON_NurbsCurve... cv count
const double*, // knot, ON_NurbsCurve... knot vector
GLfloat*, // glknot[] - GL knot vector
int = 0, // bPermitScaling - true if re-scaling is allowed
double* = nullptr // scale[2] - If not nullptr and bPermitScaling is true,
// then the scaling parameters are returned here.
// ( glknot = (knot = scale[0])*scale[1] )
);
#endif
+83
View File
@@ -0,0 +1,83 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_GROUP_INC_)
#define OPENNURBS_GROUP_INC_
class ON_CLASS ON_Group : public ON_ModelComponent
{
ON_OBJECT_DECLARE(ON_Group);
public:
static const ON_Group Unset; // nil id
/*
Parameters:
model_component_reference - [in]
none_return_value - [in]
value to return if ON_Material::Cast(model_component_ref.ModelComponent())
is nullptr
Returns:
If ON_Material::Cast(model_component_ref.ModelComponent()) is not nullptr,
that pointer is returned. Otherwise, none_return_value is returned.
*/
static const ON_Group* FromModelComponentRef(
const class ON_ModelComponentReference& model_component_reference,
const ON_Group* none_return_value
);
public:
ON_Group() ON_NOEXCEPT;
ON_Group(const ON_Group& src);
~ON_Group() = default;
ON_Group& operator=(const ON_Group& src) = default;
private:
//////////////////////////////////////////////////////////////////////
//
// ON_Object overrides
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
void Dump(
ON_TextLog& text_log
) const override;
bool Write(
ON_BinaryArchive& archive
) const override;
bool Read(
ON_BinaryArchive& archive
) override;
private:
bool Internal_WriteV5(
ON_BinaryArchive& archive
) const;
bool Internal_ReadV5(
ON_BinaryArchive& archive
);
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_Group*>;
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<const ON_Group*>;
ON_DLL_TEMPLATE template class ON_CLASS ON_ObjectArray<ON_Group>;
#endif
#endif
+199
View File
@@ -0,0 +1,199 @@
/*
//
// Copyright (c) 1993-2016 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
////////////////////////////////////////////////////////////////
//
// defines ON_Hash32Table
//
////////////////////////////////////////////////////////////////
#if !defined(OPENNURBS_HASH_TABLE_INC_)
#define OPENNURBS_HASH_TABLE_INC_
class ON_CLASS ON_Hash32TableItem
{
public:
ON_Hash32TableItem() = default;
~ON_Hash32TableItem() = default;
ON_Hash32TableItem(const ON_Hash32TableItem&) = default;
ON_Hash32TableItem& operator=(const ON_Hash32TableItem&) = default;
public:
ON__UINT32 HashTableSerialNumber() const;
static ON__UINT32 Hash32FromSHA1Hash(
const class ON_SHA1_Hash& sha1_hash
);
static ON__UINT32 Hash32FromId(
const ON_UUID& id
);
/*
Returns:
If this item has been added to an ON_Hash32Table.AddItem(hash32,item pointer) then the
value of hash3d passed as the first argument to ON_Hash32Table.AddItem(hash32,item pointer)
is returned. This is the value the ON_Hash32Table uses for this item.
Othewise 0 is returned.
Remarks:
This function is useful when copying hash tables.
count = src_hash_table.ItemCount();
MyHashTableItems src_items[count]; // items added to src_hash_table
// copy src_hash_table
MyHashTableItems copied_items[count];
copied_items = src_items;
for (unsigned i = 0; i < count; ++i)
{
ON_SubDSurfaceInterpolatortHash32TableItem& hitem = copied_items[i];
hitem.ClearHashTableSerialNumberForExperts();
m_htable.AddItem(hitem.HashTableItemHash(), &hitem);
}
*/
ON__UINT32 HashTableItemHash() const;
/*
Description:
Useful when copying hash tables to remove the hash table reference from
a copied hash item. Never remove the hash table reference from an item
that is still in a hash table.
*/
void ClearHashTableSerialNumberForExperts();
private:
friend class ON_Hash32Table;
mutable ON_Hash32TableItem* m_internal_next = nullptr;
mutable ON__UINT32 m_internal_hash32 = 0;
mutable ON__UINT32 m_internal_hash_table_sn = 0;
};
/*
Description:
A hash table designed to be used for items with high quality 32-bit hash values.
*/
class ON_CLASS ON_Hash32Table
{
public:
ON_Hash32Table();
~ON_Hash32Table();
private:
ON_Hash32Table(const ON_Hash32Table&) = delete;
ON_Hash32Table& operator=(const ON_Hash32Table&) = delete;
public:
ON__UINT32 HashTableSerialNumber() const;
/*
Description:
Adds an item to the hash table.
Parameters:
hash32 - [in]
item - [in/out]
Returns:
The added item.
*/
bool AddItem(
ON__UINT32 hash32,
class ON_Hash32TableItem* item
);
/*
Returns:
The first item in the hash table with hash = hash32.
Parameters:
hash32 - [in]
Remarks:
This function is used to find the first element in the hash table with the
specified hash32 falue. Use ON_Hash32TableItem.NextItemWithSameHash() to get
the next item in the has table with the same hash value.
*/
class ON_Hash32TableItem* FirstItemWithHash(
ON__UINT32 hash32
) const;
class ON_Hash32TableItem* NextItemWithHash(
const class ON_Hash32TableItem* current_item
) const;
/*
Returns:
The first item in the hash table.
Remarks:
This function is used for iterating throught every element in the hash table.
*/
class ON_Hash32TableItem* FirstTableItem(
) const;
/*
Returns:
The next item in the hash table.
Remarks:
This function is used for iterating throught every element in the hash table.
*/
class ON_Hash32TableItem* NextTableItem(
const ON_Hash32TableItem* item
) const;
/*
Description:
Remove an item from the hash table. Caller is responsible for managing item memory.
Parameters:
item - [in/out]
If the item is removed, the has table serial number is set to zero.
Returns:
The true if the item was removed.
*/
bool RemoveItem(
class ON_Hash32TableItem* item
);
/*
Description:
Removes all hash table items. Caller is responsible for managing the item memory.
*/
unsigned int RemoveAllItems();
/*
Description:
Removes all hash table items.
For each item memset(item,0,fsp.SizeofElement()) and fsp.ReturnElement(item) are called.
*/
unsigned int RemoveAllItems(
class ON_FixedSizePool& fsp
);
/*
Returns:
Number of items in the hash table
*/
unsigned int ItemCount() const;
bool IsValid() const;
private:
const ON__UINT32 m_hash_table_sn;
ON__UINT32 m_reserved = 0;
mutable ON__UINT32 m_hash_table_capacity = 0;
ON__UINT32 m_item_count = 0;
mutable class ON_Hash32TableItem** m_hash_table = nullptr;
void Internal_AdjustTableCapacity(
ON__UINT32 item_count
);
};
#endif
+975
View File
@@ -0,0 +1,975 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#ifndef OPENNURBS_HATCH_H_INCLUDED
#define OPENNURBS_HATCH_H_INCLUDED
/*
class ON_HatchLoop
/////////////////////////////////////////////////////////////////
Represents a 3d boundary loop curve
*/
class ON_CLASS ON_HatchLoop
{
public:
#if defined(OPENNURBS_EXPORTS) || defined(OPENNURBS_IMPORTS)
// When the Microsoft CRT(s) is/are used, this is the best
// way to prevent crashes that happen when a hatch loop is
// allocated with new in one DLL and deallocated with
// delete in another DLL.
// new/delete
void* operator new(size_t);
void operator delete(void*);
// array new/delete
void* operator new[] (size_t);
void operator delete[] (void*);
// in place new/delete
void* operator new(size_t,void*);
void operator delete(void*,void*);
#endif
enum eLoopType
{
ltOuter = 0,
ltInner = 1,
};
ON_HatchLoop();
ON_HatchLoop( ON_Curve* pCurve2d, eLoopType type = ltOuter);
ON_HatchLoop( const ON_HatchLoop& src);
~ON_HatchLoop();
ON_HatchLoop& operator=( const ON_HatchLoop& src);
bool IsValid( ON_TextLog* text_log = nullptr ) const;
void Dump( ON_TextLog& ) const; // for debugging
bool Write( ON_BinaryArchive&) const;
bool Read( ON_BinaryArchive&);
// Interface
/////////////////////////////////////////////////////////////////
/*
Description:
Get a closed 2d curve boundary loop
Parameters:
Return:
Pointer to loop's 2d curve
*/
const ON_Curve* Curve() const;
/*
Description:
Specify the 2d loop curve in the hatch's plane coordinates
Parameters:
curve - [in] 2d input curve
Return:
true: success, false, curve couldn't be duplicated
Remarks:
The curve is copied
*/
bool SetCurve( const ON_Curve& curve);
/*
Description:
Get the type flag of the loop
Returns:
eLoopType::ltInner or eLoopType::ltOuter
*/
eLoopType Type() const;
/*
Description:
Specify the type flag of the loop
Parameters:
type - [in] ltInner or ltOuter
*/
void SetType( eLoopType type);
protected:
friend class ON_Hatch;
eLoopType m_type; // loop type flag - inner or outer
ON_Curve* m_p2dCurve; // 2d closed curve bounding the hatch
// This is really a 3d curve with z coordinates = 0
};
/*
class ON_HatchLine
/////////////////////////////////////////////////////////////////
Represents one line of a hatch pattern
Similar to AutoCAD's .pat file definition
ON_HatchLine's are used by ON_HatchPattern
to specify the dashes and offset patterns of the lines.
Each line has the following information:
Angle is the direction of the line CCW from the x axis
The first line origin is at base
Each line repetition is offset by offset from the previous line
offset.x is parallel to the line and
offset.y is perpendicular to the line
The base and offset values are rotated by the line's angle to
produce a location in the hatch pattern's coordinate system
There can be gaps and dashes specified for drawing the line
If there are no dashes, the line is solid
Negative length dashes are gaps
Positive length dashes are drawn as line segments
*/
class ON_CLASS ON_HatchLine
{
public:
// Default constructor creates ON_HatchLine::SolidHorizontal
ON_HatchLine() = default;
~ON_HatchLine() = default;
ON_HatchLine(const ON_HatchLine&) = default;
ON_HatchLine& operator=(const ON_HatchLine&) = default;
static const ON_HatchLine Unset; // angle = unset
static const ON_HatchLine SolidHorizontal; // angle = 0
static const ON_HatchLine SolidVertical; // angle = pi/2
static int Compare(
const ON_HatchLine& a,
const ON_HatchLine& b
);
ON_HatchLine(
double angle_in_radians,
ON_2dPoint base,
ON_2dVector offset,
const ON_SimpleArray<double>& dashes
);
// constructs solid line
ON_HatchLine(
double angle_in_radians
);
bool operator==( const ON_HatchLine&) const;
bool operator!=( const ON_HatchLine&) const;
bool IsValid( ON_TextLog* text_log = nullptr ) const;
void Dump( ON_TextLog& ) const; // for debugging
public:
bool Write( ON_BinaryArchive&) const; // serialize definition to binary archive
bool Read( ON_BinaryArchive&); // restore definition from binary archive
private:
bool WriteV5(ON_BinaryArchive&) const; // serialize definition to binary archive
bool ReadV5(ON_BinaryArchive&); // restore definition from binary archive
public:
/////////////////////////////////////////////////////////////////
//
// Interface
//
/*
Description:
Get angle of the hatch line.
CCW from x-axis
Parameters:
Return:
The angle in radians
*/
double AngleRadians() const;
double AngleDegrees() const;
/*
Description:
Set angle of the hatch line.
CCW from x-axis
Parameters:
angle - [in] angle in radians
Return:
*/
void SetAngleRadians(
double angle_in_radians
);
void SetAngleDegrees(
double angle_in_degrees
);
/*
Description:
Get this line's 2d basepoint
Parameters:
Return:
the base point
*/
ON_2dPoint Base() const;
/*
Description:
Set this line's 2d basepoint
Parameters:
base - [in] the basepoint
Return:
*/
void SetBase( const ON_2dPoint& base);
/*
Description:
Get this line's 2d offset for line repetitions
Offset().x is shift parallel to line
Offset().y is spacing perpendicular to line
Parameters:
Return:
the offset
*/
ON_2dVector Offset() const;
/*
Description:
Get this line's 2d offset for line repetitions
Offset().x is shift parallel to line
Offset().y is spacing perpendicular to line
Parameters:
offset - [in] the shift,spacing for repeated lines
Return:
*/
void SetOffset( const ON_2dVector& offset);
/*
Description:
Get the number of gaps + dashes in the line
Parameters:
Return:
nummber of dashes in the line
*/
int DashCount() const;
/*
Description:
Get the dash length at index
Parameters:
index - [in] the dash to get
Return:
the length of the dash ( gap if negative)
*/
double Dash( int) const;
/*
Description:
Add a dash to the pattern
Parameters:
dash - [in] length to append - < 0 for a gap
*/
void AppendDash( double dash);
/*
Description:
Specify a new dash array
Parameters:
dashes - [in] array of dash lengths
*/
void SetDashes( const ON_SimpleArray<double>& dashes);
const ON_SimpleArray<double>& Dashes() const;
/*
Description:
Get the line's angle, base, offset and dashes
in one function call
Parameters:
angle_radians - [out] angle in radians CCW from x-axis
base - [out] origin of the master line
offset - [out] offset for line replications
dashes - [out] the dash array for the line
Return:
*/
void GetLineData(
double& angle_radians,
ON_2dPoint& base,
ON_2dVector& offset,
ON_SimpleArray<double>& dashes) const;
/*
Description:
Get the total length of a pattern repeat
Parameters:
Return:
Pattern length
*/
double GetPatternLength() const;
private:
double m_angle_radians = 0.0;
ON_2dPoint m_base = ON_2dPoint::Origin;
ON_2dVector m_offset = ON_2dVector::ZeroVector;
ON_SimpleArray< double> m_dashes;
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_HatchLoop*>;
ON_DLL_TEMPLATE template class ON_CLASS ON_ClassArray<ON_HatchLine>;
#endif
/*
class ON_HatchPattern
/////////////////////////////////////////////////////////////////
Fill definition for a hatch
The hatch will be one of
ON_Hatch::ON_HatchPattern::HatchFillType::Lines - pat file style definition
ON_Hatch::ON_HatchPattern::HatchFillType::Gradient - uses a color function
ON_Hatch::ON_HatchPattern::HatchFillType::Solid - uses entity color
*/
class ON_CLASS ON_HatchPattern : public ON_ModelComponent
{
ON_OBJECT_DECLARE( ON_HatchPattern);
public:
ON_HatchPattern() ON_NOEXCEPT;
~ON_HatchPattern() = default;
ON_HatchPattern(const ON_HatchPattern&);
ON_HatchPattern& operator=(const ON_HatchPattern&) = default;
public:
static const ON_HatchPattern Unset; // index = ON_UNSET_INT_INDEX, id = nil
static const ON_HatchPattern Solid; // index = -1, id set, unique and persistent
static const ON_HatchPattern Hatch1; // index = -2, id set, unique and persistent
static const ON_HatchPattern Hatch2; // index = -3, id set, unique and persistent
static const ON_HatchPattern Hatch3; // index = -4, id set, unique and persistent
static const ON_HatchPattern HatchDash; // index = -5, id set, unique and persistent
static const ON_HatchPattern Grid; // index = -6, id set, unique and persistent
static const ON_HatchPattern Grid60; // index = -7, id set, unique and persistent
static const ON_HatchPattern Plus; // index = -8, id set, unique and persistent
static const ON_HatchPattern Squares; // index = -9, id set, unique and persistent
// compare everything except Index() value.
static int Compare(
const ON_HatchPattern& a,
const ON_HatchPattern& b
);
// Compare all settings (type, lines, ...) that effect the appearance.
// Ignore Index(), Id(), Name()
static int CompareAppearance(
const ON_HatchPattern& a,
const ON_HatchPattern& b
);
public:
/*
Parameters:
model_component_reference - [in]
none_return_value - [in]
value to return if ON_Layer::Cast(model_component_ref.ModelComponent())
is nullptr
Returns:
If ON_Layer::Cast(model_component_ref.ModelComponent()) is not nullptr,
that pointer is returned. Otherwise, none_return_value is returned.
*/
static const ON_HatchPattern* FromModelComponentRef(
const class ON_ModelComponentReference& model_component_reference,
const ON_HatchPattern* none_return_value
);
public:
enum class HatchFillType : unsigned int
{
Solid = 0, // uses entity color
Lines = 1, // pat file definition
//Gradient = 2, // uses a fill color function
};
static ON_HatchPattern::HatchFillType HatchFillTypeFromUnsigned(
unsigned hatch_fill_type_as_unsigned
);
/////////////////////////////////////////////////////////////////
// ON_Object overrides
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
void Dump( ON_TextLog& ) const override; // for debugging
bool Write( ON_BinaryArchive&) const override;
bool Read( ON_BinaryArchive&) override;
private:
bool WriteV5(ON_BinaryArchive&) const;
bool ReadV5(ON_BinaryArchive&);
public:
//////////////////////////////////////////////////////////////////////
// Interface
/*
Description:
Return the pattern's fill type
Parameters:
*/
ON_HatchPattern::HatchFillType FillType() const;
/*
Description:
Set the pattern's fill type
Parameters:
type - [in] the new filltype
*/
void SetFillType(
ON_HatchPattern::HatchFillType fill_type
);
/*
Description:
Set the name of the pattern
Parameters:
pDescription - [in] the new description
Returns:
*/
void SetDescription(
const wchar_t* pDescription
);
/*
Description:
Get a short description of the pattern
Parameters:
string - [out] The string is returned here
*/
const ON_wString& Description() const;
// Interface functions for line hatches
/////////////////////////////////////////////////////////////////
/*
Description:
Get the number of ON_HatchLines in the pattern
Parameters:
Return:
number of lines
*/
int HatchLineCount() const;
/*
Description:
Add an ON_HatchLine to the pattern
Parameters:
line - [in] the line to add
Return:
>= 0 index of the new line
-1 on failure
*/
int AddHatchLine(
const ON_HatchLine& line
);
/*
Description:
Get the ON_HatchLine at index
Parameters:
index - [in] Index of the line to get
Return:
the hatch line
nullptr if index is out of range
*/
const ON_HatchLine* HatchLine(
int index
) const;
/*
Description:
Remove a hatch line from the pattern
Parameters:
index - [in] Index of the line to remove
Return:
true - success
false - index out of range
*/
bool RemoveHatchLine(
int index
);
/*
Description:
Remove all of the hatch line from the pattern
Parameters:
Return:
true - success
false - index out of range
*/
void RemoveAllHatchLines();
/*
Description:
Set all of the hatch lines at once.
Existing hatchlines are deleted.
Parameters:
lines - [in] Array of lines to add. Lines are copied
Return:
number of lines added
*/
int SetHatchLines(
const ON_ClassArray<ON_HatchLine>& lines
);
int SetHatchLines(
size_t count,
const ON_HatchLine* lines
);
const ON_ClassArray<ON_HatchLine>& HatchLines() const;
private:
ON_HatchPattern::HatchFillType m_type = ON_HatchPattern::HatchFillType::Solid;
ON_wString m_description = ON_wString::EmptyString; // String description of the pattern
// Represents a collection of ON_HatchLine's to make a complete pattern
// This is the definition of a hatch pattern.
// Simple solid line hatches with fixed angle and spacing are also
// represented with this type of hatch
ON_ClassArray<ON_HatchLine> m_lines; // used by line hatches
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_HatchPattern*>;
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<const ON_HatchPattern*>;
ON_DLL_TEMPLATE template class ON_CLASS ON_ObjectArray<ON_HatchPattern>;
#endif
/*
class ON_Hatch
/////////////////////////////////////////////////////////////////
Represents a hatch in planar boundary loop or loops
This is a 2d entity with a plane defining a local coordinate system
The loops, patterns, angles, etc are all in this local coordinate system
The ON_Hatch object manages the plane and loop array
Fill definitions are in the ON_HatchPattern or class derived from ON_HatchPattern
ON_Hatch has an index to get the pattern definition from the pattern table
*/
class ON_CLASS ON_Hatch : public ON_Geometry
{
ON_OBJECT_DECLARE( ON_Hatch);
public:
// Default constructor
ON_Hatch() = default;
~ON_Hatch();
ON_Hatch( const ON_Hatch&);
ON_Hatch& operator=(const ON_Hatch&);
static ON_Hatch* HatchFromBrep(
ON_Hatch* use_this_hatch,
const ON_Brep* brep,
int face_index,
int pattern_index,
double pattern_rotation_radians,
double pattern_scale,
ON_3dPoint basepoint);
private:
void Internal_Destroy();
void Internal_CopyFrom(const ON_Hatch& src);
public:
virtual ON_Hatch* DuplicateHatch() const;
// ON_Object overrides
/////////////////////////////////////////////////////////////////
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
void Dump( ON_TextLog& ) const override;
bool Write( ON_BinaryArchive&) const override;
bool Read( ON_BinaryArchive&) override;
ON::object_type ObjectType() const override;
// ON_Geometry overrides
/////////////////////////////////////////////////////////////////
/*
Returns the geometric dimension of the object ( usually 3)
*/
int Dimension() const override;
// virtual ON_Geometry GetBBox override
bool GetBBox( double* boxmin, double* boxmax, bool bGrowBox = false ) const override;
// virtual ON_Geometry GetTightBoundingBox override
bool GetTightBoundingBox( class ON_BoundingBox& tight_bbox, bool bGrowBox = false, const class ON_Xform* xform = nullptr ) const override;
/*
Description:
Transform the object by a 4x4 xform matrix
Parameters:
[in] xform - An ON_Xform with the transformation information
Returns:
true = Success
false = Failure
Remarks:
The object has been transformed when the function returns.
*/
bool Transform( const ON_Xform&) override;
/*
Description:
Scales the hatch's pattern by a 4x4 xform matrix
Parameters:
[in] xform - An ON_Xform with the transformation information
Returns:
true = Success
false = Failure
Remarks:
The hatch pattern scale is multiplied by the change in length of a
unit vector in the hatch plane x direction when that vector is
scaled by the input xform
*/
bool ScalePattern(ON_Xform xform);
/*
Description:
If possible, BrepForm() creates a brep form of the
ON_Geometry.
Parameters:
brep - [in] if not nullptr, brep is used to store the brep
form of the geometry.
Result:
Returns a pointer to on ON_Brep or nullptr. If the brep
parameter is not nullptr, then brep is returned if the
geometry has a brep form and nullptr is returned if the
geometry does not have a brep form.
Remarks:
The caller is responsible for managing the brep memory.
See Also
ON_Geometry::HasBrepForm
*/
class ON_Brep* BrepForm(
class ON_Brep* brep = nullptr
) const override;
// Interface
/////////////////////////////////////////////////////////////////
/*
Description:
Create a hatch from input geometry and parameters
Parameters:
plane [I] - ON_Plane to make the hatch on
loops [I] - Array of boundary loops with the outer one first
pattern_index [I] - Index into the hatch table
pattern_rotation [I] - ccw in radians about plane origin
pattern_scale [I] - Scale factor for pattern definition
Returns:
true = success, false = failure
*/
bool Create( const ON_Plane& plane,
const ON_SimpleArray<const ON_Curve*> loops,
int pattern_index,
double pattern_rotation,
double pattern_scale);
/*
Description:
Get the plane defining the hatch's coordinate system
Parameters:
Returns:
the plane
*/
const ON_Plane& Plane() const;
/*
Description:
Set the plane defining the hatch's coordinate system
Parameters:
plane - [in] the plane to set
Returns:
*/
void SetPlane( const ON_Plane& plane);
/*
Description:
Gets the rotation applied to the hatch pattern
when it is mapped to the hatch's plane
Returns:
The rotation in radians
Remarks:
The pattern is rotated counter-clockwise around
the hatch's plane origin by this value
*/
double PatternRotation() const;
/*
Description:
Sets the rotation applied to the hatch pattern
when it is mapped to the hatch's plane
Parameters:
rotation - [in] The rotation in radians
Remarks:
The pattern is rotated counter-clockwise around
the hatch's plane origin by this value
*/
void SetPatternRotation( double rotation);
/*
Description:
Gets the scale applied to the hatch pattern
when it is mapped to the hatch's plane
Returns:
The scale
Remarks:
The pattern is scaled around
the hatch's plane origin by this value
*/
double PatternScale() const;
/*
Description:
Sets the scale applied to the hatch pattern
when it is mapped to the hatch's plane
Parameters:
scale - [in] The scale
Remarks:
The pattern is scaled around
the hatch's plane origin by this value
*/
void SetPatternScale( double scale);
/*
Description:
Get the number of loops used by this hatch
Parameters:
Returns:
the number of loops
*/
int LoopCount() const;
/*
Description:
Add a loop to the hatch
Parameters:
loop - [in] the loop to add. Memory management for the loop is managed
by this class.
Returns:
*/
void AddLoop( ON_HatchLoop* loop);
/*
Description:
Insert a loop to the hatch at the specified index
Parameters:
index - [in] zero based index of the position where insert the loop to.
loop - [in] the loop to insert. Memory management for the loop is managed
by this class on success.
Returns:
true if success
false if index is lower than 0 or greater than current loop count.
*/
bool InsertLoop( int index,
ON_HatchLoop* loop);
/*
Description:
Remove a loop in the hatch
Parameters:
loop - [in] zero based index of the loop to remove.
Returns:
true if success
*/
bool RemoveLoop( int index);
/*
Description:
Get the loop at index
Parameters:
index - [in] which loop to get
Returns:
pointer to loop at index
nullptr if index is out of range
*/
const ON_HatchLoop* Loop( int index) const;
/*
Description:
Get the 3d curve corresponding to loop[index]
Parameters:
index - [in] which loop to get
Returns:
pointer to 3d curve of loop at index
nullptr if index is out of range or curve can't be made
Caller deletes the returned curve
*/
ON_Curve* LoopCurve3d( int index) const;
/*
Description:
Get the index of the hatch's pattern
Parameters:
Returns:
index of the pattern
*/
int PatternIndex() const;
/*
Description:
Set the index of the hatch's pattern
Parameters:
index - [in] pattern index to set
Returns:
*/
void SetPatternIndex( int index);
// Basepoint functions added March 23, 2008 -LW
/*
Description:
Set 2d Base point for hatch pattern alignment.
Parameters:
basepoint - 2d point in hatch's ECS
*/
void SetBasePoint(ON_2dPoint basepoint);
/*
Description:
Set 3d Base point for hatch pattern alignment.
Parameters:
point - 3d WCS point
Remarks:
Projects point to hatch's plane and sets 2d point
*/
void SetBasePoint(ON_3dPoint point);
/*
Description:
Return 3d WCS point that lies on hatch's plane used for pattern origin.
*/
ON_3dPoint BasePoint() const;
/*
Description:
Return 2d ECS point used for pattern origin.
*/
ON_2dPoint BasePoint2d() const;
/*
Function added June 12 2008 LW
Description:
Remove all of the loops on the hatch and add the curves in 'loops' as new loops
Parameters:
loops - [in] An array of pointers to 2d or 3d curves
If the curves are 2d, add them to the hatch directly
If they are 3d, project them to the hatch's plane first
Returns:
true - success
false - no loops in input array or an error adding them
*/
bool ReplaceLoops(ON_SimpleArray<const ON_Curve*>& loops);
#if defined(OPENNURBS_GRADIENT_WIP)
/*
Description:
Returns gradient fill type for this hatch
*/
ON_GradientType GetGradientType() const;
/*
Description:
Set the gradient fill type for this hatch
*/
void SetGradientType(ON_GradientType gt);
/*
Description:
Get list of color stops used for gradient drawing.
*/
void GetGradientColors(ON_SimpleArray<ON_ColorStop>& colors) const;
/*
Description:
Set list of color stops used for gradient drawing.
*/
bool SetGradientColors(const ON_SimpleArray<ON_ColorStop>& colors);
/*
Description:
Get gradient repeat factor for gradient drawing.
> 1 repeat reflected number of times between start and end point
< -1 repeat wrap number of times between start and end point
any other value does not affect repeat on a gradient
*/
double GetGradientRepeat() const;
/*
Description:
Set gradient repeat factor for gradient drawing
> 1 repeat reflected number of times between start and end point
< -1 repeat wrap number of times between start and end point
any other value does not affect repeat on a gradient
Returns:
True if the repeat factor was successfully set
*/
bool SetGradientRepeat(double repeat);
/*
Description:
Get the start and end points for gradient drawing in 3d
*/
void GetGradientEndPoints(ON_3dPoint& startPoint, ON_3dPoint& endPoint) const;
/*
Description:
Set the start and end points for gradient drawing
*/
bool SetGradientEndPoints(ON_3dPoint startpoint, ON_3dPoint endPoint);
#endif
private:
ON_Plane m_plane;
double m_pattern_scale = 1.0;
double m_pattern_rotation = 0.0;
ON_2dPoint m_basepoint = ON_2dPoint::Origin;
ON_SimpleArray<ON_HatchLoop*> m_loops;
int m_pattern_index = -1;
};
//Part of a boundary. An element has a curve subdomain and a flag to say
//whether that piece of curve should be reversed
class ON_CLASS ON_CurveRegionBoundaryElement
{
public :
ON_CurveRegionBoundaryElement();
ON_CurveRegionBoundaryElement(const ON_CurveRegionBoundaryElement& src);
~ON_CurveRegionBoundaryElement();
ON_CurveRegionBoundaryElement& operator=(const ON_CurveRegionBoundaryElement& src);
int m_curve_id;
ON_Interval m_subdomain;
bool m_bReversed;
};
//A list of curve subdomains that form a closed boundary with active space on the left.
typedef ON_ClassArray<ON_CurveRegionBoundaryElement> ON_CurveRegionBoundary;
//A list of region boundaries that bound a single connected region of the plane.
//The first boundary is always the outer boundary.
typedef ON_ClassArray<ON_CurveRegionBoundary> ON_CurveRegion;
#endif
@@ -0,0 +1,106 @@
#if !defined(ON_COMPILING_OPENNURBS_HSORT_FUNCTIONS)
/*
See opennurbs_sort.cpp for examples of using openurbs_hsort_template.c
to define type specific heap sort functions.
*/
#error Do not compile openurbs_hsort_template.c directly.
#endif
// ON_SORT_TEMPLATE_TYPE -> double, int, ....
#if !defined(ON_SORT_TEMPLATE_TYPE)
#error Define ON_SORT_TEMPLATE_TYPE macro before including opennurbs_qsort_template.c
#endif
#if !defined(ON_HSORT_FNAME)
#error Define ON_HSORT_FNAME macro before including opennurbs_qsort_template.c
#endif
#if defined(ON_SORT_TEMPLATE_COMPARE)
// use a compare function like strcmp for char* strings
#define ON_HSORT_GT(A,B) ON_SORT_TEMPLATE_COMPARE(A,B) > 0
#define ON_HSORT_GT_TMP(A) ON_SORT_TEMPLATE_COMPARE(A,&tmp) > 0
#else
// use type compares
#define ON_HSORT_GT(A,B) *A > *B
#define ON_HSORT_GT_TMP(A) *A > tmp
#endif
#if defined(ON_SORT_TEMPLATE_USE_MEMCPY)
#define ON_HSORT_TO_TMP(A) memcpy(&tmp,A,sizeof(tmp))
#define ON_HSORT_FROM_TMP(A) memcpy(A,&tmp,sizeof(tmp))
#define ON_HSORT_COPY(dst,src) memcpy(dst,src,sizeof(tmp))
#else
#define ON_HSORT_TO_TMP(A) tmp = *A
#define ON_HSORT_FROM_TMP(A) *A = tmp
#define ON_HSORT_COPY(dst,src) *dst = *src
#endif
#if defined(ON_SORT_TEMPLATE_STATIC_FUNCTION)
static
#endif
void
ON_HSORT_FNAME( ON_SORT_TEMPLATE_TYPE* base, size_t nel )
{
size_t i_end,k,i,j;
ON_SORT_TEMPLATE_TYPE* e_end;
ON_SORT_TEMPLATE_TYPE* e_i;
ON_SORT_TEMPLATE_TYPE* e_j;
ON_SORT_TEMPLATE_TYPE tmp;
if (0 == base || nel < 2)
return;
k = nel >> 1;
i_end = nel-1;
e_end = base + i_end;
for (;;)
{
if (k)
{
--k;
ON_HSORT_TO_TMP((base+k)); /* e_tmp = e[k]; */
}
else
{
ON_HSORT_TO_TMP(e_end); /* e_tmp = e[i_end]; */
ON_HSORT_COPY(e_end,base); /* e[i_end] = e[0]; */
if (!(--i_end))
{
ON_HSORT_FROM_TMP(base); /* e[0] = e_tmp; */
break;
}
e_end--;
}
i = k;
j = (k<<1) + 1;
e_i = base + i;
while (j <= i_end)
{
e_j = base + j;
if (j < i_end && ON_HSORT_GT((e_j+1),e_j) /*e[j] < e[j + 1] */)
{
j++;
e_j++;
}
if (ON_HSORT_GT_TMP(e_j) /* tmp < e[j] */)
{
ON_HSORT_COPY(e_i,e_j); /* e[i] = e[j]; */
i = j;
e_i = e_j;
j = (j<<1) + 1;
}
else
j = i_end + 1;
}
ON_HSORT_FROM_TMP(e_i); /* e[i] = e_tmp; */
}
}
#undef ON_HSORT_GT
#undef ON_HSORT_GT_TMP
#undef ON_HSORT_TO_TMP
#undef ON_HSORT_FROM_TMP
#undef ON_HSORT_COPY
#undef ON_HSORT_FROM_TMP
@@ -0,0 +1,43 @@
/*
//
// Copyright (c) 1993-2016 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_INPUT_LIBSDIR_INC_)
#define OPENNURBS_INPUT_LIBSDIR_INC_
#if defined(ON_COMPILER_MSC) && !defined(OPENNURBS_INPUT_LIBS_DIR)
// This header file insures OPENNURBS_INPUT_LIBS_DIR is defined to be
// the path to were the libraries opennurbs.dll links with are located.
// Examples of these libaries are zlib and freetype.
#if defined(OPENNURBS_OUTPUT_DIR)
// Typically, OPENNURBS_OUTPUT_DIR is defined in the
// MSBuild property sheet opennurbs_msbuild.Cpp.props.
#define OPENNURBS_INPUT_LIBS_DIR OPENNURBS_OUTPUT_DIR
#elif defined(RHINO_LIB_DIR)
// Typically, RHINO_LIB_DIR is defined in a Rhino module property sheet.
#define OPENNURBS_INPUT_LIBS_DIR RHINO_LIB_DIR
#else
// Please define OPENNURBS_INPUT_LIBS_DIR in your build environment
// Please do not modify the opennurbs vcxproj files. Instead use
// a property sheet (.props file), .sln file, or define it here.
#error You must define OPENNURBS_INPUT_LIBS_DIR
#endif
#endif
#endif
+790
View File
@@ -0,0 +1,790 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_INSTANCE_INC_)
#define OPENNURBS_INSTANCE_INC_
class ON_CLASS ON_ReferencedComponentSettings
{
public:
ON_ReferencedComponentSettings() = default;
~ON_ReferencedComponentSettings();
ON_ReferencedComponentSettings(const ON_ReferencedComponentSettings& src);
ON_ReferencedComponentSettings& operator=(const ON_ReferencedComponentSettings& src);
bool Read(
ON_BinaryArchive& archive
);
bool Write(
ON_BinaryArchive& archive
) const;
bool IsEmpty() const;
bool IsNotEmpty() const;
bool HasLayerInformation() const;
bool HasLayerTableInformation() const;
bool HasParentLayerInformation() const;
/*
Description:
Update runtime layer color visibility, locked, ... settings in the
layer table read from a refence file to the values to use in the
runtime model.
This is typically done right after the reference file layer table is
read and before the layers are added to the runtime model.
Parameters:
source_archive_manifest - [in]
manifest of archive being read (may partially read)
model_manifest - [in]
manifest of runtime model (may partially created)
layer_count - [in]
length of layers[] array;
layers - [in/out]
The input values should be the layer table read from the referenced file.
The output values have color, visibility, locked, ... settings updated
to the state they had the last time the model file (not the referenced file)
was saved.
linked_definition_parent_layer - [in/out]
If linked_definition_parent_layer is not nullptr, its color, visibility, ...
settings are updated to the state they had the last time the model file
(not the referenced file) was saved.
Remarks:
The layer idenitification information (name, index, id) are not changed by
this function.
*/
void AfterReferenceLayerTableRead(
const class ON_ComponentManifest& source_archive_manifest,
const class ON_ComponentManifest& model_manifest,
const class ON_ManifestMap& archive_to_model_map,
ON_Layer* linked_definition_parent_layer,
unsigned int layer_count,
ON_Layer** layers
);
/*
Description:
Update the mapping from from reference file layer id to runtime model layer id.
Typically this is done immediately after the reference file layers are added
to the runtime model.
Parameters:
source_archive_manifest - [in]
manifest of archive being read (may partially read)
model_manifest - [in]
manifest of runtime model (may partially created)
archive_to_model_map - [in]
Manifest map from reference file settings to runtime model settings.
This map typically exists while the archive is being read and is
destroyed after reading is complete. That's why the mapping has
to be saved.
*/
void AfterLayerTableAddedToModel(
const class ON_ComponentManifest& source_archive_manifest,
const class ON_ComponentManifest& model_manifest,
const class ON_ManifestMap& archive_to_model_map
);
/*
Description:
Save the current runtime layer color, visibility, ... states.
Typically this is done immediately before a linked instance definition
or worksession reference information is written. Calling the Write()
function destroys the information created by BeforeWrite() because
it is generally out-of-date if modeling resumes after writing.
Parameters:
model_manifest - [in]
manifest of runtime model
destination_archive_manifest - [in]
manifest of archive being written (may partially written)
model_to_archive_map - [in]
Manifest map from model to destination_archive_manifest.
linked_definition_parent_layer - [in]
nullptr or the parent layer
context - [in]
first parameter passed to ModelLayerFromIdFunc
ModelLayerFromIdFunc - [in]
Function to get model layers from id
*/
void BeforeLinkedDefinitionWrite(
const class ON_ComponentManifest& model_manifest,
const class ON_ComponentManifest& destination_archive_manifest,
const class ON_ManifestMap& model_to_archive_map,
const ON_Layer* linked_definition_parent_layer,
void* context,
const ON_Layer*(*ModelLayerFromIdFunc)(void* context, const ON_UUID&)
);
private:
class ON_ReferencedComponentSettingsImpl* Impl(
bool bCreateIfNull
);
class ON_ReferencedComponentSettingsImpl* m_impl = nullptr;
};
/*
Description:
An ON_InstanceDefinition defines the geometry used by
instance references.
See Also:
ON_InstanceRef
*/
class ON_CLASS ON_InstanceDefinition : public ON_ModelComponent
{
ON_OBJECT_DECLARE(ON_InstanceDefinition);
public:
// IDEF_UPDATE_TYPE lists the possible relationships between
// the instance definition geometry and the archive
// (m_source_archive) containing the original defition.
enum class IDEF_UPDATE_TYPE : unsigned int
{
Unset = 0,
Static = 1,
LinkedAndEmbedded = 2,
Linked = 3
//static_def = 0,
//embedded_def = 1,
// // As of 7 February, "static_def" and "embedded_def"
// // and shall be treated the same. Using "static_def"
// // is prefered and "embedded_def" is obsolete.
// // The geometry for the instance definition
// // is saved in archives, is fixed and has no
// // connection to a source archive.
// // All source archive information should be
// // empty strings and m_source_archive_checksum
// // shoule be "zero".
//linked_and_embedded_def = 2,
// // The geometry for the instance definition
// // is saved in archives. Complete source
// // archive and checksum information will be
// // present. The document setting
// // ON_3dmIOSettings.m_idef_link_update
// // determines if, when and how the instance
// // definition geometry is updated by reading the
// // source archive.
//linked_def = 3,
// // The geometry for this instance definition
// // is not saved in the archive that contains
// // this instance definition. This instance
// // definition geometry is imported from a
// // "source archive" The "source archive" file
// // name and checksum information are saved
// // in m_source_archive and m_source_archive_checksum.
// // If file named in m_source_archive is not available,
// // then this instance definition is not valid and any
// // references to it are not valid.
};
// Converts and integer into an IDEF_UPDATE_TYPE enum.
static ON_InstanceDefinition::IDEF_UPDATE_TYPE InstanceDefinitionTypeFromUnsigned(
unsigned int idef_type_as_unsigned
);
// Bits that identify subsets of the instance defintion
// fields. These bits are used to determine which fields to
// set when an ON_InstanceDefinition class is used to
// modify an existing instance definition.
enum
{
no_idef_settings = 0,
idef_name_setting = 1, // m_name
idef_description_setting = 2, // m_description
idef_url_setting = 4, // all m_url_* fields
idef_units_setting = 8, // m_us and m_unit_scale
idef_source_archive_setting = 0x10, // all m_source_*, layer style, update depth fields
idef_userdata_setting = 0x20,
all_idef_settings = 0xFFFFFFFF
};
public:
ON_InstanceDefinition() ON_NOEXCEPT;
~ON_InstanceDefinition();
ON_InstanceDefinition(const ON_InstanceDefinition&);
ON_InstanceDefinition& operator=(const ON_InstanceDefinition&);
private:
void Internal_Destroy();
void Internal_Copy(const ON_InstanceDefinition& src);
public:
static const ON_InstanceDefinition Unset;
/*
Parameters:
model_component_reference - [in]
none_return_value - [in]
value to return if ON_InstanceDefinition::Cast(model_component_ref.ModelComponent())
is nullptr
Returns:
If ON_InstanceDefinition::Cast(model_component_ref.ModelComponent()) is not nullptr,
that pointer is returned. Otherwise, none_return_value is returned.
*/
static const ON_InstanceDefinition* FromModelComponentRef(
const class ON_ModelComponentReference& model_component_reference,
const ON_InstanceDefinition* none_return_value
);
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
// virtual ON_Object::Dump override
void Dump(
ON_TextLog& text_log
) const override;
public:
bool Write(
ON_BinaryArchive& archive
) const override;
private:
bool Internal_WriteV5(
ON_BinaryArchive& archive
) const;
bool Internal_WriteV6(
ON_BinaryArchive& archive
) const;
public:
bool Read(
ON_BinaryArchive& archive
) override;
private:
bool Internal_ReadV5(
ON_BinaryArchive& archive
);
bool Internal_ReadV6(
ON_BinaryArchive& archive
);
public:
ON::object_type ObjectType() const override;
// virtual ON_Object:: override
unsigned int SizeOf() const override;
const ON_BoundingBox BoundingBox() const;
void SetBoundingBox( ON_BoundingBox bbox );
void ClearBoundingBox();
const ON_wString Description() const;
void SetDescription( const wchar_t* description );
const ON_wString URL() const;
void SetURL( const wchar_t* url );
const ON_wString URL_Tag() const;
void SetURL_Tag( const wchar_t* url_tag );
/*
Returns:
A list of object ids in the instance geometry table sorted by id.
*/
const ON_SimpleArray<ON_UUID>& InstanceGeometryIdList() const;
/*
Parameters:
instance_geometry_id_list - [in]
A list of object ids in the instance geometry table.
*/
void SetInstanceGeometryIdList(
const ON_SimpleArray<ON_UUID>& instance_geometry_id_list
);
/*
Description:
Remove all ids from the InstanceGeometryIdList().
*/
void ClearInstanceGeometryIdList();
/*
Description:
Remove id from the InstanceGeometryIdList().
*/
bool RemoveInstanceGeometryId(
ON_UUID id
);
/*
Description:
Remove InstanceGeometryIdList()[id_index] from the InstanceGeometryIdList() array.
*/
bool RemoveInstanceGeometryId(
int id_index
);
/*
Description:
Add id to the InstanceGeometryIdList().
Parameters:
id - [in]
non-nil id to add.
Returns:
True if id is not nil and was added to the InstanceGeometryIdList().
*/
bool AddInstanceGeometryId(
ON_UUID id
);
/*
Returns:
True if id is in the InstanceGeometryIdList().
*/
bool IsInstanceGeometryId(
ON_UUID id
) const;
private:
int Internal_InstanceGeometryIdIndex(
ON_UUID id
) const;
public:
/*
Parameters:
instance_definition_type - [in]
ON_InstanceDefinition::IDEF_UPDATE_TYPE::Unset - change the type to Unset
and remove all linked file information.
ON_InstanceDefinition::IDEF_UPDATE_TYPE::Static - change the type to Static
and remove all linked file information.
ON_InstanceDefinition::IDEF_UPDATE_TYPE::LinkedAndEmbedded - change
the type to from Linked to LinkedAndEmbedded. If the current type
is not Linked, then no changes are made.
ON_InstanceDefinition::IDEF_UPDATE_TYPE::Linked - change
the type to from LinkedAndEmbedded to Linked. If the current type
is not LinkedAndEmbedded, then no changes are made.
*/
bool SetInstanceDefinitionType(
const ON_InstanceDefinition::IDEF_UPDATE_TYPE instance_definition_type
);
/*
Parameters:
linked_definition_type - [in]
Either ON_InstanceDefinition::IDEF_UPDATE_TYPE::LinkedAndEmbedded
or ON_InstanceDefinition::IDEF_UPDATE_TYPE::Linked.
linked_file_reference - [in]
*/
bool SetLinkedFileReference(
ON_InstanceDefinition::IDEF_UPDATE_TYPE linked_definition_type,
ON_FileReference linked_file_reference
);
bool SetLinkedFileReference(
ON_InstanceDefinition::IDEF_UPDATE_TYPE linked_definition_type,
const wchar_t* linked_file_full_path
);
const ON_FileReference LinkedFileReference() const;
/*
Destroy all linked file path information and convert the type to Static.
*/
void ClearLinkedFileReference();
void ClearLinkedFileContentHash();
void ClearLinkedFileRelativePath();
const ON_wString& LinkedFilePath() const;
const ON_UnitSystem& UnitSystem() const;
public:
/*
Description:
Sets m_us and m_unit_scale.
*/
void SetUnitSystem( ON::LengthUnitSystem us );
void SetUnitSystem( const ON_UnitSystem& us );
/*
Returns:
True if this is a linked instance definition with
layer settings information.
*/
bool HasLinkedIdefReferenceComponentSettings() const;
void ClearLinkedIdefReferenceComponentSettings();
/*
Parameters:
bCreateIfNonePresent - [in]
When bCreateIfNonePresent is true and the idef type is ON_InstanceDefinition::IDEF_UPDATE_TYPE::Linked,
then ON_ReferencedComponentSettings will be created if none are present.
Return:
ON_ReferencedComponentSettings pointer or nullptr.
*/
const ON_ReferencedComponentSettings* LinkedIdefReferenceComponentSettings() const;
/*
Parameters:
bCreateIfNonePresent - [in]
When bCreateIfNonePresent is true and the idef type is ON_InstanceDefinition::IDEF_UPDATE_TYPE::Linked,
then ON_ReferencedComponentSettings will be created if none are present.
Return:
ON_ReferencedComponentSettings pointer or nullptr.
*/
ON_ReferencedComponentSettings* LinkedIdefReferenceComponentSettings(
bool bCreateIfNonePresent
);
public:
// OBSOLETE - change IdefUpdateType() to InstanceDefinitionType()
ON_InstanceDefinition::IDEF_UPDATE_TYPE IdefUpdateType() const;
ON_InstanceDefinition::IDEF_UPDATE_TYPE InstanceDefinitionType() const;
/*
Returns:
true if InstanceDefinitionType() = ON_InstanceDefinition::IDEF_UPDATE_TYPE::Linked or ON_InstanceDefinition::IDEF_UPDATE_TYPE::LinkedAndEmbedded.
*/
bool IsLinkedType() const;
/*
Description:
This property applies when an instance definiton is linked.
Returns:
true:
When reading the file that defines the content of the linked instance definition,
skip any linked instance definitions found in that file.
false:
When reading the file that defines the content of the linked instance definition,
recursively load linked instance definitions found in that file.
*/
bool SkipNestedLinkedDefinitions() const;
void SetSkipNestedLinkedDefinitions(
bool bSkipNestedLinkedDefinitions
);
private:
// list of object ids in the instance geometry table.
ON_SimpleArray<ON_UUID> m_object_uuid;
private:
ON_wString m_description;
ON_wString m_url;
ON_wString m_url_tag; // UI link text for m_url
private:
ON_BoundingBox m_bbox = ON_BoundingBox::EmptyBoundingBox;
private:
ON_UnitSystem m_us = ON_UnitSystem::None;
private:
// Note: the embedded_def type is obsolete.
// To avoid having to deal with this obsolete type in
// your code, using ON_InstanceDefintion::IdefUpdateType()
// to get this value. The IdefUpdateType() function
// with convert the obsolte value to the correct
// value.
ON_InstanceDefinition::IDEF_UPDATE_TYPE m_idef_update_type = ON_InstanceDefinition::IDEF_UPDATE_TYPE::Static;
private:
bool m_bSkipNestedLinkedDefinitions = false;
private:
/////////////////////////////////////////////////////////////
//
// linked instance definition internals
//
private:
ON_FileReference m_linked_file_reference;
// For V5 3dm archive compatibility.
// Set as needed by the Write() function for new idefs and saved if the idef is read from a V5 file.
private:
mutable ON_CheckSum m_linked_file_V5_checksum = ON_CheckSum::UnsetCheckSum;
private:
bool Internal_SetLinkedFileReference(
ON_InstanceDefinition::IDEF_UPDATE_TYPE linked_definition_type,
const ON_FileReference& linked_file_reference,
ON_CheckSum V5_checksum
);
// See comment for Internal_ReferencedComponentSettings() function.
private:
mutable class ON_ReferencedComponentSettings* m_linked_idef_component_settings = nullptr;
public:
/// <summary>
/// ON_InstanceDefinition::LinkedComponentStates specifies how model components
/// (layers, materials, dimension styles, ...) from linked instance defintion files
/// are appear in the active model.
/// </summary>
enum class eLinkedComponentAppearance : unsigned char
{
///<summary>
/// This is the only valid layer style when the instance definition type is
/// ON_InstanceDefinition::IDEF_UPDATE_TYPE::Static or
/// ON_InstanceDefinition::IDEF_UPDATE_TYPE::LinkedAndEmbedded.
/// This style is not valid when the instance definition type
/// ON_InstanceDefinition::IDEF_UPDATE_TYPE::Linked.
///</summary>
Unset = 0,
///<summary>
/// Model components (layers, materials, dimension styles, ...) from
/// linked instance definition files are embedded as ordinary components
/// in the active model.
/// This layer style may be used when the instance definition type is
/// ON_InstanceDefinition::IDEF_UPDATE_TYPE::Linked.
///</summary>
Active = 1,
///<summary>
/// Layers from the linked instance definition are reference components in the model.
/// This is the default layer style when the instance definition type is
/// ON_InstanceDefinition::IDEF_UPDATE_TYPE::Linked.
/// This layer style may be used when the instance definition type is
/// ON_InstanceDefinition::IDEF_UPDATE_TYPE::Linked.
///</summary>
Reference = 2
};
static ON_InstanceDefinition::eLinkedComponentAppearance LinkedComponentAppearanceFromUnsigned(
unsigned int linked_component_appearance_as_unsigned
);
ON_InstanceDefinition::eLinkedComponentAppearance LinkedComponentAppearance() const;
bool SetLinkedComponentAppearance(
ON_InstanceDefinition::eLinkedComponentAppearance linked_component_appearance
);
private:
ON_InstanceDefinition::eLinkedComponentAppearance m_linked_component_appearance = ON_InstanceDefinition::eLinkedComponentAppearance::Unset;
public:
/*
Returns:
A SHA-1 hash of these instance defintions properties:
InstanceGeometryIdList()
BoundingBox()
UnitSystem()
InstanceDefinitionType()
LinkedFileReference()
LinkedComponentAppearance()
*/
const ON_SHA1_Hash GeometryContentHash() const;
/*
Returns:
A SHA-1 hash of these instance defintions properties
Description()
URL()
URL_Tag()
and all the properties that contribute to the GeometryContentHash().
*/
const ON_SHA1_Hash ContentHash() const;
private:
void Internal_AccumulateHash() const;
private:
// Internal_AccumulateHash() uses lazy evaluation to set m_geometry_content_hash when needed.
mutable ON_SHA1_Hash m_geometry_content_hash = ON_SHA1_Hash::ZeroDigest;
// Internal_AccumulateHash() uses lazy evaluation to set m_content_hash when needed.
mutable ON_SHA1_Hash m_content_hash = ON_SHA1_Hash::ZeroDigest;
private:
// Increments content version number and sets hashes to ON_SHA1_Hash::ZeroDigest.
void Internal_ContentChanged();
private:
unsigned char m_reserved2A = 0;
unsigned char m_reserved2B = 0;
unsigned char m_reserved2C = 0;
private:
unsigned int m_reserved1 = 0;
private:
ON__UINT_PTR m_reserved_ptr = 0;
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_InstanceDefinition*>;
ON_DLL_TEMPLATE template class ON_CLASS ON_ObjectArray<ON_InstanceDefinition>;
#endif
/*
Description:
An ON_InstanceRef is a reference to an instance definition
along with transformation to apply to the definition.
See Also:
ON_InstanceRef
*/
class ON_CLASS ON_InstanceRef : public ON_Geometry
{
ON_OBJECT_DECLARE(ON_InstanceRef);
public:
ON_InstanceRef() = default;
~ON_InstanceRef() = default;
ON_InstanceRef(const ON_InstanceRef&) = default;
ON_InstanceRef& operator=(const ON_InstanceRef&) = default;
public:
/////////////////////////////////////////////////////////////
//
// virtual ON_Object overrides
//
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
bool Write(
ON_BinaryArchive& binary_archive
) const override;
bool Read(
ON_BinaryArchive& binary_archive
) override;
ON::object_type ObjectType() const override;
/////////////////////////////////////////////////////////////
//
// virtual ON_Geometry overrides
//
int Dimension() const override;
// virtual ON_Geometry GetBBox override
bool GetBBox( double* boxmin, double* boxmax, bool bGrowBox = false ) const override;
bool Transform(
const ON_Xform& xform
) override;
// virtual ON_Geometry::IsDeformable() override
bool IsDeformable() const override;
// virtual ON_Geometry::MakeDeformable() override
bool MakeDeformable() override;
/////////////////////////////////////////////////////////////
//
// Unique id of the instance definition (ON_InstanceDefinition)
// in the instance definition table that defines the geometry
// used by this reference.
ON_UUID m_instance_definition_uuid = ON_nil_uuid;
// Transformation for this reference.
ON_Xform m_xform = ON_Xform::IdentityTransformation;
// Bounding box for this reference.
ON_BoundingBox m_bbox;
#if 0
public:
/*
Remove all reference to the nested linked idef information.
*/
void ClearReferenceToNestedLinkedIdef();
/*
Returns:
true
if input was valid and the reference to the nested linked idef was set.
false
if reference to the nested linked idef was not set.
*/
bool SetReferenceToNestedLinkedIdef(
const ON_UUID& parent_idef_uuid,
const ON_FileReference& parent_reference_file,
const ON_FileReference& nested_reference_file
);
/*
Parameters:
parent_idef_uuid - [in]
The persistent id of the parent idef that contains the (possibly deeply nested)
instance definion this reference refers to.
parent_reference_file - [in]
the file for the parent idef.
nested_reference_file - [in]
if the referenced idef is itself linked, nested_reference_file identifies
the file.
Returns:
True if this is a reference to a nested linked idef.
*/
bool GetReferenceToNestedLinkedIdef(
ON_UUID& parent_idef_uuid,
ON_FileReference& parent_reference_file,
ON_FileReference& nested_reference_file
) const;
/*
Returns:
True if this is a reference to a nested linked idef.
*/
bool ContainsReferenceToNestedLinkedIdef() const;
private:
/////////////////////////////////////////////////////////////
//
// Additional information used when this reference is to
// an instance definition that is nested inside an ordinary
// linked instance definition.
//
// For example, if
// idefA = linked instance defintion referencing file A.
// idefX = any type of instance definition found in idefA.
//
// iref = model geometry reference to idefX.
//
// When A is not a 3dm file or the 3dm id of idefX is
// in use in the current model, the id of idefX will change
// every time A is read. This means saving the value of
// iref.m_instance_definition_uuid is not sufficient to identify
// idefX. In this case, the additional information
//
// iref.m_bReferenceToNestedLinkedIdef = true
// iref.m_parent_idef_uuid = idefA.Id()
// iref.m_parent_reference_file = idefA.FileReference().
// iref.m_nested_reference_file = idefX.FileReference().
//
// is used to identify idefX in a persistent way.
//
bool m_bReferenceToNestedLinkedIdef = false;
ON_UUID m_parent_idef_uuid = ON_nil_uuid; // persistent id
ON_FileReference m_parent_reference_file = ON_FileReference::Unset;
ON_FileReference m_nested_reference_file = ON_FileReference::Unset;
#endif
public:
// Tolerance to use for flagging instance xforms
// as singular.
// A valid ON_InstanceRef.m_xform satisfies:
// true == (m_xform.Inverse()*m_xform).IsIdentity(ON_InstanceRef::SingularTransformationTolerance)
static const double SingularTransformationTolerance;
};
#endif
@@ -0,0 +1,377 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_INTERNAL_V2_ANNOTATION_H_INC)
#define OPENNURBS_INTERNAL_V2_ANNOTATION_H_INC
#if defined(ON_COMPILING_OPENNURBS)
#include "opennurbs_internal_defines.h"
// Annotation classes used in version 2 .3dm archives and Rhino version 2.
// All classes in this file are obsolete. They exist so that old files can be read.
// Legacy annotation arrow is in some old .3dm files.
// Gets converted to an ON_Line with ON_3dmObjectAttributes arrow head
// ON_3dmObjectAttributes.m_object_decoration = (ON::end_arrowhead | other bits)
class ON_OBSOLETE_V2_AnnotationArrow : public ON_Geometry
{
// 3d annotation arrow
ON_OBJECT_DECLARE(ON_OBSOLETE_V2_AnnotationArrow);
public:
ON_OBSOLETE_V2_AnnotationArrow();
~ON_OBSOLETE_V2_AnnotationArrow();
ON_OBSOLETE_V2_AnnotationArrow(const ON_OBSOLETE_V2_AnnotationArrow&);
ON_OBSOLETE_V2_AnnotationArrow& operator=(const ON_OBSOLETE_V2_AnnotationArrow&);
/////////////////////////////////////////////////////////////////
//
// ON_Object overrides
//
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
void Dump( ON_TextLog& ) const override; // for debugging
bool Write(
ON_BinaryArchive& // serialize definition to binary archive
) const override;
bool Read(
ON_BinaryArchive& // restore definition from binary archive
) override;
ON::object_type ObjectType() const override;
/////////////////////////////////////////////////////////////////
//
// ON_Geometry overrides
//
int Dimension() const override;
// virtual ON_Geometry GetBBox override
bool GetBBox( double* boxmin, double* boxmax, bool bGrowBox = false ) const override;
bool Transform(
const ON_Xform&
) override;
/////////////////////////////////////////////////////////////////
//
// Interface
//
ON_3dVector Vector() const;
ON_3dPoint Head() const;
ON_3dPoint Tail() const;
ON_3dPoint m_tail;
ON_3dPoint m_head;
};
class ON_OBSOLETE_V2_TextDot : public ON_Point
{
// 3d annotation dot with text
ON_OBJECT_DECLARE(ON_OBSOLETE_V2_TextDot);
public:
ON_OBSOLETE_V2_TextDot();
~ON_OBSOLETE_V2_TextDot();
ON_OBSOLETE_V2_TextDot(const ON_OBSOLETE_V2_TextDot&);
ON_OBSOLETE_V2_TextDot& operator=(const ON_OBSOLETE_V2_TextDot&);
/////////////////////////////////////////////////////////////////
//
// ON_Object overrides
//
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
void Dump( ON_TextLog& ) const override; // for debugging
bool Write(
ON_BinaryArchive& // serialize definition to binary archive
) const override;
bool Read(
ON_BinaryArchive& // restore definition from binary archive
) override;
ON_wString m_text;
};
////////////////////////////////////////////////////////////////
//
// ON_OBSOLETE_V2_Annotation - used to serialize definitions of annotation
// objects (dimensions, text blocks, etc.).
//
class ON_OBSOLETE_V2_Annotation : public ON_Geometry
{
ON_OBJECT_DECLARE(ON_OBSOLETE_V2_Annotation);
protected:
ON_OBSOLETE_V2_Annotation() = default;
ON_OBSOLETE_V2_Annotation(const ON_OBSOLETE_V2_Annotation&) = default;
ON_OBSOLETE_V2_Annotation& operator=(const ON_OBSOLETE_V2_Annotation&) = default;
public:
virtual ~ON_OBSOLETE_V2_Annotation() = default;
protected:
void Internal_Initialize(); // initialize class's fields assuming
// memory is uninitialized
public:
static ON_OBSOLETE_V2_Annotation* CreateFromV5Annotation(
const class ON_OBSOLETE_V5_Annotation& V5_annotation,
const class ON_3dmAnnotationContext* annotation_context
);
static ON_OBSOLETE_V2_Annotation* CreateFromV6Annotation(
const class ON_Annotation& V6_annotation,
const class ON_3dmAnnotationContext* annotation_context
);
protected:
void Internal_InitializeFromV5Annotation(
const ON_OBSOLETE_V5_Annotation& V5_annotation,
const class ON_3dmAnnotationContext* annotation_context
);
public:
void Destroy();
void EmergencyDestroy();
/////////////////////////////////////////////////////////////////
//
// ON_Object overrides
//
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
void Dump( ON_TextLog& ) const override; // for debugging
bool Write(
ON_BinaryArchive& // serialize definition to binary archive
) const override;
bool Read(
ON_BinaryArchive& // restore definition from binary archive
) override;
ON::object_type ObjectType() const override;
/////////////////////////////////////////////////////////////////
//
// ON_Geometry overrides
//
int Dimension() const override;
// virtual ON_Geometry GetBBox override
bool GetBBox( double* boxmin, double* boxmax, bool bGrowBox = false ) const override;
bool Transform(
const ON_Xform&
) override;
/////////////////////////////////////////////////////////////////
//
// ON_OBSOLETE_V2_Annotation interface
//
// use these to get/set the current annotation settings
static const ON_3dmAnnotationSettings& AnnotationSettings();
static void SetAnnotationSettings( const ON_3dmAnnotationSettings* );
bool IsText() const;
bool IsLeader() const;
bool IsDimension() const;
virtual double NumericValue() const;
virtual void SetTextToDefault();
void SetType( ON_INTERNAL_OBSOLETE::V5_eAnnotationType type );
ON_INTERNAL_OBSOLETE::V5_eAnnotationType Type() const;
void SetTextDisplayMode( ON_INTERNAL_OBSOLETE::V5_TextDisplayMode mode);
ON_INTERNAL_OBSOLETE::V5_TextDisplayMode TextDisplayMode() const;
void SetPlane( const ON_Plane& plane );
ON_Plane Plane() const;
int PointCount() const;
void SetPoints( const ON_SimpleArray<ON_2dPoint>& points );
const ON_SimpleArray<ON_2dPoint>& Points() const;
void SetPoint( int idx, ON_3dPoint point );
ON_2dPoint Point( int idx ) const;
void SetUserText( const wchar_t* string );
const ON_wString& UserText() const;
void SetDefaultText( const wchar_t* string );
const ON_wString& DefaultText() const;
void SetUserPositionedText( int bUserPositionedText );
bool UserPositionedText() const;
// to convert world 3d points to and from annotation 2d points
bool GetECStoWCSXform( ON_Xform& xform ) const;
bool GeWCStoECSXform( ON_Xform& xform ) const;
ON_INTERNAL_OBSOLETE::V5_eAnnotationType m_type = ON_INTERNAL_OBSOLETE::V5_eAnnotationType::dtNothing; // enum for type of annotation
// DimLinear, DimRadius, etc.
ON_INTERNAL_OBSOLETE::V5_TextDisplayMode m_textdisplaymode = ON_INTERNAL_OBSOLETE::V5_TextDisplayMode::kNormal; // how the text is displayed
// Horizontal, InLine, AboveLine
ON_Plane m_plane = ON_Plane::World_xy; // ECS reference plane in WCS coordinates
ON_SimpleArray<ON_2dPoint> m_points; // Definition points for the dimension
ON_wString m_usertext; // "<>", or user override
ON_wString m_defaulttext; // The displayed text string
bool m_userpositionedtext = false; // true: User has positioned text
// false: use default location
};
class ON_OBSOLETE_V2_DimLinear : public ON_OBSOLETE_V2_Annotation
{
ON_OBJECT_DECLARE(ON_OBSOLETE_V2_DimLinear);
public:
ON_OBSOLETE_V2_DimLinear();
ON_OBSOLETE_V2_DimLinear(const ON_OBSOLETE_V2_DimLinear&);
~ON_OBSOLETE_V2_DimLinear();
ON_OBSOLETE_V2_DimLinear& operator=(const ON_OBSOLETE_V2_DimLinear&);
double NumericValue() const override;
void SetTextToDefault() override;
void EmergencyDestroy();
static ON_OBSOLETE_V2_DimLinear* CreateFromV5LinearDimension(
const class ON_OBSOLETE_V5_DimLinear& V5_linear_dimension,
const class ON_3dmAnnotationContext* annotation_context,
ON_OBSOLETE_V2_DimLinear* destination
);
};
class ON_OBSOLETE_V2_DimRadial : public ON_OBSOLETE_V2_Annotation
{
ON_OBJECT_DECLARE(ON_OBSOLETE_V2_DimRadial);
public:
ON_OBSOLETE_V2_DimRadial();
ON_OBSOLETE_V2_DimRadial(const ON_OBSOLETE_V2_DimRadial&);
~ON_OBSOLETE_V2_DimRadial();
ON_OBSOLETE_V2_DimRadial& operator=(const ON_OBSOLETE_V2_DimRadial&);
double NumericValue() const override;
void SetTextToDefault() override;
void EmergencyDestroy();
static ON_OBSOLETE_V2_DimRadial* CreateFromV5RadialDimension(
const class ON_OBSOLETE_V5_DimRadial& V5_linear_dimension,
const class ON_3dmAnnotationContext* annotation_context,
ON_OBSOLETE_V2_DimRadial* destination
);
};
class ON_OBSOLETE_V2_DimAngular : public ON_OBSOLETE_V2_Annotation
{
ON_OBJECT_DECLARE(ON_OBSOLETE_V2_DimAngular);
public:
ON_OBSOLETE_V2_DimAngular();
ON_OBSOLETE_V2_DimAngular(const ON_OBSOLETE_V2_DimAngular&);
~ON_OBSOLETE_V2_DimAngular();
ON_OBSOLETE_V2_DimAngular& operator=(const ON_OBSOLETE_V2_DimAngular&);
static ON_OBSOLETE_V2_DimAngular* CreateFromV5AngularDimension(
const class ON_OBSOLETE_V5_DimAngular& V5_angular_dimension,
const class ON_3dmAnnotationContext* annotation_context,
ON_OBSOLETE_V2_DimAngular* destination
);
void EmergencyDestroy();
bool Write( ON_BinaryArchive& file ) const override;
bool Read( ON_BinaryArchive& file ) override;
void SetAngle( double angle ) { m_angle = angle; }
double Angle() const { return m_angle; }
void SetRadius( double radius ) { m_radius = radius; }
double Radius() const { return m_radius; }
double NumericValue() const override;
void SetTextToDefault() override;
private:
double m_angle; // angle being dimensioned
double m_radius; // radius for dimension arc
};
class ON_OBSOLETE_V2_TextObject : public ON_OBSOLETE_V2_Annotation
{
ON_OBJECT_DECLARE(ON_OBSOLETE_V2_TextObject);
public:
ON_OBSOLETE_V2_TextObject();
ON_OBSOLETE_V2_TextObject(const ON_OBSOLETE_V2_TextObject&);
~ON_OBSOLETE_V2_TextObject();
ON_OBSOLETE_V2_TextObject& operator=(const ON_OBSOLETE_V2_TextObject&);
static ON_OBSOLETE_V2_TextObject* CreateFromV5TextObject(
const class ON_OBSOLETE_V5_TextObject& V5_text_object,
const class ON_3dmAnnotationContext* annotation_context,
ON_OBSOLETE_V2_TextObject* destination
);
void EmergencyDestroy();
bool Write( ON_BinaryArchive& file ) const override;
bool Read( ON_BinaryArchive& file ) override;
void SetFaceName( ON_wString string ) { m_facename = string; }
ON_wString FaceName() const { return m_facename; }
void SetFontWeight( int weight ) { m_fontweight = weight; }
int FontWeight() const { return m_fontweight; }
void SetHeight( double height ) { m_height = height; }
double Height() const { return m_height; }
private:
ON_wString m_facename;
int m_fontweight; // windows - 400 = NORMAL )
double m_height; // gets multiplied by dimscale
};
class ON_OBSOLETE_V2_Leader : public ON_OBSOLETE_V2_Annotation
{
ON_OBJECT_DECLARE(ON_OBSOLETE_V2_Leader);
public:
ON_OBSOLETE_V2_Leader();
ON_OBSOLETE_V2_Leader(const ON_OBSOLETE_V2_Leader&);
~ON_OBSOLETE_V2_Leader();
ON_OBSOLETE_V2_Leader& operator=(const ON_OBSOLETE_V2_Leader&);
static ON_OBSOLETE_V2_Leader* CreateFromV5Leader(
const class ON_OBSOLETE_V5_Leader& V5_leader,
const class ON_3dmAnnotationContext* annotation_context,
ON_OBSOLETE_V2_Leader* destination
);
void EmergencyDestroy();
};
#endif
#endif
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,731 @@
/*
//
// Copyright (c) 1993-2017 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_INTERNAL_V5_DIMSTYLE_INC_)
#define OPENNURBS_INTERNAL_V5_DIMSTYLE_INC_
#include "opennurbs_internal_defines.h"
#if defined(ON_COMPILING_OPENNURBS)
// ON_V5x_DimStyle is used to read and write version 5 and earlier archives.
// ON_DimStyle is the class for runtime dimension style.
class ON_V5x_DimStyle : public ON_ModelComponent
{
ON_OBJECT_DECLARE(ON_V5x_DimStyle);
private:
friend class ON_DimStyle;
public:
enum eArrowType
{
// eArrowType is used for V5 and earlier dimensions
// V6 dimensions (ON_Dimension) use ON_Arrowhead::arrow_type
solidtriangle = 0, // 2:1
dot = 1,
tick = 2,
shorttriangle = 3, // 1:1
arrow = 4,
rectangle = 5,
longtriangle = 6, // 4:1
longertriangle = 7, // 6:1
};
public:
ON_V5x_DimStyle();
~ON_V5x_DimStyle();
ON_V5x_DimStyle(const ON_V5x_DimStyle&) = default;
ON_V5x_DimStyle& operator=(const ON_V5x_DimStyle&) = default;
public:
ON_V5x_DimStyle( const class ON_3dmAnnotationSettings& src);
ON_V5x_DimStyle(
ON::LengthUnitSystem model_length_unit_system,
const class ON_DimStyle& src
);
public:
bool CompareDimstyle(const ON_V5x_DimStyle& src) const;
bool CompareValidFields(const ON_V5x_DimStyle& src) const;
//////////////////////////////////////////////////////////////////////
//
// ON_Object overrides
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
// virtual
void Dump( ON_TextLog& ) const override; // for debugging
// virtual
bool Write(
ON_BinaryArchive& // serialize definition to binary archive
) const override;
// virtual
bool Read(
ON_BinaryArchive& // restore definition from binary archive
) override;
// When a V5 file is being read into v6
// Copy the fields that were in DimstyleExtra in v5 into the v6 dimstyle
// that now contains the fields that were in DimstyleExtra
///void ConsolidateDimstyleExtra();
bool AttachDimstyleExtra();
bool Write_v5(
ON_BinaryArchive& // serialize definition to binary archive
) const;
private:
bool Internal_Read_v5(
ON_BinaryArchive& // restore definition from binary archive
);
//bool Write_v6(
// ON_BinaryArchive& // serialize definition to binary archive
// ) const;
bool Internal_Read_v6(
ON_BinaryArchive& // restore definition from binary archive
);
public:
void EmergencyDestroy();
//////////////////////////////////////////////////////////////////////
//
// Interface
void SetDefaultsNoExtension();
double ExtExtension() const;
void SetExtExtension( const double);
double ExtOffset() const;
void SetExtOffset( const double);
double ArrowSize() const;
void SetArrowSize( const double);
double LeaderArrowSize() const;
void SetLeaderArrowSize( const double);
double CenterMark() const;
void SetCenterMark( const double);
ON_INTERNAL_OBSOLETE::V5_TextDisplayMode TextAlignment() const;
void SetTextAlignment( ON_INTERNAL_OBSOLETE::V5_TextDisplayMode);
int ArrowType() const; // For ON_OBSOLETE_V2_Annotation & ON_OBSOLETE_V5_Annotation derived dimensions
void SetArrowType( eArrowType); // ON_Dimension derived dimensions use ArrowType1() and ArrowType2()
int LeaderArrowType() const;
void SetLeaderArrowType( eArrowType);
int AngularUnits() const;
void SetAngularUnits( int);
int LengthFormat() const;
void SetLengthFormat( int);
int AngleFormat() const;
void SetAngleFormat( int);
int LengthResolution() const;
void SetLengthResolution( int);
int AngleResolution() const;
void SetAngleResolution( int);
const class ON_TextStyle& V5TextStyle() const;
void SetV5TextStyle(
const class ON_TextStyle& v5_text_style
);
double TextGap() const;
void SetTextGap( double gap);
double TextHeight() const;
void SetTextHeight( double height);
double LengthFactor() const;
void SetLengthFactor( double);
bool Alternate() const;
void SetAlternate( bool);
double AlternateLengthFactor() const;
void SetAlternateLengthFactor( double);
int AlternateLengthFormat() const;
void SetAlternateLengthFormat( int);
int AlternateLengthResolution() const;
void SetAlternateLengthResolution( int);
int AlternateAngleFormat() const;
void SetAlternateAngleFormat( int);
int AlternateAngleResolution() const;
void SetAlternateAngleResolution( int);
void GetPrefix( ON_wString& ) const;
const wchar_t* Prefix() const;
void SetPrefix( const wchar_t*);
void SetPrefix( wchar_t*);
void GetSuffix( ON_wString& ) const;
const wchar_t* Suffix() const;
void SetSuffix( const wchar_t*);
void SetSuffix( wchar_t*);
void GetAlternatePrefix( ON_wString& ) const;
const wchar_t* AlternatePrefix() const;
void SetAlternatePrefix( const wchar_t*);
void SetAlternatePrefix( wchar_t*);
void GetAlternateSuffix( ON_wString& ) const;
const wchar_t* AlternateSuffix() const;
void SetAlternateSuffix( const wchar_t*);
void SetAlternateSuffix( wchar_t*);
bool SuppressExtension1() const;
void SetSuppressExtension1( bool);
bool SuppressExtension2() const;
void SetSuppressExtension2( bool);
// Don't change these enum values
// They are used in file reading & writing
enum class Field : unsigned int
{
fn_name = 0,
fn_index = 1,
fn_extextension = 2,
fn_extoffset = 3,
fn_arrowsize = 4,
fn_centermark = 5,
fn_textgap = 6,
fn_textheight = 7,
fn_textalign = 8,
fn_arrowtype = 9, // For v5 and previous ON_OBSOLETE_V2_Annotation and ON_OBSOLETE_V5_Annotation dimensions
fn_angularunits = 10,
fn_lengthformat = 11,
fn_angleformat = 12,
fn_angleresolution = 13,
fn_lengthresolution = 14,
fn_fontindex = 15,
fn_lengthfactor = 16,
fn_bAlternate = 17,
fn_alternate_lengthfactor = 18,
fn_alternate_lengthformat = 19,
fn_alternate_lengthresolution = 20,
fn_alternate_angleformat = 21,
fn_alternate_angleresolution = 22,
fn_prefix = 23,
fn_suffix = 24,
fn_alternate_prefix = 25,
fn_alternate_suffix = 26,
fn_dimextension = 27,
fn_leaderarrowsize = 28,
fn_leaderarrowtype = 29,
fn_suppressextension1 = 30,
fn_suppressextension2 = 31,
fn_last = 32, // not used - left here for sdk
// Added for v5 - 5/01/07 LW
// version 1.6
fn_overall_scale = 33,
fn_ext_line_color_source = 34,
fn_dim_line_color_source = 35,
fn_arrow_color_source = 36,
fn_text_color_source = 37,
fn_ext_line_color = 38,
fn_dim_line_color = 39,
fn_arrow_color = 40,
fn_text_color = 41,
fn_ext_line_plot_color_source = 42,
fn_dim_line_plot_color_source = 43,
fn_arrow_plot_color_source = 44,
fn_text_plot_color_source = 45,
fn_ext_line_plot_color = 46,
fn_dim_line_plot_color = 47,
fn_arrow_plot_color = 48,
fn_text_plot_color = 49,
fn_ext_line_plot_weight_source = 50,
fn_dim_line_plot_weight_source = 51,
fn_ext_line_plot_weight_mm = 52,
fn_dim_line_plot_weight_mm = 53,
fn_tolerance_style = 54,
fn_tolerance_resolution = 55,
fn_tolerance_upper_value = 56,
fn_tolerance_lower_value = 57,
fn_tolerance_height_scale = 58,
fn_baseline_spacing = 59,
// Added for v5 - 12/15/09 LW
// version 1.7
fn_draw_mask = 60,
fn_mask_color_source = 61,
fn_mask_color = 62,
fn_mask_border = 63,
// Added for v5 - 12/17/09 LW
// version 1.8
fn_dimscale = 64,
fn_dimscale_source = 65,
// Added for V6 -
// version 2.0
fn_fixed_extension_len = 66,
fn_fixed_extension_on = 67,
fn_text_rotation = 68,
fn_tolerance_alt_resolution = 69,
fn_tolerance_textheight_fraction = 70,
fn_suppress_arrow1 = 71,
fn_suppress_arrow2 = 72,
fn_textmove_leader = 73,
fn_arclength_sym = 74,
fn_stack_textheight_fraction = 75,
fn_stack_format = 76,
fn_alt_round = 77,
fn_round = 78,
fn_alt_zero_suppress = 79,
fn_tol_zero_suppress = 80,
fn_ang_zero_suppress = 81,
fn_zero_suppress = 82,
fn_alt_below = 83,
fn_dim_arrow_type1 = 84, // For ON_Dimension derived dimensions
fn_dim_arrow_type2 = 85,
fn_dim_arrow_blockname1 = 86,
fn_dim_arrow_blockname2 = 87,
FieldCount,
fn_unset = 0xFFFE,
fn_really_last = 0xFFFF
};
enum : unsigned int
{
// must be 1 + the maximum value of an ON_V5x_DimStyle::Field enum value.
FieldCount = 88
};
// Combines a field id and a field value
// Dimensions will have an array of DimstyleField's to record
// dimension style overrides for individual dimensions
class DimstyleField
{
public:
DimstyleField()
: m_next(nullptr)
, m_field_id(ON_V5x_DimStyle::Field::fn_unset)
{
m_val.s_val = nullptr;
}
~DimstyleField()
{
if (nullptr != m_next)
{
delete m_next;
m_next = nullptr;
}
if (nullptr != m_val.s_val)
{
delete m_val.s_val;
m_val.s_val = nullptr;
}
}
DimstyleField* m_next;
ON_V5x_DimStyle::Field m_field_id;
union
{
bool b_val;
int i_val;
unsigned char uc_val;
double d_val;
unsigned int c_val;
const ON_wString* s_val;
} m_val;
};
// added version 1.3
double DimExtension() const;
void SetDimExtension( const double);
// This section Added for v5 - 4-24-07 LW
// version 1.6
// Test if a specific field has been set in this dimstyle
// and not inherited from its parent.
bool IsFieldOverride(ON_V5x_DimStyle::Field field_id) const;
// Set a field to be overridden or not
// Fields that aren't overrides inherit from their parent dimstyle
void SetFieldOverride(ON_V5x_DimStyle::Field field_id, bool bOverride);
/*
Clear all field overrides
*/
void ClearAllFieldOverrides();
// Test if the dimstyle has any field override flags set
bool HasOverrides() const;
// Change the fields in this dimstyle to match the fields of the
// source dimstyle for all of the fields that are marked overridden in the source
// and to match the parent for all of the fields not marked overriden.
// Returns true if any overrides were set.
bool OverrideFields( const ON_V5x_DimStyle& source, const ON_V5x_DimStyle& parent);
//
// Change the fields in this dimstyle to match the fields of the
// parent dimstyle for all of the fields that are not marked overridden in the
// target dimstyle.
// This is the complement of OverrideFields()
bool InheritFields( const ON_V5x_DimStyle& parent);
// Test if this dimstyle is the child of any other dimstyle
bool IsChildDimstyle() const;
// Test if this dimstyle is the child of a given dimstyle
// A dimstyle may have several child dimstyles, but only one parent
bool IsChildOf(const ON_UUID& parent_uuid) const;
// use ON_ModelComponent parent id - // ON_UUID ParentId() const;
// Set the parent of this dimstyle
// use ON_ModelComponent parent id - //void SetParentId(ON_UUID parent_uuid);
// Tolerances
// Tolerance style
// 0: None
// 1: Symmetrical
// 2: Deviation
// 3: Limits
// 4: Basic
enum eToleranceStyle
{
tsMin = 0,
tsNone = 0,
tsSymmetrical = 1,
tsDeviation = 2,
tsLimits = 3,
tsBasic = 4,
tsMax = 4
};
int ToleranceStyle() const;
int ToleranceResolution() const;
double ToleranceUpperValue() const;
double ToleranceLowerValue() const;
double ToleranceHeightScale() const;
double BaselineSpacing() const;
void SetToleranceStyle( int style);
void SetToleranceResolution( int resolution);
void SetToleranceUpperValue( double upper_value);
void SetToleranceLowerValue( double lower_value);
void SetToleranceHeightScale( double scale);
void SetBaselineSpacing( double spacing = false);
// Determines whether or not to draw a Text Mask
bool DrawTextMask() const;
void SetDrawTextMask(bool bDraw);
// Determines where to get the color to draw a Text Mask
// 0: Use background color of the viewport. Initially, gradient backgrounds will not be supported
// 1: Use the ON_Color returned by MaskColor()
int MaskColorSource() const;
void SetMaskColorSource(int source);
ON_Color MaskColor() const; // Only works right if MaskColorSource returns 1.
// Does not return viewport background color
void SetMaskColor(ON_Color color);
// Per DimStyle DimScale
void SetDimScaleSource(int source);
int DimScaleSource() const; // 0: Global DimScale, 1: DimStyle DimScale
void SetDimScale(double scale);
double DimScale() const;
// Offset for the border around text to the rectangle used to draw the mask
// This number * CRhinoAnnotation::TextHeight() for the text is the offset
// on each side of the tight rectangle around the text characters to the mask rectangle.
double MaskOffsetFactor() const;
void Scale( double scale);
// UUID of the dimstyle this was originally copied from
// so Restore Defaults has some place to look
void SetSourceDimstyle(ON_UUID source_uuid);
ON_UUID SourceDimstyle() const;
// ver 2.0 V6
void SetExtensionLineColorSource(const ON::object_color_source src);
ON::object_color_source ExtensionLineColorSource() const;
void SetDimensionLineColorSource(const ON::object_color_source src);
ON::object_color_source DimensionLineColorSource() const;
void SetArrowColorSource(const ON::object_color_source src);
ON::object_color_source ArrowColorSource() const;
void SetExtensionLineColor(ON_Color c);
ON_Color ExtensionLineColor() const;
void SetDimensionLineColor(ON_Color c);
ON_Color DimensionLineColor() const;
void SetArrowColor(ON_Color c);
ON_Color ArrowColor() const;
void SetTextColor(ON_Color c);
ON_Color TextColor() const;
void SetExtensionLinePlotColorSource(const ON::plot_color_source src);
ON::plot_color_source ExtensionLinePlotColorSource() const;
void SetDimensionLinePlotColorSource(const ON::plot_color_source src);
ON::plot_color_source DimensionLinePlotColorSource() const;
void SetArrowPlotColorSource(const ON::plot_color_source src);
ON::plot_color_source ArrowPlotColorSource() const;
void SetExtensionLinePlotColor(ON_Color c);
ON_Color ExtensionLinePlotColor() const;
void SetDimensionLinePlotColor(ON_Color c);
ON_Color DimensionLinePlotColor() const;
void SetArrowPlotColor(ON_Color c);
ON_Color ArrowPlotColor() const;
void SetTextPlotColor(ON_Color c);
ON_Color TextPlotColor() const;
void SetExtensionLinePlotWeightSource(const ON::plot_weight_source src);
ON::plot_weight_source ExtensionLinePlotWeightSource() const;
void SetDimensionLinePlotWeightSource(const ON::plot_weight_source src);
ON::plot_weight_source DimensionLinePlotWeightSource() const;
void SetExtensionLinePlotWeight(double w);
double ExtensionLinePlotWeight() const;
void SetDimensionLinePlotWeight(double w);
double DimensionLinePlotWeight() const;
void SetFixedExtensionLen(double l);
double FixedExtensionLen() const;
void SetFixedExtensionLenOn(bool on);
bool FixedExtensionLenOn() const;
void SetTextRotation(double r);
double TextRotation() const;
void SetAlternateToleranceResolution(int r);
int AlternateToleranceResolution() const;
//void SetAlternateTolHeightFraction(double f);
//double AltTolHeightFraction() const;
void SetSuppressArrow1(bool s);
bool SuppressArrow1() const;
void SetSuppressArrow2(bool s);
bool SuppressArrow2() const;
void SetTextMoveLeader(int m);
int TextMoveLeader() const;
void SetArcLengthSymbol(int m);
int ArcLengthSymbol() const;
void SetStackFractionFormat(int f);
int StackFractionFormat() const;
void SetStackHeightFraction(double f);
double StackHeightFraction() const;
void SetRoundOff(double r);
double RoundOff() const;
void SetAlternateRoundOff(double r);
double AlternateRoundOff() const;
void SetZeroSuppress(int s);
int ZeroSuppress() const;
void SetAlternateZeroSuppress(int s);
int AlternateZeroSuppress() const;
void SetToleranceZeroSuppress(int s);
int ToleranceZeroSuppress() const;
void SetAngleZeroSuppress(int s);
int AngleZeroSuppress() const;
void SetAlternateBelow(bool below);
bool AlternateBelow() const;
void SetArrowType1(ON_Arrowhead::arrow_type); // ON_Dimension derived dimensions
ON_Arrowhead::arrow_type ArrowType1() const;
void SetArrowBlockId1(ON_UUID id);
ON_UUID ArrowBlockId1() const;
void SetArrowType2(ON_Arrowhead::arrow_type);
ON_Arrowhead::arrow_type ArrowType2() const;
void SetArrowBlockId2(ON_UUID id);
ON_UUID ArrowBlockId2() const;
const ON_Arrowhead& Arrowhead1() const;
const ON_Arrowhead& Arrowhead2() const;
// Defaults for values stored in Userdata extension - needed to read and write pre-v6 files
static int DefaultToleranceStyle();
static int DefaultToleranceResolution();
static double DefaultToleranceUpperValue();
static double DefaultToleranceLowerValue();
static double DefaultToleranceHeightScale();
static double DefaultBaselineSpacing();
static bool DefaultDrawTextMask(); // false
static int DefaultMaskColorSource(); // 0;
static ON_Color DefaultMaskColor(); // .SetRGB(255,255,255);
static double DefaultDimScale(); // 1.0;
static int DefaultDimScaleSource(); // 0;
bool CompareFields(const ON_V5x_DimStyle& other) const;
public:
double m_extextension = 0.5; // extension line extension
double m_extoffset = 0.5; // extension line offset
double m_arrowsize = 1.0; // length of an arrow - may mean different things to different arrows
double m_centermark = 0.5; // size of the + at circle centers
double m_textgap = 0.25; // gap around the text for clipping dim line
double m_textheight = 1.0; // model unit height of dimension text before applying dimscale
ON_INTERNAL_OBSOLETE::V5_TextDisplayMode m_dimstyle_textalign = ON_INTERNAL_OBSOLETE::V5_TextDisplayMode::kAboveLine; // text alignment relative to the dimension line
int m_arrowtype = 0; // 0: filled narrow triangular arrow - For ON_OBSOLETE_V2_Annotation & ON_OBSOLETE_V5_Annotation derived dimensnions
// m_arrowtype = ((ON_Arrowhead::arrow_type enum value as int) - 2)
int m_angularunits = 0; // 0: degrees, 1: radians
int m_lengthformat = 0; // 0: decimal, 1: fractional, 2: feet & inches
int m_angleformat = 0; // 0: decimal degrees, 1:DMS, ...
int m_angleresolution = 2; // for decimal degrees, digits past decimal
int m_lengthresolution = 2; // depends on m_lengthformat
// for decimal, digits past the decimal point
private:
ON_TextStyle m_v5_text_style = ON_TextStyle::Default;
public:
// added fields version 1.2, Jan 13, 05
double m_lengthfactor = 1.0; // (dimlfac) model units multiplier for length display
bool m_bAlternate = false; // (dimalt) display alternate dimension string (or not)
// using m_alternate_xxx values
double m_alternate_lengthfactor = 1.0; // (dimaltf) model units multiplier for alternate length display
int m_alternate_lengthformat = 0; // 0: decimal, 1: feet, 2: feet & inches
int m_alternate_lengthresolution = 2; // depends on m_lengthformat
// for decimal, digits past the decimal point
int m_alternate_angleformat = 0; // 0: decimal degrees, ...
int m_alternate_angleresolution = 2; // for decimal degrees, digits past decimal
ON_wString m_prefix; // string preceding dimension value string
ON_wString m_suffix; // string following dimension value string
ON_wString m_alternate_prefix; // string preceding alternate value string
ON_wString m_alternate_suffix; // string following alternate value string
private:
///unsigned int m_valid = 0; // Obsolete deprecated field to be removed - Do not use
public:
// field added version 1.4, Dec 28, 05
double m_dimextension = 0.0; // (dimdle) dimension line extension past the "tip" location
// fields added version 1.5 Mar 23 06
double m_leaderarrowsize = 1.0; // Like dimension arrow size but applies to leaders
int m_leaderarrowtype = 0; // Like dimension arrow type but applies to leaders
bool m_bSuppressExtension1 = false; // flag to not draw extension lines
bool m_bSuppressExtension2 = false; // flag to not draw extension lines
private:
friend class ON_DimStyleExtra;
// 8 Apr, 2014 - The next few fields were transferred from ON_DimStyleExtra for V6
/// Use ON_ModelComponent.ParentId() /// ON_UUID m_parent_dimstyle = ON_nil_uuid; // ON_nil_uuid if there is no parent dimstyle
unsigned int m_field_override_count = 0; // number of
bool m_field_override[ON_V5x_DimStyle::FieldCount];
public:
int m_tolerance_style = 0;
int m_tolerance_resolution = 4;
double m_tolerance_upper_value = 0.0; // or both upper and lower in symmetrical style
double m_tolerance_lower_value = 0.0;
double m_tolerance_height_scale = 1.0; // relative to the main dimension text
double m_baseline_spacing = 1.0;
// Text mask - added Dec 12 2009
bool m_bDrawMask = false;
int m_mask_color_source = 0;
ON_Color m_mask_color = ON_Color::White;
// Per dimstyle DimScale added Dec 16, 2009
double m_dimscale = 1.0;
int m_dimscale_source = 0;
// 19 Oct 2010 - Added uuid of source dimstyle to restore defaults
ON_UUID m_source_dimstyle = ON_nil_uuid;
// End of fields that were in ON_DimStyleExtra
// Fields added for V6, ver 2.0
unsigned char m_ext_line_color_source = 0;
unsigned char m_dim_line_color_source = 0;
unsigned char m_arrow_color_source = 0;
unsigned char m_text_color_source = 0;
ON_Color m_ext_line_color = ON_Color::Black;
ON_Color m_dim_line_color = ON_Color::Black;
ON_Color m_arrow_color = ON_Color::Black;
ON_Color m_text_color = ON_Color::Black;
unsigned char m_ext_line_plot_color_source = 0;
unsigned char m_dim_line_plot_color_source = 0;
unsigned char m_arrow_plot_color_source = 0;
unsigned char m_text_plot_color_source = 0;
ON_Color m_ext_line_plot_color = ON_Color::Black;
ON_Color m_dim_line_plot_color = ON_Color::Black;
ON_Color m_arrow_plot_color = ON_Color::Black;
ON_Color m_text_plot_color = ON_Color::Black;
unsigned char m_ext_line_plot_weight_source = 0;
unsigned char m_dim_line_plot_weight_source = 0;
double m_ext_line_plot_weight_mm = 0.0;
double m_dim_line_plot_weight_mm = 0.0;
double m_fixed_extension_len = 1.0; // Fixed extension line length if m_fixed_extension_len_on is true
bool m_fixed_extension_len_on = false; // true: use fixed_extension_len, false: don't use m_fixed_extension_len
double m_text_rotation = 0.0; // Dimension text rotation around text point (radians)
int m_alt_tol_resolution = 4; // for decimal, digits past the decimal point, fractions: 1/2^n
double m_tol_textheight_fraction = 1.0; // fraction of main text height
bool m_suppress_arrow1 = false; // false: dont suppress, true: suppress
bool m_suppress_arrow2 = false; // false: dont suppress, true: suppress
int m_textmove_leader = 0; // 0: move text anywhere, 1: add leader when moving text
int m_arclength_sym = 0; // 0: symbol before dim text, 1: symbol above dim text, no symbol
double m_stack_textheight_fraction = 1.0; // fraction of main text height
int m_stack_format = 0; // 0: no stacking, 1: horizontal, 2: diagonal
double m_alt_round = 0.0; // rounds to nearest specified value
double m_round = 0.0;
int m_alt_zero_suppress = 0; // 0: no zero suppressing
int m_tol_zero_suppress = 0; // 1: suppress zero feet
int m_zero_suppress = 0; // 2: suppress zero inches
int m_ang_zero_suppress = 0; // 3: suppress both zero feet and 0 inches
// 4: suppress leading zeros
// 8: suppress trailing zeros
// 12: suppress both leading and trailing zeros
bool m_alt_below = false; // true: display alternate text below main text
// true: display alternate text after main text
//ON_Arrowhead::arrow_type m_arrow_type_1; // Arrow types for ON_Dimension derived dimensions
//ON_Arrowhead::arrow_type m_arrow_type_2;
//ON_wString m_dim_arrow_block1;
//ON_wString m_dim_arrow_block2;
ON_Arrowhead m_arrow_1;
ON_Arrowhead m_arrow_2;
};
void ON_Internal_FixBogusDimStyleLengthFactor(
const class ON_BinaryArchive& file,
double& dimstyle_length_factor
);
#endif
#endif
@@ -0,0 +1,165 @@
/*
// Copyright (c) 1993-2017 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_INTERNAL_DEFINES_INC_)
#define OPENNURBS_INTERNAL_DEFINES_INC_
#if defined(ON_COMPILING_OPENNURBS)
class ON_INTERNAL_OBSOLETE
{
public:
//// OBSOLETE V5 Dimension Types ///////////////////////////////////////////////////////////
enum class V5_eAnnotationType : unsigned char
{
dtNothing,
dtDimLinear,
dtDimAligned,
dtDimAngular,
dtDimDiameter,
dtDimRadius,
dtLeader,
dtTextBlock,
dtDimOrdinate,
};
// convert integer to eAnnotationType enum
static ON_INTERNAL_OBSOLETE::V5_eAnnotationType V5AnnotationTypeFromUnsigned(
unsigned int v5_annotation_type_as_unsigned
);
//// dim text locations ///////////////////////////////////////////////////////////
enum class V5_TextDisplayMode : unsigned char
{
kNormal = 0, // antique name - triggers use of current default
kHorizontalToScreen = 1, // Horizontal to the screen
kAboveLine = 2,
kInLine = 3,
kHorizontalInCplane = 4 // horizontal in the dimension's plane
};
static ON_INTERNAL_OBSOLETE::V5_TextDisplayMode V5TextDisplayModeFromUnsigned(
unsigned int text_display_mode_as_unsigned
);
static ON_INTERNAL_OBSOLETE::V5_TextDisplayMode V5TextDisplayModeFromV6DimStyle(
const ON_DimStyle& V6_dim_style
);
/// <summary>
/// Attachment of content
/// </summary>
enum class V5_vertical_alignment : unsigned char
{
/// <summary>
/// Text centered on dimension line (does not apply to leaders or text)
/// </summary>
Centered = 0,
/// <summary>
/// Text above dimension line (does not apply to leaders or text)
/// </summary>
Above = 1,
/// <summary>
/// Text below dimension line (does not apply to leaders or text)
/// </summary>
Below = 2,
/// <summary>
/// Leader tail at top of text (does not apply to text or dimensions)
/// </summary>
Top = 3, // = TextVerticalAlignment::Top
/// <summary>
/// Leader tail at middle of first text line (does not apply to text or dimensions)
/// </summary>
FirstLine = 4, // = MiddleOfTop
/// <summary>
/// Leader tail at middle of text or content (does not apply to text or dimensions)
/// </summary>
Middle = 5, // = Middle
/// <summary>
/// Leader tail at middle of last text line (does not apply to text or dimensions)
/// </summary>
LastLine = 6, // = MiddleOfBottom
/// <summary>
/// Leader tail at bottom of text (does not apply to text or dimensions)
/// </summary>
Bottom = 7, // = Bottom
/// <summary>
/// Leader tail at bottom of text, text underlined (does not apply to text or dimensions)
/// </summary>
Underlined = 8 // Underlined
// nothing matched BottomOfTop
};
static ON_INTERNAL_OBSOLETE::V5_vertical_alignment V5VerticalAlignmentFromUnsigned(
unsigned int vertical_alignment_as_unsigned
);
static ON_INTERNAL_OBSOLETE::V5_vertical_alignment V5VerticalAlignmentFromV5Justification(
unsigned int v5_justification_bits
);
static ON_INTERNAL_OBSOLETE::V5_vertical_alignment V5VerticalAlignmentFromV6VerticalAlignment(
const ON::TextVerticalAlignment text_vertical_alignment
);
static ON::TextVerticalAlignment V6VerticalAlignmentFromV5VerticalAlignment(
ON_INTERNAL_OBSOLETE::V5_vertical_alignment V5_vertical_alignment
);
enum class V5_horizontal_alignment : unsigned char
{
/// <summary>
/// Left aligned
/// </summary>
Left = 0, // Left
/// <summary>
/// Centered
/// </summary>
Center = 1,
/// <summary>
/// Right aligned
/// </summary>
Right = 2,
/// <summary>
/// Determined by orientation
/// Primarily for leaders to make
/// text right align when tail is to the left
/// and left align when tail is to the right
/// </summary>
Auto = 3,
};
static ON_INTERNAL_OBSOLETE::V5_horizontal_alignment V5HorizontalAlignmentFromUnsigned(
unsigned int horizontal_alignment_as_unsigned
);
static ON_INTERNAL_OBSOLETE::V5_horizontal_alignment V5HorizontalAlignmentFromV5Justification(
unsigned int v5_justification_bits
);
static ON_INTERNAL_OBSOLETE::V5_horizontal_alignment V5HorizontalAlignmentFromV6HorizontalAlignment(
const ON::TextHorizontalAlignment text_horizontal_alignment
);
static ON::TextHorizontalAlignment V6HorizontalAlignmentFromV5HorizontalAlignment(
ON_INTERNAL_OBSOLETE::V5_horizontal_alignment V5_vertical_alignment
);
};
#endif
#endif
@@ -0,0 +1,261 @@
/*
//
// Copyright (c) 1993-2017 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_INTERNAL_GLYPH_INC_)
#define OPENNURBS_INTERNAL_GLYPH_INC_
class ON_Internal_FontGlyphPool : private ON_FixedSizePool
{
private:
friend class ON_FontGlyph;
friend class ON_GlyphMap;
ON_Internal_FontGlyphPool();
~ON_Internal_FontGlyphPool() = default;
ON_Internal_FontGlyphPool(const ON_Internal_FontGlyphPool&) = delete;
ON_Internal_FontGlyphPool operator=(const ON_Internal_FontGlyphPool&) = delete;
static ON_Internal_FontGlyphPool theGlyphItemPool;
};
class ON_ManagedFonts
{
public:
// List is the only instance of this class.
static ON_ManagedFonts List;
static const ON_FontList& InstalledFonts();
static const ON_FontList& ManagedFonts()
{
return List.m_managed_fonts;
}
const ON_Font* GetFromFontCharacteristics(
const ON_Font& font_characteristics,
bool bCreateIfNotFound
);
const ON_Font* GetFromSerialNumber(
unsigned int managed_font_runtime_serial_number
);
#if defined(ON_OS_WINDOWS_GDI)
static void Internal_GetWindowsInstalledFonts(ON_SimpleArray<const ON_Font*>&);
#endif
#if defined (ON_RUNTIME_APPLE_CORE_TEXT_AVAILABLE)
static void Internal_GetAppleInstalledCTFonts(ON_SimpleArray<const ON_Font*>& platform_font_list);
#endif
private:
static void Internal_SetFakeWindowsLogfontNames(
ON_SimpleArray<const ON_Font*>& device_list
);
static void Internal_SetFakeWindowsLogfontName(
const ON_Font* font,
const ON_wString fake_loc_logfont_name,
const ON_wString fake_en_logfont_name
);
public:
// sorts nulls to end of lists
static int CompareFontPointer(ON_Font const* const* lhs, ON_Font const* const* rhs);
/*
Returns:
0: failure
>0: success font glyph index
*/
static unsigned int GetGlyphMetricsInFontDesignUnits(
const class ON_Font* font,
ON__UINT32 unicode_code_point,
class ON_TextBox& glyph_metrics_in_font_design_units
);
/*
Parameters:
font - [in]
font_metrics_in_font_design_units - [out]
Returns:
True:
font_metrics_in_font_design_units set from a font installed on the
current device.
False:
ON_FontMetrics::LastResortMetrics used or other corrections applied.
*/
static bool GetFontMetricsInFontDesignUnits(
const ON_Font* font,
ON_FontMetrics& font_metrics_in_font_design_units
);
private:
// The purpose of this nondefault constructor is to create ON_ManagedFonts::List
// in opennurbs_statics.cpp in a way that Apple's CLang will actually compile.
// The only instance of ON_ManagedFonts is ON_ManagedFonts::List.
ON_ManagedFonts(ON__UINT_PTR zero);
~ON_ManagedFonts();
private:
ON_ManagedFonts() = delete;
ON_ManagedFonts(const ON_ManagedFonts&) = delete;
ON_ManagedFonts& operator=(const ON_ManagedFonts&) = delete;
private:
/*
Parameters:
managed_font_metrics_in_font_design_units - [in]
Pass nullptr if not available.
If not nullptr, then the values are assumed to be accurate
and the units are the font design units (not normalized).
*/
const ON_Font* Internal_AddManagedFont(
const ON_Font* managed_font,
const ON_FontMetrics* managed_font_metrics_in_font_design_units // can be nullptr
);
private:
ON__UINT_PTR m_default_font_ptr = 0;
private:
// Managed fonts used in annotation, etc.
// They may or may not be installed on this device
ON_FontList m_managed_fonts;
private:
// Fonts installed on this device
ON_FontList m_installed_fonts;
};
class ON_CLASS ON_GlyphMap
{
public:
ON_GlyphMap();
~ON_GlyphMap() = default;
public:
const class ON_FontGlyph* FindGlyph(
const ON__UINT32 unicode_code_point
) const;
// returns pointer to the persistent glyph item
const ON_FontGlyph* InsertGlyph(
const ON_FontGlyph& glyph
);
unsigned int GlyphCount() const;
private:
friend class ON_Font;
friend class ON_FontGlyph;
unsigned int m_glyph_count = 0;
mutable ON_SleepLock m_sleep_lock;
ON_SimpleArray< const class ON_FontGlyph* > m_glyphs;
};
#if defined(ON_OS_WINDOWS_GDI)
/*
Parameters:
glyph - [in]
font_metrics - [out]
font metrics in font design units
Returns:
>0: glyph index
0: failed
*/
ON_DECL
void ON_WindowsDWriteGetFontMetrics(
const ON_Font* font,
ON_FontMetrics& font_metrics
);
/*
Parameters:
glyph - [in]
glyph_metrics - [out]
Returns glyph metrics in font design units
Returns:
>0: glyph index
0: failed
*/
ON_DECL
unsigned int ON_WindowsDWriteGetGlyphMetrics(
const ON_FontGlyph* glyph,
ON_TextBox& glyph_metrics
);
/*
Parameters:
glyph - [in]
bSingleStrokeFont - [in]
outline - [out]
outline and metrics in font design units
*/
ON_DECL
bool ON_WindowsDWriteGetGlyphOutline(
const ON_FontGlyph* glyph,
ON_OutlineFigure::Type figure_type,
class ON_Outline& outline
);
#endif
#if defined(ON_RUNTIME_APPLE_CORE_TEXT_AVAILABLE)
/*
Parameters:
glyph - [in]
font_metrics - [out]
font metrics in font design units
Returns:
>0: glyph index
0: failed
*/
ON_DECL
void ON_AppleFontGetFontMetrics(
const ON_Font* font,
ON_FontMetrics& font_metrics
);
/*
Parameters:
glyph - [in]
glyph_metrics - [out]
Returns glyph metrics in font design units
Returns:
>0: glyph index
0: failed
*/
ON_DECL
unsigned int ON_AppleFontGetGlyphMetrics(
const ON_FontGlyph* glyph,
ON_TextBox& glyph_metrics
);
/*
Parameters:
glyph - [in]
figure_type - [in]
Pass ON_OutlineFigure::Type::Unset if not known.
outline - [out]
outline and metrics in font design units
*/
ON_DECL
bool ON_AppleFontGetGlyphOutline(
const ON_FontGlyph* glyph,
ON_OutlineFigure::Type figure_type,
class ON_Outline& outline
);
#endif
#endif
@@ -0,0 +1,151 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_INTERNAL_UNICODE_CP_INC_)
#define OPENNURBS_INTERNAL_UNICODE_CP_INC_
#if !defined(ON_COMPILING_OPENNURBS)
// This check is included in all opennurbs source .c and .cpp files to insure
// ON_COMPILING_OPENNURBS is defined when opennurbs source is compiled.
// When opennurbs source is being compiled, ON_COMPILING_OPENNURBS is defined
// and the opennurbs .h files alter what is declared and how it is declared.
#error ON_COMPILING_OPENNURBS must be defined when compiling opennurbs
#endif
#if !defined(ON_RUNTIME_WIN)
#error Do not use for Windows builds.
#endif
#if !defined(ON_RUNTIME_WIN)
// When we do not have access to Windows code page tools,
// we have to add in code to get convert Windows and Apple
// multibyte encodings to UNICODE encodings.
//
// In practice, the primary use of the double byte code page support
// is in parsing rich text (RTF) in ON_TextContent classes created
// on computers with Eastern European and Asian locales as the default
// locale.
//
// Many Western European and Americas locales are handled by the
// single byte code pages 1252 and 10000. Code pages for other
// locales will be added as needed because embedding the large
// double byte tables makes the resulting libraries large.
//
// At this time opennurbs does not ship the
// code page N to UNICODE translation tables as separate files
// that can be loaded on demand because of the added installation
// and runtime lookup complexities.
//
// When possible, Rhino and opennurbs replace code page
// encodings with UNICODE in RTF. All runtimes strings
// use UNICODE UTF-8, UTF-16, or UTF-32 encodings.
// Whenever posssible, the UNICODE encoding is used
// to retrieve glyph information from fonts.
#define ON_DOUBLE_BYTE_CODE_PAGE_SUPPORT
#endif
#if defined(ON_DOUBLE_BYTE_CODE_PAGE_SUPPORT)
/////////////////////////////////////////////////////////
//
// Code page 932
//
bool ON_IsPotentialWindowsCodePage932SingleByteEncoding(
ON__UINT32 x
);
bool ON_IsPotentialWindowsCodePage932DoubleByteEncoding(
ON__UINT32 lead_byte,
ON__UINT32 trailing_byte
);
/*
Description:
Convert a Windows code page 932 encoded value to a UNICODE code point.
This code page is often used for Japanese glpyhs.
Parameters:
code_page_932_character_value - [in]
Valid values are 0 to 0xFDFE with some exceptions in that range.
unicode_code_point - [out]
ON_UnicodeCodePoint::ON_ReplacementCharacter is returned when code_page_932_character_value is not valid.
Returns:
1: if code_page_932_character_value and the corresponding UNICODE code point is returned in *unicode_code_point.
0: otherwise and *unicode_code_point = ON_UnicodeCodePoint::ON_ReplacementCharacter.
Remarks:
Windows code page 932: https://msdn.microsoft.com/en-us/library/cc194887.aspx
Conversions to Unicode are based on the Unicode.org mapping of Shift JIS
ftp://ftp.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/JIS/SHIFTJIS.TXT
*/
#if defined(ON_COMPILER_MSC) && defined(NDEBUG)
// Work around Release build optimization bug in Visual Studio 2017.
__declspec(noinline)
#endif
int ON_MapWindowsCodePage932ToUnicode(
ON__UINT32 code_page_932_character_value,
ON__UINT32* unicode_code_point
);
/////////////////////////////////////////////////////////
//
// Code page 949
//
bool ON_IsPotentialWindowsCodePage949SingleByteEncoding(
ON__UINT32 x
);
bool ON_IsPotentialWindowsCodePage949DoubleByteEncoding(
ON__UINT32 lead_byte,
ON__UINT32 trailing_byte
);
/*
Description:
Convert a Windows code page 949 encoded value to a UNICODE code point.
This code page is often used for Korean glpyhs.
Parameters:
code_page_949_character_value - [in]
Valid values are 0 to 0xFDFE with some exceptions in that range.
unicode_code_point - [out]
ON_UnicodeCodePoint::ON_ReplacementCharacter is returned when code_page_949_character_value is not valid.
Returns:
1: if code_page_949_character_value and the corresponding UNICODE code point is returned in *unicode_code_point.
0: otherwise and *unicode_code_point = ON_UnicodeCodePoint::ON_ReplacementCharacter.
Remarks:
Windows code page 949: https://msdn.microsoft.com/en-us/library/cc194941.aspx
Conversions to Unicode are based on the Unicode.org mapping of Windows-949
ftp://ftp.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP949.TXT
*/
#if defined(ON_COMPILER_MSC) && defined(NDEBUG)
// Work around Release build optimization bug in Visual Studio 2017.
__declspec(noinline)
#endif
int ON_MapWindowsCodePage949ToUnicode(
ON__UINT32 code_page_949_character_value,
ON__UINT32* unicode_code_point
);
#endif
#endif
+271
View File
@@ -0,0 +1,271 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(ON_INTERSECT_INC_)
#define ON_INTERSECT_INC_
// These simple intersectors are fast and detect transverse intersections.
// If the intersection is not a simple transverse case, then they
// return false and you will have to use one of the slower but fancier
// models.
/*
Description:
Intersect two lines.
Parameters:
lineA - [in]
lineB - [in]
double* a - [out]
double* b - [out] The shortest distance between the lines is the
chord from lineA.PointAt(*a) to lineB.PointAt(*b).
tolerance - [in] If > 0.0, then an intersection is reported only
if the distance between the points is <= tolerance.
If <= 0.0, then the closest point between the lines
is reported.
bIntersectSegments - [in] if true, the input lines are treated
as finite segments. If false, the
input lines are treated as infinite lines.
Returns:
True if a closest point can be calculated and the result passes
the tolerance parameter test.
See Also:
ON_Intersect( const ON_Line& lineA, const ON_Line& line B)
Remarks:
If the lines are exactly parallel, meaning the system of equations
used to find a and b has no numerical solution, then false is returned.
If the lines are nearly parallel, which is often numerically true
even if you think the lines look exactly parallel, then the
closest points are found and true is returned. So, if you
care about weeding out "parallel" lines, then you need to
do something like the following.
bool rc = ON_IntersectLineLine(lineA,lineB,
&a,&b,
tolerance,
bIntersectSegments);
if (rc)
{
double angle_tolerance_radians = 0.5*ON_PI/180.0; // or whatever
double parallel_tol = cos(angle_tolerance_radians);
if ( fabs(lineA.Tangent()*lineB.Tangent()) >= parallel_tol )
{
... do whatever you think is appropriate
}
}
*/
ON_DECL
bool ON_IntersectLineLine(
const ON_Line& lineA,
const ON_Line& lineB,
double* a,
double* b,
double tolerance,
bool bIntersectSegments
);
/*
Description:
Find the closest point between two infinte lines.
Parameters:
lineA - [in]
lineB - [in]
double* a - [out]
double* b - [out] The shortest distance between the lines is the
chord from lineA.PointAt(*a) to lineB.PointAt(*b).
Returns:
True if points are found and false if the lines are numerically parallel.
Numerically parallel means the 2x2 matrix
AoA -AoB
-AoB BoB
is numerically singluar, where A = lineA.to-lineA.from
and B = lineB.to-lineB.from.
See Also:
ON_IntersectLineLine
*/
/* 15 Sept 2016 - Already in opennurbs_math.h
ON_DECL
bool ON_Intersect(
const ON_Line& lineA,
const ON_Line& lineB,
double* a,
double* b
);
*/
/* 15 Sept 2016 - Already in opennurbs_math.h
ON_DECL
bool ON_Intersect( // Returns false unless intersection is a single point
// If returned parameter is < 0 or > 1, then the line
// segment between line.m_point[0] and line.m_point[1]
// does not intersect the plane
const ON_Line&,
const ON_Plane&,
double* // parameter on line
);
*/
/*
Parameters:
line - [in]
plane_equation - [in]
line_parameter - [out]
If the returned parameter is < 0 or > 1, then the
line segment between line.from and line.to
does not intersect the plane.
Returns:
true if the interesection is a singe point.
and false otherwise.
If returned parameter is < 0 or > 1, then the line
segment between line.m_point[0] and line.m_point[1]
does not intersect the plane
*/
ON_DECL
bool ON_Intersect(
const ON_Line& line,
const ON_PlaneEquation& plane_equation,
double* line_parameter
);
/* 15 Sept 2016 - Already in opennurbs_math.h
ON_DECL
bool ON_Intersect( const ON_Plane&,
const ON_Plane&,
ON_Line& // intersection line is returned here
);
*/
/* 15 Sept 2016 - Already in opennurbs_math.h
ON_DECL
bool ON_Intersect( const ON_Plane&,
const ON_Plane&,
const ON_Plane&,
ON_3dPoint& // intersection point is returned here
);
*/
/*
Description:
Intersect a plane and a sphere.
Parameters:
plane - [in]
sphere - [in]
circle - [out]
Returns:
0: no intersection
circle radius = 0 and circle origin = point on the plane
closest to the sphere.
1: intersection is a single point
circle radius = 0;
2: intersection is a circle
circle radius > 0.
*/
/* 15 Sept 2016 - Already in opennurbs_math.h
ON_DECL
int ON_Intersect(
const ON_Plane& plane,
const ON_Sphere& sphere,
ON_Circle& circle
);
*/
/* 15 Sept 2016 - Already in opennurbs_math.h
ON_DECL
int ON_Intersect( // returns 0 = no intersections,
// 1 = one intersection,
// 2 = 2 intersections
// If 0 is returned, first point is point
// on line closest to sphere and 2nd point is the point
// on the sphere closest to the line.
// If 1 is returned, first point is obtained by evaluating
// the line and the second point is obtained by evaluating
// the sphere.
const ON_Line&, const ON_Sphere&,
ON_3dPoint&, ON_3dPoint& // intersection point(s) returned here
);
*/
/* 15 Sept 2016 - Already in opennurbs_math.h
ON_DECL
int ON_Intersect( // returns 0 = no intersections,
// 1 = one intersection,
// 2 = 2 intersections
// 3 = line lies on cylinder
// If 0 is returned, first point is point
// on line closest to cylinder and 2nd point is the point
// on the sphere closest to the line.
// If 1 is returned, first point is obtained by evaluating
// the line and the second point is obtained by evaluating
// the sphere.
const ON_Line&, const ON_Cylinder&,
ON_3dPoint&, ON_3dPoint& // intersection point(s) returned here
);
*/
/*
Description:
Intersect an infinite line and an axis aligned bounding box.
Parameters:
bbox - [in]
line - [in]
tolerance - [in] If tolerance > 0.0, then the intersection is
performed against a box that has each side
moved out by tolerance.
line_parameters - [out]
Pass null if you do not need the parameters.
If true is returned and line.from != line.to,
then the chord from line.PointAt(line_parameters[0])
to line.PointAt(line_parameters[1]) is the intersection.
If true is returned and line.from = line.to, then line.from
is in the box and the interval (0.0,0.0) is returned.
If false is returned, the input value of line_parameters
is not changed.
Returns:
True if the line intersects the box and false otherwise.
*/
ON_DECL
bool ON_Intersect( const ON_BoundingBox& bbox,
const ON_Line& line,
double tolerance,
ON_Interval* line_parameters
);
/*
Description:
Intersect two spheres using exact calculations.
Parameters:
sphere0 - [in]
sphere1 - [in]
circle - [out] If intersection is a point, then that point will be the center, radius 0.
Returns:
0 if no intersection,
1 if a single point,
2 if a circle,
3 if the spheres are the same.
*/
ON_DECL
int ON_Intersect( const ON_Sphere& sphere0,
const ON_Sphere& sphere1,
ON_Circle& circle
);
#endif
+433
View File
@@ -0,0 +1,433 @@
//
// Copyright (c) 1993-2017 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
#if !defined(OPENNURBS_IPOINT_INC_)
#define OPENNURBS_IPOINT_INC_
/*
A 2 dimensional point with integer coordinates.
Clear code will distinguish between situation where (x,y) is a
location (ON_2iPoint) or a direction (ON_2iVector) and use
the appropriate class.
*/
class ON_CLASS ON_2iPoint
{
public:
// Default construction intentionally leaves x and y uninitialized.
// Use something like
// ON_2iPoint pt(1,2);
// or
// ON_2iPoint pt = ON_2iPoint::Origin;
// when you need an initialized ON_2iPoint.
ON_2iPoint() = default;
~ON_2iPoint() = default;
ON_2iPoint(const ON_2iPoint& ) = default;
ON_2iPoint& operator=(const ON_2iPoint& ) = default;
ON_2iPoint(
int x,
int y
);
public:
static const ON_2iPoint Origin; // (0,0)
static const ON_2iPoint Unset; // (ON_UNSET_INT_INDEX,ON_UNSET_INT_INDEX)
/*
Dictionary order compare.
*/
static int Compare(
const ON_2iPoint& lhs,
const ON_2iPoint& rhs
);
public:
ON_2iPoint& operator+=(const class ON_2iVector&);
ON_2iPoint& operator-=(const class ON_2iVector&);
// It is intentional that points are not added to points to encourage
// code that is clear about what is a location and what is diplacement.
public:
/*
For those times when a location was incorrectly represented by a vector.
It is intentional that ther is not an ON_2iPoint constructor from an ON_2iVector.
*/
static const ON_2iPoint FromVector(const class ON_2iVector& v);
static const ON_2iPoint From2dex(const class ON_2dex& src);
public:
/*
Returns:
(0 == x && 0 == y)
*/
bool IsOrigin() const;
/*
Returns:
(ON_UNSET_INT_INDEX == x || ON_UNSET_INT_INDEX ==y)
*/
bool IsSet() const;
public:
ON__INT32 x;
ON__INT32 y;
};
ON_DECL
bool operator==(const ON_2iPoint&, const ON_2iPoint&);
ON_DECL
bool operator!=(const ON_2iPoint&, const ON_2iPoint&);
/*
A 2 dimensional vector with integer coordinates.
Clear code will distinguish between situation where (x,y) is a
location (ON_2iPoint) or a direction (ON_2iVector) and use
the appropriate class.
*/
class ON_CLASS ON_2iVector
{
public:
// Default construction intentionally leaves x and y uninitialized.
// Use something like
// ON_2iVector pt(1,2);
// or
// ON_2iVector pt = ON_2iVector::Zero;
// when you need an initialized ON_2iVector.
ON_2iVector() = default;
~ON_2iVector() = default;
ON_2iVector(const ON_2iVector& ) = default;
ON_2iVector& operator=(const ON_2iVector& ) = default;
ON_2iVector(
int x,
int y
);
/*
For those times when a direction was incorrectly represented by a point.
It is intentional that ther is not an ON_2iVector constructor from an ON_2iPoint.
*/
static const ON_2iVector FromPoint(const class ON_2iPoint& p);
static const ON_2iVector From2dex(const class ON_2dex& src);
public:
static const ON_2iVector Zero; // (0,0)
static const ON_2iVector UnitX; // (1,0)
static const ON_2iVector UnitY; // (0,1)
static const ON_2iVector Unset; // (ON_UNSET_INT_INDEX,ON_UNSET_INT_INDEX)
/*
Dictionary order compare.
*/
static int Compare(
const ON_2iVector& lhs,
const ON_2iVector& rhs
);
public:
ON_2iVector& operator+=(const class ON_2iVector&);
ON_2iVector& operator-=(const class ON_2iVector&);
ON_2iVector& operator*=(int);
ON_2iVector operator-() const;
public:
/*
Returns:
(0 == x && 0 == y)
*/
bool IsZero() const;
/*
Returns:
IsSet() && (0 != x || 0 != y)
*/
bool IsNotZero() const;
/*
Returns:
(ON_UNSET_INT_INDEX == x || ON_UNSET_INT_INDEX ==y)
*/
bool IsSet() const;
public:
ON__INT32 x;
ON__INT32 y;
};
ON_DECL
bool operator==(const ON_2iVector&, const ON_2iVector&);
ON_DECL
bool operator!=(const ON_2iVector&, const ON_2iVector&);
ON_DECL
ON_2iPoint operator+(const ON_2iPoint&, const ON_2iVector&);
ON_DECL
ON_2iPoint operator-(const ON_2iPoint&, const ON_2iVector&);
ON_DECL
ON_2iVector operator+(const ON_2iVector&, const ON_2iVector&);
ON_DECL
ON_2iVector operator-(const ON_2iVector&, const ON_2iVector&);
ON_DECL
ON_2iVector operator*(int, const ON_2iVector&);
class ON_CLASS ON_2iBoundingBox
{
public:
// Default construction intentionally leaves m_min and m_max uninitialized.
// Use something like
// ON_2iBoundingBox bbox(min_pt,max_pt);
// or
// ON_2iBoundingBox bbox = ON_2iBoundingBox::Unset;
ON_2iBoundingBox() = default;
~ON_2iBoundingBox() = default;
ON_2iBoundingBox(const ON_2iBoundingBox& ) = default;
ON_2iBoundingBox& operator=(const ON_2iBoundingBox& ) = default;
ON_2iBoundingBox(
const class ON_2iPoint bbox_min,
const class ON_2iPoint bbox_max
);
public:
static const ON_2iBoundingBox Zero; // (ON_2iPoint::Origin,ON_2iPoint::Origin);
static const ON_2iBoundingBox Unset; // (ON_2iPoint::Unset,ON_2iPoint::Unset)
public:
/*
Returns:
m_min.IsSet() && m_max.IsSet() && m_min.x <= m_max.x && m_min.y <= m_max.y.
*/
bool IsSet() const;
const ON_2iPoint Min() const;
const ON_2iPoint Max() const;
public:
ON_2iPoint m_min;
ON_2iPoint m_max;
};
ON_DECL
bool operator==(const ON_2iBoundingBox&, const ON_2iBoundingBox&);
ON_DECL
bool operator!=(const ON_2iBoundingBox&, const ON_2iBoundingBox&);
/*
Class ON_2iSize
For those situations where a Windows SDK SIZE or MFC CSize
value needs to be used in code that does not link with MFC.
*/
class ON_CLASS ON_2iSize
{
public:
// Default construction intentionally leaves x and y uninitialized.
// Use something like
// ON_2iSize pt(1,2);
// or
// ON_2iSize pt = ON_2iSize::Zero;
// when you need an initialized ON_2iSize.
ON_2iSize() = default;
~ON_2iSize() = default;
ON_2iSize(const ON_2iSize& ) = default;
ON_2iSize& operator=(const ON_2iSize& ) = default;
ON_2iSize(
int cx,
int cy
);
/*
Dictionary compare.
Returns:
-1: lhs < rhs
0: lsh == rsh
+1: lhs > rhs
*/
static int Compare(
const ON_2iSize& lhs,
const ON_2iSize& rhs
);
/*
Dictionary compare.
Returns:
-1: lhs < rhs
0: lsh == rsh
+1: lhs > rhs
*/
static int ComparePointer(
const ON_2iSize* lhs,
const ON_2iSize* rhs
);
public:
static const ON_2iSize Zero; // (0,0)
static const ON_2iSize Unset; // (ON_UNSET_INT_INDEX,ON_UNSET_INT_INDEX)
public:
/*
Returns:
true if both cx and cy are 0.
*/
bool IsZero() const;
/*
Returns:
true if neither cx nor cy are ON_UNSET_INT_INDEX.
*/
bool IsSet() const;
public:
ON__INT32 cx;
ON__INT32 cy;
};
ON_DECL
bool operator==(
const ON_2iSize& lhs,
const ON_2iSize& rhs
);
ON_DECL
bool operator!=(
const ON_2iSize& lhs,
const ON_2iSize& rhs
);
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_2iSize>;
#endif
/*
Class ON_4iRect
For those situations where a Windows SDK RECT or MFC CRect
value needs to be used in code that does not link with MFC.
If you want a traditional bounding box, use ON_2dBoundingBox.
*/
class ON_CLASS ON_4iRect
{
public:
// Default construction intentionally leaves x and y uninitialized.
// Use something like
// ON_4iRect pt(1,2,3,4);
// or
// ON_4iRect pt = ON_4iRect::Zero;
// when you need an initialized ON_4iRect.
ON_4iRect() = default;
~ON_4iRect() = default;
ON_4iRect(const ON_4iRect& ) = default;
ON_4iRect& operator=(const ON_4iRect& ) = default;
ON_4iRect(
int left,
int top,
int right,
int bottom
);
ON_4iRect(const ON_2iPoint topLeft, const ON_2iPoint& bottomRight);
ON_4iRect(const ON_2iPoint& point, const ON_2iSize& size);
public:
static const ON_4iRect Zero; // (0,0,0,0)
static const ON_4iRect Unset; // (ON_UNSET_INT_INDEX,ON_UNSET_INT_INDEX,ON_UNSET_INT_INDEX,ON_UNSET_INT_INDEX)
public:
/*
Returns:
true if all of left, top, right, and bottom are set to 0.
*/
bool IsZero() const;
void SetZero();
/*
Returns:
true if none of left, top, right, or bottom is set to ON_UNSET_INT_INDEX
*/
bool IsSet() const;
int Width(void) const;
int Height(void) const;
const ON_2iSize Size(void) const;
const ON_2iPoint CenterPoint(void) const;
const ON_2iPoint TopLeft(void) const;
const ON_2iPoint BottomRight(void) const;
bool IntersectRect(const ON_4iRect* r1, const ON_4iRect* r2);
bool IntersectRect(const ON_4iRect& r1, const ON_4iRect& r2);
bool IsRectEmpty(void) const;
bool IsRectNull(void) const;
void SetRectEmpty(void) { *this = Zero; }
void SetRect(int l, int t, int r, int b);
bool PtInRect(const ON_2iPoint& pt) const;
void OffsetRect(int, int);
void OffsetRect(const ON_2iVector&);
void InflateRect(int, int);
void InflateRect(int, int, int, int);
void DeflateRect(int, int);
bool SubtractRect(const ON_4iRect* rect1, const ON_4iRect* rect2);
void NormalizeRect();
public:
// NOTE WELL:
// Windows 2d integer device coordinates have a
// strong y-down bias and it is common for top < bottom.
// General 2d bounding boxes have a strong lower < upper / min < max bias.
// Take care when converting between ON_2iBoundingBox and ON_4iRect.
// It is intentional that no automatic conversion between bounding box
// and ON_4iRect is supplied because each case must be carefully considered.
ON__INT32 left;
ON__INT32 top;
ON__INT32 right;
ON__INT32 bottom;
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_4iRect>;
#endif
ON_DECL
bool operator==(const ON_4iRect&, const ON_4iRect&);
ON_DECL
bool operator!=(const ON_4iRect&, const ON_4iRect&);
#endif
+492
View File
@@ -0,0 +1,492 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_KNOT_INC_)
#define OPENNURBS_KNOT_INC_
ON_DECL
double ON_DomainTolerance(
double, // start of domain
double // end of domain
);
ON_DECL
double ON_KnotTolerance(
int, // order (>=2)
int, // cv count
const double*, // knot[] array
int // knot index
);
ON_DECL
double ON_SpanTolerance(
int, // order (>=2)
int, // cv count
const double*, // knot[] array
int // span index
);
ON_DECL
int ON_KnotCount( // returns (order + cv_count - 2)
int, // order (>=2)
int // cv_count (>=order)
);
ON_DECL
int ON_KnotMultiplicity(
int, // order (>=2)
int, // cv_count (>=order)
const double*, // knot[]
int // knot_index
);
ON_DECL
int ON_KnotVectorSpanCount(
int, // order (>=2)
int, // cv count
const double* // knot[] array
);
ON_DECL
bool ON_GetKnotVectorSpanVector(
int, // order (>=2)
int, // cv count
const double*, // knot[] array
double* // s[] array
);
/*
Description:
Given an evaluation parameter t in the domain of a NURBS curve,
ON_NurbsSpanIndex(order,cv_count,knot,t,0,0) returns the integer
i such that (knot[i],...,knot[i+2*degree-1]), and
(cv[i],...,cv[i+degree]) are the knots and control points that
define the span of the NURBS that are used for evaluation at t.
Parameters:
order - [in] order >= 2
cv_count - [in] cv_count >= order
knot - [in] valid knot vector
t - [in] evaluation parameter
side - [in] determines which span is used when t is at a knot
value; side = 0 for the default (from above),
side = -1 means from below, and
side = +1 means from above.
hint - [in] Search hint, or 0 if not hint is available.
Returns:
Returns the index described above.
*/
ON_DECL
int ON_NurbsSpanIndex(
int order,
int cv_count,
const double* knot,
double t,
int side,
int hint
);
ON_DECL
int ON_NextNurbsSpanIndex(
// returns 0: input span_index < 0
// cv_count-order: input span_index = cv_count-order
// -1: input span_index > cv_count-order;
// otherwise next span index
int order,
int cv_count,
const double* knot,
int // current span_index
);
ON_DECL
int ON_GetSpanIndices( // returns span count, which is one less than length of span_indices[]
int order,
int cv_count,
const double* knot,
int* // span_indices[cv_count-order+2].
//Indices of knots at end of group of mult knots
//at start of span, and knot at start of group of mult knots
//at end of spline.
);
ON_DECL
double ON_SuperfluousKnot(
int order,
int cv_count,
const double* knot,
int // 0 = first superfluous knot
// 1 = last superfluous knot
);
ON_DECL
bool ON_IsKnotVectorPeriodic(
int order,
int cv_count,
const double* knot
);
ON_DECL
bool ON_IsKnotVectorClamped(
int order,
int cv_count,
const double* knot,
int = 2 // 0 = check left end, 1 = check right end, 2 = check both
);
ON_DECL
bool ON_IsKnotVectorUniform(
int order,
int cv_count,
const double* knot
);
//////////
// returns true if all knots have multiplicity = degree
ON_DECL
bool ON_KnotVectorHasBezierSpans(
int order,
int cv_count,
const double* knot
);
ON_DECL
ON::knot_style ON_KnotVectorStyle(
int order,
int cv_count,
const double* knot
);
/*
Description:
Set the domain of a knot vector.
Parameters:
order - [in] order >= 2
cv_count - [in] cv_count >= order
knot - [in/out] input existing knots and returns knots with new domain.
t0 - [in]
t1 - [in] New domain will be the interval (t0,t1).
Returns:
True if input is valid and the returned knot vector
has the requested domain. False if the input is
invalid, in which case the input knot vector is not
changed.
*/
ON_DECL
bool ON_SetKnotVectorDomain(
int order,
int cv_count,
double* knot,
double t0,
double t1
);
ON_DECL
bool ON_GetKnotVectorDomain(
int, // order (>=2)
int, // cv count
const double*, // knot[] array
double*, double*
);
ON_DECL
bool ON_ReverseKnotVector(
int, // order (>=2)
int, // cv count
double* // knot[] array
);
ON_DECL
int ON_CompareKnotVector( // returns
// -1: first < second
// 0: first == second
// +1: first > second
// first knot vector
int, // order (>=2)
int, // cv count
const double*, // knot[] array
// second knot vector
int, // order (>=2)
int, // cv count
const double* // knot[] array
);
ON_DECL
bool ON_IsValidKnotVector(
int order,
int cv_count,
const double* knot,
ON_TextLog* text_log = 0
);
ON_DECL
bool ON_ClampKnotVector(
// Sets inital/final order-2 knots to values in
// knot[order-2]/knot[cv_count-1].
int, // order (>=2)
int, // cv count
double*, // knot[] array
int // 0 = clamp left end, 1 = right end, 2 = clamp both ends
);
ON_DECL
bool ON_MakeKnotVectorPeriodic(
// Sets inital and final order-2 knots to values
// that make the knot vector periodic
int, // order (>=2)
int, // cv count
double* // knot[] array
);
/*
Description:
Fill in knot values for a clamped uniform knot
vector.
Parameters:
order - [in] (>=2) order (degree+1) of the NURBS
cv_count - [in] (>=order) total number of control points
in the NURBS.
knot - [in/out] Input is an array with room for
ON_KnotCount(order,cv_count) doubles. Output is
a clamped uniform knot vector with domain
(0, (1+cv_count-order)*delta).
delta - [in] (>0, default=1.0) spacing between knots.
Returns:
true if successful
See Also:
ON_NurbsCurve::MakeClampedUniformKnotVector
*/
ON_DECL
bool ON_MakeClampedUniformKnotVector(
int order,
int cv_count,
double* knot,
double delta = 1.0
);
/*
Description:
Fill in knot values for a clamped uniform knot
vector.
Parameters:
order - [in] (>=2) order (degree+1) of the NURBS
cv_count - [in] (>=order) total number of control points
in the NURBS.
knot - [in/out] Input is an array with room for
ON_KnotCount(order,cv_count) doubles. Output is
a periodic uniform knot vector with domain
(0, (1+cv_count-order)*delta).
delta - [in] (>0, default=1.0) spacing between knots.
Returns:
true if successful
See Also:
ON_NurbsCurve::MakePeriodicUniformKnotVector
*/
ON_DECL
bool ON_MakePeriodicUniformKnotVector(
int order,
int cv_count,
double* knot,
double delta = 1.0
);
ON_DECL
double ON_GrevilleAbcissa( // get Greville abcissae from knots
int, // order (>=2)
const double* // knot[] array (length = order-1)
);
ON_DECL
bool ON_GetGrevilleAbcissae( // get Greville abcissae from knots
int, // order (>=2)
int, // cv count
const double*, // knot[] array
bool, // true for periodic case
double* // g[] array has length cv_count in non-periodic case
// and cv_count-order+1 in periodic case
);
ON_DECL
bool ON_GetGrevilleKnotVector( // get knots from Greville abcissa
int, // g[] array stride (>=1)
const double*, // g[] array
// if not periodic, length = cv_count
// if periodic, length = cv_count-order+2
bool, // true for periodic knots
int, // order (>=2)
int, // cv_count (>=order)
double* // knot[cv_count+order-2]
);
ON_DECL
bool ON_ClampKnotVector(
int, // cv_dim ( = dim+1 for rational cvs )
int, // order (>=2)
int, // cv_count,
int, // cv_stride,
double*, // cv[] nullptr or array of order many cvs
double*, // knot[] array with room for at least knot_multiplicity new knots
int // end 0 = clamp start, 1 = clamp end, 2 = clamp both ends
);
/*
Returns:
Number of knots added.
*/
ON_DECL
int ON_InsertKnot(
double, // knot_value,
int, // knot_multiplicity, (1 to order-1 including multiplicity of any existing knots)
int, // cv_dim ( = dim+1 for rational cvs )
int, // order (>=2)
int, // cv_count,
int, // cv_stride (>=cv_dim)
double*, // cv[] nullptr or cv array with room for at least knot_multiplicity new cvs
double*, // knot[] knot array with room for at least knot_multiplicity new knots
int* // hint, optional hint about where to search for span to add knots to
// pass nullptr if no hint is available
);
/*
Description:
Reparameterize a rational Bezier curve.
Parameters:
c - [in]
reparameterization constant (generally speaking, c should be > 0).
The control points are adjusted so that
output_bezier(t) = input_bezier(lambda(t)), where
lambda(t) = c*t/( (c-1)*t + 1 ).
Note that lambda(0) = 0, lambda(1) = 1, lambda'(t) > 0,
lambda'(0) = c and lambda'(1) = 1/c.
dim - [in]
order - [in]
cvstride - [in] (>= dim+1)
cv - [in/out] homogeneous rational control points
Returns:
The cv values are changed so that
output_bezier(t) = input_bezier(lambda(t)).
*/
ON_DECL
bool ON_ReparameterizeRationalBezierCurve(
double c,
int dim,
int order,
int cvstride,
double* cv
);
/*
Description:
Use a combination of scaling and reparameterization to set two rational
Bezier weights to specified values.
Parameters:
dim - [in]
order - [in]
cvstride - [in] ( >= dim+1)
cv - [in/out] homogeneous rational control points
i0 - [in]
w0 - [in]
i1 - [in]
w1 - [in]
The i0-th cv will have weight w0 and the i1-th cv will have weight w1.
If v0 and v1 are the cv's input weights, then v0, v1, w0 and w1 must
all be nonzero, and w0*v0 and w1*v1 must have the same sign.
Returns:
true if successful
Remarks:
The equations
s * r^i0 = w0/v0
s * r^i1 = w1/v1
determine the scaling and reparameterization necessary to change v0,v1 to
w0,w1.
If the input Bezier has control vertices {B_0, ..., B_d}, then the
output Bezier has control vertices {s*B_0, ... s*r^i * B_i, ..., s*r^d * B_d}.
*/
ON_DECL
bool ON_ChangeRationalBezierCurveWeights(
int dim, int order, int cvstride, double* cv,
int i0, double w0,
int i1, double w1
);
/*
Description:
Reparameterize a rational NURBS curve.
Parameters:
c - [in]
reparameterization constant (generally speaking, c should be > 0).
The control points and knots are adjusted so that
output_nurbs(t) = input_nurbs(lambda(t)), where
lambda(t) = c*t/( (c-1)*t + 1 ).
Note that lambda(0) = 0, lambda(1) = 1, lambda'(t) > 0,
lambda'(0) = c and lambda'(1) = 1/c.
dim - [in]
order - [in]
cvstride - [in] (>=dim+1)
cv - [in/out] homogeneous rational control points
knot - [in/out]
NURBS curve knots
Returns:
The cv values are changed so that
output_bezier(t) = input_bezier(lambda(t)).
See Also:
ON_ChangeRationalNurbsCurveEndWeights
*/
ON_DECL
bool ON_ReparameterizeRationalNurbsCurve(
double c,
int dim,
int order,
int cv_count,
int cvstride,
double* cv,
double* knot
);
/*
Description:
Use a combination of scaling and reparameterization to set the end
weights to the specified values. This
Parameters:
dim - [in]
order - [in]
cvstride - [in] (>=dim+1)
cv - [in/out] homogeneous rational control points
knot - [in/out] (output knot vector will be clamped and internal
knots may be shifted.)
w0 - [in]
w1 - [in]
The first cv will have weight w0 and the last cv will have weight w1.
If v0 and v1 are the cv's input weights, then v0, v1, w0 and w1 must
all be nonzero, and w0*v0 and w1*v1 must have the same sign.
Returns:
true if successful
See Also:
ON_ReparameterizeRationalNurbsCurve
*/
ON_DECL
bool ON_ChangeRationalNurbsCurveEndWeights(
int dim,
int order,
int cv_count,
int cvstride,
double* cv,
double* knot,
double w0,
double w1
);
#endif
+772
View File
@@ -0,0 +1,772 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_LAYER_INC_)
#define OPENNURBS_LAYER_INC_
class ON_CLASS ON_Layer : public ON_ModelComponent
{
ON_OBJECT_DECLARE(ON_Layer);
public:
ON_Layer() ON_NOEXCEPT;
~ON_Layer() = default;
ON_Layer(const ON_Layer&);
ON_Layer& operator=(const ON_Layer&) = default;
static const ON_Layer Unset; // index = ON_UNSET_INT_INDEX, id = nil
static const ON_Layer Default; // index = -1, id set, unique and persistent
/*
Parameters:
model_component_reference - [in]
none_return_value - [in]
value to return if ON_Layer::Cast(model_component_ref.ModelComponent())
is nullptr
Returns:
If ON_Layer::Cast(model_component_ref.ModelComponent()) is not nullptr,
that pointer is returned. Otherwise, none_return_value is returned.
*/
static const ON_Layer* FromModelComponentRef(
const class ON_ModelComponentReference& model_component_reference,
const ON_Layer* none_return_value
);
bool UpdateReferencedComponents(
const class ON_ComponentManifest& source_manifest,
const class ON_ComponentManifest& destination_manifest,
const class ON_ManifestMap& manifest_map
) override;
//////////////////////////////////////////////////////////////////////
//
// ON_Object overrides
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
void Dump( ON_TextLog& ) const override; // for debugging
bool Write(
ON_BinaryArchive& // serialize definition to binary archive
) const override;
bool Read(
ON_BinaryArchive& // restore definition from binary archive
) override;
ON::object_type ObjectType() const override;
//////////////////////////////////////////////////////////////////////
//
// Interface
// The PER_VIEWPORT_SETTINGS enum defines
// the bits used to set masks in functions used
// to specify and query per viewport layer settings.
enum PER_VIEWPORT_SETTINGS : unsigned int
{
per_viewport_none = 0,
per_viewport_id = 1,
per_viewport_color = 2,
per_viewport_plot_color = 4,
per_viewport_plot_weight = 8,
per_viewport_visible = 16,
per_viewport_persistent_visibility = 32,
per_viewport_all_settings = 0xFFFFFFFF
// (Developers: these values are used in file IO and must not be changed.)
};
/*
Parameters:
viewport_id - [in]
If viewport_id is not nil, then checks for per viewport
settings for that specific viewport.
If viewport_id is nil, then checks for per viewport settings
in any viewport.
settings_mask - [in]
settings_mask is a bitfield that specifies which settings
to check for. The bits are defined in the
ON_Layer::PER_VIEWPORT_PROPERTIES enum. If you want to
determine if the layer has any per viewport settings,
then pass 0xFFFFFFFF.
Returns:
True if the layer has per viewport override for the specified
settings.
*/
bool HasPerViewportSettings(
ON_UUID viewport_id,
unsigned int settings_mask
) const;
/*
Parameters:
viewport_id - [in]
If viewport_id is not nil, then checks for setting for
that specific viewport.
If viewport_id is nil, then checks for any viewport settings.
Returns:
True if the layer has per viewport settings.
*/
bool HasPerViewportSettings(
const ON_UUID& viewport_id
) const;
/*
Description:
Copies all per viewport settings for the source_viewport_id
Parameters:
source_viewport_id - [in]
viewport id to copy all per viewport settings from
destination_viewport_id - [in]
viewport od to copy all per viewport settings to
Returns:
True if the settings could be copied, False if no per-viewport
settings exist for the source viewport id
*/
bool CopyPerViewportSettings(
ON_UUID source_viewport_id,
ON_UUID destination_viewport_id
);
/*
Description:
Copies specified per viewport settings from a source layer to this
layer.
Parameters:
source_layer - [in]
layer to copy settings from
viewport_id - [in]
viewport id to copy all per viewport settings from.
If viewport_id is nil, then the per viewport settings
for all viewports will be copied.
settings_mask - [in]
bits indicate which settings to copy
Use the ON_Layer PER_VIEWPORT_SETTINGS enum to
set the bits.
Returns:
True if the settings were copied, False if no per-viewport
settings exist for the specified viewport_id.
*/
bool CopyPerViewportSettings(
const ON_Layer& source_layer,
ON_UUID viewport_id,
unsigned int settings_mask
);
/*
Description:
Delete per viewport layer settings.
Parameters:
viewport_id - [in]
If viewport_id is not nil, then the settings for that
viewport are deleted. If viewport_id is nil, then all
per viewport settings are deleted.
*/
void DeletePerViewportSettings(
const ON_UUID& viewport_id
) const;
/*
Description:
Cull unused per viewport layer settings.
Parameters:
viewport_id_count - [in]
viewport_id_list - [in]
Settings for any viewports NOT in the viewport_id_list[]
are culled.
*/
void CullPerViewportSettings(
int viewport_id_count,
const ON_UUID* viewport_id_list
);
/*
Description:
The PerViewportSettingsCRC() can be used to determine
when layers have different per viewport settings.
*/
ON__UINT32 PerViewportSettingsCRC() const;
/*
Description:
Set the color used by objects on this layer that do
not have a per object color set
Parameters:
layer_color - [in]
Passing ON_UNSET_COLOR will clear the settings.
viewport_id - [in]
If viewport_id is not nil, then the setting applies only
to the viewport with the specified id.
*/
void SetColor( ON_Color layer_color ); // layer display color
/*
Description:
Set the color used by objects on this layer that do
not have a per object color set
Parameters:
viewport_id - [in]
If viewport_id is not nil, then the setting applies only
to the viewport with the specified id.
layer_color - [in]
Passing ON_UNSET_COLOR will clear the settings.
*/
void SetPerViewportColor( ON_UUID viewport_id, ON_Color layer_color );
// /* use ON_Layer::SetPerViewportColor */
//ON_DEPRECATED void SetColor( ON_Color, const ON_UUID& );
/*
Parameters:
viewport_id - [in]
If viewport_id is not nil, then the setting to use
for a specific viewport is returned.
Returns:
The color used by objects on this layer that do
not have a per object color set.
*/
ON_Color Color() const;
/*
Parameters:
viewport_id - [in]
If viewport_id is not nil, then the setting to use
for a specific viewport is returned.
Returns:
The color used by objects in the specified viewport and
on this layer that do not have a per object color set.
*/
ON_Color PerViewportColor( ON_UUID viewport_id ) const;
// /* use ON_Layer::PerViewportColor */
//ON_DEPRECATED ON_Color Color( const ON_UUID& ) const;
/*
Description:
Remove any per viewport layer color setting so the
layer's overall setting will be used for all viewports.
Parameters:
viewport_id - [in]
If viewport_id is not nil, then the setting for this
viewport will be deleted. If viewport_id is nil,
the all per viewport layer color settings will be removed.
*/
void DeletePerViewportColor( const ON_UUID& viewport_id );
/*
Description:
Set the plotting color used by objects on this layer that do
not have a per object plotting color set
Parameters:
plot_color - [in]
Passing ON_UNSET_COLOR will clear the settings.
viewport_id - [in]
If viewport_id is not nil, then the setting applies only
to the viewport with the specified id.
*/
void SetPlotColor( ON_Color plot_color ); // plotting color
void SetPerViewportPlotColor( ON_UUID viewport_id, ON_Color plot_color );
// /* use ON_Layer::SetPerViewportPlotColor */
//ON_DEPRECATED void SetPlotColor( ON_Color, const ON_UUID& );
/*
Returns:
The plotting color used by objects on this layer that do
not have a per object color set.
*/
ON_Color PlotColor() const;
/*
Parameters:
viewport_id - [in]
If viewport_id is not nil, then the setting to use
for a specific viewport is returned.
Returns:
The plotting color used by objects on this layer that do
not have a per object color set.
*/
ON_Color PerViewportPlotColor( ON_UUID viewport_id ) const;
// /* use ON_Layer::PerViewportPlotColor */
//ON_DEPRECATED ON_Color PlotColor( const ON_UUID& ) const;
/*
Description:
Remove any per viewport plot color setting so the
layer's overall setting will be used for all viewports.
Parameters:
viewport_id - [in]
If viewport_id is not nil, then the setting for this
viewport will be deleted. If viewport_id is nil,
the all per viewport plot color settings will be removed.
*/
void DeletePerViewportPlotColor( const ON_UUID& viewport_id );
/*
Description:
Set the index of the linetype used by objects on this layer that do
not have a per object lintypes
Parameters:
linetype_index - [in]
Passing -1 will clear the setting.
*/
bool SetLinetypeIndex( int linetype_index );
/*
Returns:
The index of the linetype used by objects on this layer that do
not have a per object linetype set.
*/
int LinetypeIndex() const;
/*
Returns:
Returns true if objects on layer are visible.
Remarks:
Does not inspect per viewport settings.
See Also:
ON_Layer::SetVisible
*/
bool IsVisible() const;
/*
Description:
Controls layer visibility
Parameters:
bVisible - [in] true to make layer visible,
false to make layer invisible
viewport_id - [in]
If viewport_id is not nil, then the setting applies only
to the viewport with the specified id.
See Also:
ON_Layer::IsVisible
*/
void SetVisible( bool bVisible );
/*
Description:
The persistent visbility setting is used for layers whose
visibilty can be changed by a "parent" object. A common case
is when a layer is a child layer (ON_Layer.m_parent_id is
not nil). In this case, when a parent layer is turned off,
then child layers are also turned off. The persistent
visibility setting determines what happens when the parent
is turned on again.
Returns:
true:
If this layer's visibility is controlled by a parent object
and the parent is turned on (after being off), then this
layer will also be turned on.
false:
If this layer's visibility is controlled by a parent object
and the parent layer is turned on (after being off), then
this layer will continue to be off.
Remarks:
When the persistent visbility is not explicitly set, this
function returns the current value of IsVisible().
See Also:
ON_Layer::SetPersistentVisibility
ON_Layer::UnsetPersistentVisibility
*/
bool PersistentVisibility() const;
/*
Description:
Set the persistent visibility setting for this layer.
Parameters:
bPersistentVisibility - [in]
persistent visibility setting for this layer.
Remarks:
See ON_Layer::PersistentVisibility for a detailed description
of persistent visibility.
See Also:
ON_Layer::PersistentVisibility
ON_Layer::UnsetPersistentVisibility
*/
void SetPersistentVisibility( bool bPersistentVisibility );
/*
Description:
Remove any explicit persistent visibility setting from this
layer. When persistent visibility is not explictly set,
the value of ON_Layer::IsVisible() is used.
Remarks:
See ON_Layer::PersistentVisibility for a detailed description
of persistent visibility.
See Also:
ON_Layer::PersistentVisibility
ON_Layer::SetPersistentVisibility
*/
void UnsetPersistentVisibility();
/*
Parameters:
viewport_id - [in]
If viewport_id is not nil, then the visibility setting
for that viewport is returned.
If viewport_id is nil, the ON_Layer::IsVisible() is returned.
Returns:
Returns true if objects on layer are visible.
*/
bool PerViewportIsVisible( ON_UUID viewport_id ) const;
/*
Description:
Controls layer visibility in specific viewports.
Parameters:
viewport_id - [in]
If viewport_id is not nil, then the setting applies only
to the viewport with the specified id. If viewport_id
is nil, then the setting applies to all viewports with
per viewport layer settings.
bVisible - [in] true to make layer visible,
false to make layer invisible
See Also:
ON_Layer::IsVisibleInViewport()
*/
void SetPerViewportVisible(
ON_UUID viewport_id,
bool bVisible
);
// /* use ON_Layer::SetPerViewportVisible */
// ON_DEPRECATED void SetVisible( bool, const ON_UUID& );
/*
Parameters:
viewport_id - [in]
id of a viewport. If viewport_id is nil, then
ON_Layer::PersistentVisibility() is returned.
Returns:
true:
If this layer's visibility in the specified viewport is
controlled by a parent object and the parent is turned on
(after being off), then this layer will also be turned on
in the specified viewport.
false:
If this layer's visibility in the specified viewport is
controlled by a parent object and the parent layer is
turned on (after being off), then this layer will continue
to be off in the specified viewport.
Remarks:
See ON_Layer::SetPersistentVisibility
for a description of persistent visibility.
See Also:
ON_Layer::SetPerViewportPersistentVisibility
*/
bool PerViewportPersistentVisibility( ON_UUID viewport_id ) const;
/*
Description:
This function allows per viewport setting the
child visibility property.
Parameters
viewport_id - [in]
bPersistentVisibility - [in]
Remarks:
See ON_Layer::SetPersistentVisibility
for a description of the child visibility property.
See Also:
ON_Layer::SetPersistentVisibility
*/
void SetPerViewportPersistentVisibility( ON_UUID viewport_id, bool bPersistentVisibility );
void UnsetPerViewportPersistentVisibility( ON_UUID viewport_id );
/*
Description:
Remove any per viewport visibility setting so the
layer's overall setting will be used for all viewports.
Parameters:
viewport_id - [in]
If viewport_id is not nil, then the setting for this
viewport will be deleted. If viewport_id is nil,
the all per viewport visibility settings will be removed.
*/
void DeletePerViewportVisible( const ON_UUID& viewport_id );
/*
Description:
Get a list of the viewport ids of viewports that
that have per viewport visibility settings that
override the default layer visibility setting
ON_Layer::m_bVisible.
Parameters:
viewport_id_list - [out]
List of viewport id's that have a per viewport visibility
setting. If the returned list is empty, then there
are no per viewport visibility settings.
Returns:
Number of ids added to the list.
*/
void GetPerViewportVisibilityViewportIds(
ON_SimpleArray<ON_UUID>& viewport_id_list
) const;
/*
Description:
Controls layer locked
Parameters:
bLocked - [in] True to lock layer
False to unlock layer
See Also:
ON_Layer::IsLocked
*/
void SetLocked( bool bLocked );
/*
Description:
The persistent locking setting is used for layers that can
be locked by a "parent" object. A common case is when a layer
is a child layer (ON_Layer.m_parent_id is not nil). In this
case, when a parent layer is locked, then child layers are
also locked. The persistent locking setting determines what
happens when the parent is unlocked again.
Returns:
true:
If this layer's locking is controlled by a parent object
and the parent is unlocked (after being locked), then this
layer will also be unlocked.
false:
If this layer's locking is controlled by a parent object
and the parent layer is unlocked (after being locked), then
this layer will continue to be locked.
Remarks:
When the persistent locking is not explicitly set, this
function returns the current value of IsLocked().
See Also:
ON_Layer::SetPersistentLocking
ON_Layer::UnsetPersistentLocking
*/
bool PersistentLocking() const;
/*
Description:
Set the persistent locking setting for this layer.
Parameters:
bPersistentLocking - [in]
persistent locking for this layer.
Remarks:
See ON_Layer::PersistentLocking for a detailed description of
persistent locking.
See Also:
ON_Layer::PersistentLocking
ON_Layer::UnsetPersistentLocking
*/
void SetPersistentLocking(bool bPersistentLocking);
/*
Description:
Remove any explicity persistent locking settings from this
layer.
Remarks:
See ON_Layer::PersistentLocking for a detailed description of
persistent locking.
See Also:
ON_Layer::PersistentLocking
ON_Layer::SetPersistentLocking
*/
void UnsetPersistentLocking();
/*
Returns:
Value of (IsVisible() && !IsLocked()).
*/
bool IsVisibleAndNotLocked() const;
/*
Returns:
Value of (IsVisible() && IsLocked()).
*/
bool IsVisibleAndLocked() const;
//////////
// Index of render material for objects on this layer that have
// MaterialSource() == ON::material_from_layer.
// A material index of -1 indicates no material has been assigned
// and the material created by the default ON_Material constructor
// should be used.
bool SetRenderMaterialIndex( int ); // index of layer's rendering material
int RenderMaterialIndex() const;
bool SetIgesLevel( int ); // IGES level for this layer
int IgesLevel() const;
/*
Description:
Get the weight (thickness) of the plotting pen.
Returns:
Thickness of the plotting pen in millimeters.
A thickness of 0.0 indicates the "default" pen weight should be used.
A thickness of -1.0 indicates the layer should not be printed.
*/
double PlotWeight() const;
double PerViewportPlotWeight( ON_UUID viewport_id ) const;
// /* use ON_Layer::PerViewportPlotWeight */
// ON_DEPRECATED double PlotWeight( const ON_UUID& ) const;
/*
Description:
Set the weight of the plotting pen.
Parameters:
plot_weight_mm - [in] Set the thickness of the plotting pen in millimeters.
0.0 means use the default pen width which is a Rhino app setting.
-1.0 means layer does not print (still displays on the screen)
*/
void SetPlotWeight(double plot_weight_mm);
/*
Description:
Set the weight of the plotting pen.
Parameters:
plot_weight_mm - [in] Set the thickness of the plotting pen in millimeters.
0.0 means use the default pen width which is a Rhino app setting.
-1.0 means layer does not print (still displays on the screen)
*/
void SetPerViewportPlotWeight(ON_UUID viewport_id, double plot_weight_mm);
// /* use ON_Layer::SetPerViewportPlotWeight */
// ON_DEPRECATED void SetPlotWeight(double, const ON_UUID& );
/*
Description:
Remove any per viewport plot weight setting so the
layer's overall setting will be used for all viewports.
Parameters:
viewport_id - [in]
If viewport_id is not nil, then the setting for this
viewport will be deleted. If viewport_id is nil,
the all per viewport plot weight settings will be removed.
*/
void DeletePerViewportPlotWeight( const ON_UUID& viewport_id );
/*
Description:
Use UpdateViewportIds() to change viewport ids in situations
like merging when a viewport id conflict requires the viewport
ids in a file to be changed.
Returns:
Number of viewport ids that were updated.
*/
int UpdateViewportIds(
const ON_UuidPairList& viewport_id_map
);
public:
// Layers are origanized in a hierarchical
// structure (like file folders).
// If a layer is in a parent layer,
// then m_parent_layer_id is the id of
// the parent layer.
ON_UUID ParentLayerId() const;
void SetParentLayerId(
ON_UUID parent_layer_id
);
int m_iges_level = -1; // IGES level number if this layer was made during IGES import
// Rendering material:
// If you want something simple and fast, set
// m_material_index to the index of your rendering material
// and ignore m_rendering_attributes.
// If you are developing a fancy plug-in renderer, and a user is
// assigning one of your fabulous rendering materials to this
// layer, then add rendering material information to the
// m_rendering_attributes.m_materials[] array.
//
// Developers:
// As soon as m_rendering_attributes.m_materials[] is not empty,
// rendering material queries slow down. Do not populate
// m_rendering_attributes.m_materials[] when setting
// m_material_index will take care of your needs.
int m_material_index = -1;
ON_RenderingAttributes m_rendering_attributes;
int m_linetype_index = -1; // index of linetype
// Layer display attributes.
// If m_display_material_id is nil, then m_color is the layer color
// and defaults are used for all other display attributes.
// If m_display_material_id is not nil, then some complicated
// scheme is used to decide what objects on this layer look like.
// In all cases, m_color is a good choice if you don't want to
// deal with m_display_material_id. In Rhino, m_display_material_id
// is used to identify a registry entry that contains user specific
// display preferences.
ON_Color m_color = ON_Color::Black;
ON_UUID m_display_material_id = ON_nil_uuid;
// Layer printing (plotting) attributes.
ON_Color m_plot_color = ON_Color::UnsetColor; // printing color
// ON_UNSET_COLOR means use layer color
double m_plot_weight_mm = 0.0; // printing pen thickness in mm
// 0.0 means use the default width (a Rhino app setting)
// -1.0 means layer does not print (still visible on screen)
bool m_bExpanded = true; // If true, when the layer table is displayed in
// a tree control then the list of child layers is
// shown in the control.
private:
// The following information may not be accurate and is subject
// to change at any time.
//
// m_extension_bits & 0x01:
// The value of ( m_extension_bits & 0x01) is used to speed
// common per viewport visiblity and color queries.
// 0x00 = there may be per viewport settings on this layer.
// 0x01 = there are no per viewport settings on this layer.
//
// m_extension_bits & 0x06:
// The value of ( m_extension_bits & 0x06) is the persistent
// visibility setting for this layer.
// 0x00 = no persistent visibility setting
// 0x02 = persistent visibility = true
// 0x04 = persistent visibility = false
// 0x06 = invalid value - treated as 0x00
//
// m_extension_bits & 0x18:
// The value of ( m_extension_bits & 0x18) is the persistent
// locking setting for this layer.
// 0x00 = no persistent locking setting
// 0x08 = persistent locking = true
// 0x10 = persistent locking = false
// 0x18 = invalid value - treated as 0x00
ON__UINT8 m_extension_bits = 0;
ON__UINT16 m_reserved = 0;
private:
ON__UINT_PTR m_reserved_ptr = 0;
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_Layer*>;
ON_DLL_TEMPLATE template class ON_CLASS ON_ObjectArray<ON_Layer>;
#endif
#endif
+196
View File
@@ -0,0 +1,196 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
// ON_Leader class
#ifndef OPENNURBS_LEADER_H_INCLUDED
#define OPENNURBS_LEADER_H_INCLUDED
class ON_CLASS ON_Leader : public ON_Annotation
{
ON_OBJECT_DECLARE(ON_Leader);
public:
ON_Leader();
~ON_Leader();
ON_Leader(const ON_Leader& src);
ON_Leader& operator=(const ON_Leader& src);
static const ON_Leader Empty;
private:
void Internal_Destroy();
void Internal_CopyFrom(const ON_Leader& src);
public:
/*
Parameters:
dimstyle - [in]
If you want to specify text appearance or other custom properties ...
ON_DimStyle style = ON_DimStyle::DimStyleFromProperties( doc->DimStyleContext().CurrentDimStyle(), ... );
style.Set...(...);
Then pass &style
Remarks:
Parses text string and makes runs
*/
bool Create(
const wchar_t* leader_text,
const ON_DimStyle* dimstyle,
int point_count,
const ON_3dPoint* points,
const ON_Plane& plane,
bool bWrapped,
double rect_width
);
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
void Dump(ON_TextLog& log) const override;
bool Write(ON_BinaryArchive& file) const override;
bool Read(ON_BinaryArchive& file) override;
ON::object_type ObjectType() const override;
/*
Description:
Create a V6 leader from a V5 leader.
The function is used when reading V5 files.
Parameters:
v5_leader -[in]
dim_style - [in]
Dimstyle referenced by v5_leader or nullptr if not available.
destination - [in]
If destination is not nullptr, then the V6 leader is constructed
in destination. If destination is nullptr, then the new V6 leader
is allocated with a call to new ON_Leader().
*/
static ON_Leader* CreateFromV5Leader(
const class ON_OBSOLETE_V5_Leader& V5_leader,
const class ON_3dmAnnotationContext* annotation_context,
ON_Leader* destination
);
int Dimension() const override;
// virtual ON_Geometry GetBBox override
bool GetBBox( double* boxmin, double* boxmax, bool bGrowBox = false ) const override;
bool GetAnnotationBoundingBox(
const ON_Viewport* vp,
const ON_DimStyle* dimstyle,
double dimscale,
double* boxmin,
double* boxmax,
bool bGrow = false
) const override; // ON_Annotation override
bool Transform(const ON_Xform& xform) override;
bool GetTextGripPoints(
ON_2dPoint& base,
ON_2dPoint& width,
const ON_DimStyle* dimstyle,
double textscale) const;
//bool Explode(
// const ON_DimStyle* dimstyle,
// ON_SimpleArray<const ON_Geometry*> object_parts) const;
// Transforms text from natural position at origin to
// 3d location as it displays in the leader
bool GetTextXform(
const ON_Viewport* vp,
const ON_DimStyle* dimstyle,
double dimscale,
ON_Xform& text_xform_out
) const override;
bool GetTextXform(
const ON_Xform* model_xform,
const ON_Viewport* vp,
const ON_DimStyle* dimstyle,
double dimscale,
ON_Xform& text_xform_out
) const;
void UpdateTextAlignment(ON_2dVector angle); // Sets text to right or left justified per leader direction
const ON_NurbsCurve* Curve(
const ON_DimStyle* dimstyle
) const; // cached curve for display and picking
void DeleteCurve() const;
void SetPlane(ON_Plane plane);
//// TailDirection is the tangent direction
//// of the end of the leader tail
//// Returns 1,0 if there isn't a tangent
ON_2dVector TailDirection(const ON_DimStyle* dimstyle) const;
// These do nothing and return false if
// HasLanding is false
// Otherwise, they return a line added to the
// tail of the leader in the direction of
// LeaderContentAngleStyle()
bool LandingLine2d(
const ON_DimStyle* style,
double dimscale,
ON_Line& line) const;
bool LandingLine3d(
const ON_DimStyle* style,
double dimscale,
ON_Line& line) const;
ON__UINT32 PointCount() const;
void SetPoints2d(int count, const ON_2dPoint* points);
void SetPoints3d(int count, const ON_3dPoint* points);
bool SetPoint2d(int idx, ON_2dPoint point);
bool SetPoint3d(int idx, ON_3dPoint point);
void InsertPoint2d(int atidx, ON_2dPoint point);
void InsertPoint3d(int atidx, ON_3dPoint point);
void AppendPoint2d(ON_2dPoint point);
bool AppendPoint3d(ON_3dPoint point);
void RemovePoint(int idx);
bool Point2d(int idx, ON_2dPoint& point) const;
bool Point3d(int idx, ON_3dPoint& point) const;
bool GetTextPoint2d(
const ON_DimStyle* dimstyle,
double leaderscale,
ON_2dPoint& point) const;
//bool GetTextPoint3d(ON_3dPoint& point) const;
ON_2dPointArray& Points2d();
const ON_2dPointArray& Points2d() const;
void InvalidateTextPoint();
bool UpdateTextPosition(
const ON_DimStyle* dimstyle,
double leaderscale);
private:
ON_2dPointArray m_points;
// runtime
mutable ON_NurbsCurve* m_curve = nullptr; // Deleted by ~ON_Leader()
mutable ON_2dPoint m_text_point = ON_2dPoint::UnsetPoint;
};
#endif
+287
View File
@@ -0,0 +1,287 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_LIGHT_INC_)
#define OPENNURBS_LIGHT_INC_
class ON_CLASS ON_Light : public ON_Geometry
{
ON_OBJECT_DECLARE(ON_Light);
public:
ON_Light();
~ON_Light();
ON_Light& operator=(const ON_Light&) = default;
ON_Light(const ON_Light&) = default;
static const ON_Light Unset;
/////////////////////////////////////////////////////////////////
//
// ON_Object virtual functions
//
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
void Dump( ON_TextLog& ) const override; // for debugging
// Use ON_BinaryArchive::WriteObject() and ON_BinaryArchive::ReadObject()
// for top level serialization. These Read()/Write() members should just
// write/read specific definitions. In particular, they should not write/
// read any chunk typecode or length information. The default
// implementations return false and do nothing.
bool Write(
ON_BinaryArchive& // serialize definition to binary archive
) const override;
bool Read(
ON_BinaryArchive& // restore definition from binary archive
) override;
ON::object_type ObjectType() const override;
// virtual
ON_UUID ModelObjectId() const override;
/////////////////////////////////////////////////////////////////
//
// ON_Geometry virtual functions
//
int Dimension() const override;
// virtual ON_Geometry GetBBox override
bool GetBBox( double* boxmin, double* boxmax, bool bGrowBox = false ) const override;
bool Transform(
const ON_Xform&
) override;
/////////////////////////////////////////////////////////
//
// Interface
//
void Default(); // make default light
/////////////////////////////////////////////////////////
//
// turn light on/off
//
bool Enable( bool = true ); // returns previous state
bool IsEnabled() const;
/////////////////////////////////////////////////////////
//
// style, location, and direction
// direction is ignored for "point" and "ambient" lights
// location is ignored for "directional" and "ambient" lights
void SetStyle(ON::light_style);
ON::light_style Style() const;
const bool IsPointLight() const;
const bool IsDirectionalLight() const;
const bool IsSpotLight() const;
const bool IsLinearLight() const;
const bool IsRectangularLight() const;
ON::coordinate_system CoordinateSystem() const; // determined by style
/*
Description:
A light's location and direction can be defined with respect
to world, camera, or view coordinates. GetLightXform gets
the transformation from the light's intrinsic coordinate
system to the destination coordinate system specified
by dest_cs.
Parameters:
vp - [in] viewport where light is being used
dest_cs - [in] destination coordinate system
xform - [out] transformation from the light's intrinsic
coordinate system to cs.
Returns:
true if successful.
*/
bool GetLightXform(
const ON_Viewport& vp,
ON::coordinate_system dest_cs,
ON_Xform& xform
) const;
void SetLocation( const ON_3dPoint& );
void SetDirection( const ON_3dVector& );
ON_3dPoint Location() const;
ON_3dVector Direction() const;
ON_3dVector PerpindicularDirection() const;
double Intensity() const; // 0.0 = 0% 1.0 = 100% Only clamped above zero - no maximum.
void SetIntensity(double);
double PowerWatts() const;
double PowerLumens() const;
double PowerCandela() const;
void SetPowerWatts( double );
void SetPowerLumens( double );
void SetPowerCandela( double );
/////////////////////////////////////////////////////////
//
// colors
//
void SetAmbient( ON_Color );
void SetDiffuse( ON_Color );
void SetSpecular( ON_Color );
ON_Color Ambient() const;
ON_Color Diffuse() const;
ON_Color Specular() const;
/////////////////////////////////////////////////////////
//
// attenuation settings (ignored for "directional" and "ambient" lights)
// attenuation = 1/(a[0] + d*a[1] + d^2*a[2]) where d = distance to light
//
void SetAttenuation(double,double,double);
void SetAttenuation(const ON_3dVector&);
ON_3dVector Attenuation() const;
double Attenuation(double) const; // computes 1/(a[0] + d*a[1] + d^2*a[2]) where d = argument
// returns 0 if a[0] + d*a[1] + d^2*a[2] <= 0
/////////////////////////////////////////////////////////
//
// spot light parameters (ignored for non-spot lights)
//
// angle = 0 to 90 degrees
// exponent = 0 to 128 (0=uniform, 128=high focus)
//
void SetSpotAngleDegrees( double );
double SpotAngleDegrees() const;
void SetSpotAngleRadians( double );
double SpotAngleRadians() const;
//////////
// The spot exponent varies from 0.0 to 128.0 and provides
// an exponential interface for controling the focus or
// concentration of a spotlight (like the
// OpenGL GL_SPOT_EXPONENT parameter). The spot exponent
// and hot spot parameters are linked; changing one will
// change the other.
// A hot spot setting of 0.0 corresponds to a spot exponent of 128.
// A hot spot setting of 1.0 corresponds to a spot exponent of 0.0.
void SetSpotExponent( double );
double SpotExponent() const;
//////////
// The hot spot setting runs from 0.0 to 1.0 and is used to
// provides a linear interface for controling the focus or
// concentration of a spotlight.
// A hot spot setting of 0.0 corresponds to a spot exponent of 128.
// A hot spot setting of 1.0 corresponds to a spot exponent of 0.0.
void SetHotSpot( double );
double HotSpot() const;
// The spotlight radii are useful for display UI.
bool GetSpotLightRadii( double* inner_radius, double* outer_radius ) const;
/////////////////////////////////////////////////////////
//
// linear and rectangular light parameters
// (ignored for non-linear/rectangular lights)
//
void SetLength( const ON_3dVector& );
ON_3dVector Length() const;
void SetWidth( const ON_3dVector& );
ON_3dVector Width() const;
/////////////////////////////////////////////////////////
//
// shadow parameters (ignored for non-spot lights)
//
// shadow intensity 0.0 = does not cast any shadows
// 1.0 = casts black shadows
//
void SetShadowIntensity(double);
double ShadowIntensity() const;
/////////////////////////////////////////////////////////
//
// light index
//
void SetLightIndex( int );
int LightIndex() const;
/////////////////////////////////////////////////////////
//
// light name
//
void SetLightName( const char* );
void SetLightName( const wchar_t* );
const ON_wString& LightName() const;
public:
int m_light_index;
ON_UUID m_light_id;
ON_wString m_light_name;
bool m_bOn; // true if light is on
ON::light_style m_style; // style of light
ON_Color m_ambient;
ON_Color m_diffuse;
ON_Color m_specular;
ON_3dVector m_direction; // ignored for "point" and "ambient" lights
ON_3dPoint m_location; // ignored for "directional" and "ambient" lights
ON_3dVector m_length; // only for linear and rectangular lights
// ends of linear lights are m_location and m_location+m_length
ON_3dVector m_width; // only for rectangular lights
// corners of rectangular lights are m_location, m_location+m_length,
// m_location+m_width, m_location+m_width+m_length
double m_intensity; // Linear dimming/brightening factor: 0.0 = off, 1.0 = 100%.
// Values < 0.0 and values > 1.0 are permitted but are
// not consistently interpreted by various renderers.
// Renderers should clamp the range to [0.0, 1.0] if their
// lighting model does not support more exotic interpretations
// of m_intensity.
double m_watts; // Used by lighting models that reference lighting fixtures.
// Values < 0.0 are invalid. If m_watts is 0.0, the
// value is ignored.
// spot settings - ignored for non-spot lights
double m_spot_angle; // 0.0 to 90.0
double m_spot_exponent; // 0.0 to 128.0
// 0.0 = uniform
// 128.0 = high focus
double m_hotspot; // 0.0 to 1.0 (See SetHotSpot() for details)
// attenuation settings - ignored for "directional" and "ambient" lights
ON_3dVector m_attenuation; // each entry >= 0.0
// att = 1/(a[0] + d*a[1] + d^2*a[2])
// where d = distance to light
// shawdow casting
double m_shadow_intensity; // 0.0 = no shadow casting, 1.0 = full shadow casting
};
#endif
+606
View File
@@ -0,0 +1,606 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(ON_LINE_INC_)
#define ON_LINE_INC_
class ON_CLASS ON_Line
{
public:
static const ON_Line ZeroLine; // (ON_3dPoint::Origin, ON_3dPoint::Origin)
static const ON_Line UnsetLine; // (ON_3dPoint::UnsetPoint, ON_3dPoint::UnsetPoint)
static const ON_Line NanLine; // (ON_3dPoint::NanPoint, ON_3dPoint::NanPoint)
// Default constructor sets from = to = ON_3dPoint::Origin
ON_Line();
~ON_Line();
explicit ON_Line(
ON_3dPoint start,
ON_3dPoint end
);
explicit ON_Line(
ON_2dPoint start,
ON_2dPoint end
);
/*
Returns:
True if from != to and both from and to are valid.
*/
bool IsValid() const;
// line[0] = start point line[1] = end point
ON_3dPoint& operator[](int);
const ON_3dPoint& operator[](int) const;
// Description:
// Create a line from two points.
// Parameters:
// start - [in] point at start of line segment
// end - [in] point at end of line segment
// Returns:
// true if start and end are distinct points.
bool Create(
const ON_3dPoint start,
const ON_3dPoint end
);
bool Create(
const ON_2dPoint start,
const ON_2dPoint end
);
/*
Description:
Get line's 3d axis aligned bounding box.
Returns:
3d bounding box.
*/
ON_BoundingBox BoundingBox() const;
/*
Description:
Get line's 3d axis aligned bounding box or the
union of the input box with the object's bounding box.
Parameters:
bbox - [in/out] 3d axis aligned bounding box
bGrowBox - [in] (default=false)
If true, then the union of the input bbox and the
object's bounding box is returned in bbox.
If false, the object's bounding box is returned in bbox.
Returns:
true if object has bounding box and calculation was successful.
*/
bool GetBoundingBox(
ON_BoundingBox& bbox,
int bGrowBox = false
) const;
/*
Description:
Get tight bounding box.
Parameters:
tight_bbox - [in/out] tight bounding box
bGrowBox -[in] (default=false)
If true and the input tight_bbox is valid, then returned
tight_bbox is the union of the input tight_bbox and the
line's tight bounding box.
xform -[in] (default=nullptr)
If not nullptr, the tight bounding box of the transformed
line is calculated. The line is not modified.
Returns:
True if a valid tight_bbox is returned.
*/
bool GetTightBoundingBox(
ON_BoundingBox& tight_bbox,
bool bGrowBox = false,
const ON_Xform* xform = nullptr
) const;
/*
Description:
Get a plane that contains the line.
Parameters:
plane - [out] a plane that contains the line. The orgin
of the plane is at the start of the line. The distance
from the end of the line to the plane is <= tolerance.
If possible a plane parallel to the world xy, yz or zx
plane is returned.
tolerance - [in]
Returns:
true if a coordinate of the line's direction vector is
larger than tolerance.
*/
bool InPlane( ON_Plane& plane, double tolerance = 0.0 ) const;
// Returns:
// Length of line
double Length() const;
// Returns:
// direction vector = line.to - line.from
// See Also:
// ON_Line::Tangent
ON_3dVector Direction() const;
// Returns:
// Unit tangent vector.
// See Also:
// ON_Line::Direction
ON_3dVector Tangent() const;
/*
Description:
Evaluate point on (infinite) line.
Parameters:
t - [in] evaluation parameter. t=0 returns line.from
and t=1 returns line.to.
Returns:
(1-t)*line.from + t*line.to.
See Also:
ON_Line::Direction
ON_Line::Tangent
*/
ON_3dPoint PointAt(
double t
) const;
/*
Description:
Find the point on the (infinite) line that is
closest to the test_point.
Parameters:
test_point - [in]
t - [out] line.PointAt(*t) is the point on the line
that is closest to test_point.
Returns:
true if successful.
*/
bool ClosestPointTo(
const ON_3dPoint& test_point,
double* t
) const;
/*
Description:
Find the point on the (infinite) line that is
closest to the test_point.
Parameters:
test_point - [in]
Returns:
The point on the line that is closest to test_point.
*/
ON_3dPoint ClosestPointTo(
const ON_3dPoint& test_point
) const;
/*
Description:
Find the point on the (infinite) line that is
closest to the test_point.
Parameters:
test_point - [in]
Returns:
distance from the point on the line that is closest
to test_point.
See Also:
ON_3dPoint::DistanceTo
ON_Line::ClosestPointTo
*/
double DistanceTo( ON_3dPoint test_point ) const;
/*
Description:
Finds the shortest distance between the line as a finite
chord and the other object.
Parameters:
P - [in]
L - [in] (another finite chord)
Returns:
A value d such that if Q is any point on
this line and P is any point on the other object,
then d <= Q.DistanceTo(P).
*/
double MinimumDistanceTo( const ON_3dPoint& P ) const;
double MinimumDistanceTo( const ON_Line& L ) const;
/*
Description:
Finds the longest distance between the line as a finite
chord and the other object.
Parameters:
P - [in]
L - [in] (another finite chord)
Returns:
A value d such that if Q is any point on this line and P is any
point on the other object, then d >= Q.DistanceTo(P).
*/
double MaximumDistanceTo( const ON_3dPoint& P ) const;
double MaximumDistanceTo( const ON_Line& other ) const;
/*
Description:
Quickly determine if the shortest distance from
this line to the other object is greater than d.
Parameters:
d - [in] distance (> 0.0)
P - [in]
L - [in]
Returns:
True if if the shortest distance from this line
to the other object is greater than d.
*/
bool IsFartherThan( double d, const ON_3dPoint& P ) const;
bool IsFartherThan( double d, const ON_Line& L ) const;
// For intersections see ON_Intersect();
// Description:
// Reverse line by swapping from and to.
void Reverse();
bool Transform(
const ON_Xform& xform
);
// rotate line about a point and axis
bool Rotate(
double sin_angle,
double cos_angle,
const ON_3dVector& axis_of_rotation,
const ON_3dPoint& center_of_rotation
);
bool Rotate(
double angle_in_radians,
const ON_3dVector& axis_of_rotation,
const ON_3dPoint& center_of_rotation
);
bool Translate(
const ON_3dVector& delta
);
public:
ON_3dPoint from; // start point
ON_3dPoint to; // end point
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_Line>;
#endif
/*
Returns:
True if a and be are identical and no coordinate is a nan.
*/
ON_DECL
bool operator==(const ON_Line& a, const ON_Line& b);
/*
Returns:
True if a and be are not identical.
Remarks:
If a nan is involved in every coordinate compare,
the result will be false.
*/
ON_DECL
bool operator!=(const ON_Line& a, const ON_Line& b);
class ON_CLASS ON_Triangle
{
public:
static const ON_Triangle ZeroTriangle; // {ON_3dPoint::Origin, ON_3dPoint::Origin, ON_3dPoint::Origin}
static const ON_Triangle UnsetTriangle; // {ON_3dPoint::UnsetPoint, ON_3dPoint::UnsetPoint, ON_3dPoint::UnsetPoint}
static const ON_Triangle NanTriangle; // {ON_3dPoint::NanPoint, ON_3dPoint::NanPoint, ON_3dPoint::NanPoint}
ON_Triangle() = default; // Default constructor is uninitialized
ON_Triangle(const ON_3dPoint vertices[3]);
ON_Triangle(const ON_3dPoint& a, const ON_3dPoint& b, const ON_3dPoint& c);
ON_Triangle(double x); // Allows Triangle(0.0) ZeroTriangle
ON_Triangle(const double vertices[9]);
ON_Triangle(const ON_Triangle& tri) = default;
ON_Triangle& operator=(const ON_Triangle& tri) = default;
~ON_Triangle() = default;
operator ON_3dPoint*();
operator const ON_3dPoint*() const;
/*
Returns:
True if m_V[i].IsValid() for all i
*/
bool IsValid() const;
// Triangle[i] = Triangle.m_V[i]
ON_3dPoint& operator[](int);
const ON_3dPoint& operator[](int) const;
// Description:
// Create a Triangle from three points.
// Parameters:
// vertices - [in] vertices
void Create(const ON_3dPoint vertices[3]);
// Description:
// Create a Triangle from three points.
// Parameters:
// a,b,c - [in] vertices
void Create(const ON_3dPoint& a, const ON_3dPoint& b, const ON_3dPoint& c);
/*
Description:
Get Triangles 3d axis aligned bounding box.
Returns:
3d bounding box.
*/
ON_BoundingBox BoundingBox() const;
/*
Description:
Get line's 3d axis aligned bounding box or the
union of the input box with the object's bounding box.
Parameters:
bbox - [in/out] 3d axis aligned bounding box
bGrowBox - [in] (default=false)
If true, then the union of the input bbox and the
object's bounding box is returned in bbox.
If false, the object's bounding box is returned in bbox.
Returns:
true if object has bounding box and calculation was successful.
*/
bool GetBoundingBox(
ON_BoundingBox& bbox,
int bGrowBox = false
) const;
/*
Description:
Get tight bounding box with respect to a given frame
Parameters:
tight_bbox - [in/out] tight bounding box
bGrowBox -[in] (default=false)
If true and the input tight_bbox is valid, then returned
tight_bbox is the union of the input tight_bbox and the
line's tight bounding box.
xform -[in] (default=nullptr)
If not nullptr, the tight bounding box of the transformed
triangle is calculated. The triangle is not modified.
Returns:
True if a valid tight_bbox is returned.
*/
bool GetTightBoundingBox(
ON_BoundingBox& tight_bbox,
bool bGrowBox = false,
const ON_Xform* xform = nullptr
) const;
// Returns:
// Index of edge opposite to m_V[i] that is longest.
// When lenghts are equal, lowest index has priority.
unsigned char LongestEdge() const;
// Returns:
// Index of edge opposite to m_V[i] that is shortest.
// When lenghts are equal, lowest index has priority.
unsigned char ShortestEdge() const;
// Returns:
// Edge opposite m_V[i]
// Specifically,
// ON_Line( m_V[(i+1)%3 ], m_V[(i+2)%3 ] )
ON_Line Edge(int i) const;
// Returns:
// true if Area()< tol
// Note:
// Recall Area = .5* base * height. So this degeneracy tests for
// a combination long enough and high enough.
// See Also:
// ON_Triangle::Area()
bool IsDegenerate(double tol = ON_ZERO_TOLERANCE) const;
// Returns:
// Area of triangle
double Area() const;
// Returns:
// N = ( b-a) X ( c-a)
// where a,b,c are the verticies
// See Also:
// ON_Triangle UnitNormal()
ON_3dVector Normal() const;
// Returns:
// Normal().Unitize()
// Notes:
// Ensure !IsDegenerate() to gaurentee that UnitNormal().Length()==1
// and the result is not just a bunch of noise. Can return zero vector
// in some degenerate cases.
ON_3dVector UnitNormal() const;
// Returns:
// Plane containing Triangle with normal given by UnitNormal().
// Notes:
// Ensure !IsDegenerate() to gaurentee meaningful result
ON_PlaneEquation PlaneEquation() const;
/*
Description:
Evaluate point on triangle.
Parameters:
s1, s2 - [in] evaluation parameter.
Returns:
(1-s1-s2)* m_V[0] + s1*m_V[1] + s2*m_V[2]
Notes:
Point is in the triangle iff s1>=0, s2>=0 and s1 + s2<=1.
Other values produce points on the plane of the triangle.
*/
ON_3dPoint PointAt(
double s1, double s2
) const;
// Returns:
// Evaluation of PointAt(1/3.0, 1/3.0);
ON_3dPoint Centroid() const;
/*
Description:
Find the point on the triangle that is
closest to the test_point.
Parameters:
test_point - [in]
s1, s2 - [out] PointAt( *s1, *s2) is the point on the
triangle closest to test_point.
Returns:
true if successful.
*/
bool ClosestPointTo(
const ON_3dPoint& test_point,
double* s1, double *s2
) const;
/*
Description:
Find the point that is closest to the test_point.
Parameters:
test_point - [in]
constrainInside[in] - if true, variable are inside triangle
s1, s2 - [out] PointAt( *s1, *s2) is the point on the
triangle closest to test_point.
Returns:
true if successful.
*/
bool GetBarycentricCoordinates(
const ON_3dPoint& test_point,
bool constrainInside,
double* s1, double *s2
) const;
/*
Description:
Find the point on the triangle that is
closest to the test_point.
Parameters:
test_point - [in]
Returns:
The point on the line that is closest to test_point.
*/
ON_3dPoint ClosestPointTo(
const ON_3dPoint& test_point
) const;
/*
Description:
Find the point on the triangle that is
closest to the test_point.
Parameters:
test_point -[in]
Returns:
distance from the point on triangle that is closest
to test_point.
See Also:
ON_3dPoint::DistanceTo
ON_Line::ClosestPointTo
*/
double DistanceTo(const ON_3dPoint& test_point) const;
// Description:
// Reverse endpoints of Edge[i].
void Reverse(int i);
bool Transform(
const ON_Xform& xform
);
// rotate line about a point and axis
bool Rotate(
double sin_angle,
double cos_angle,
const ON_3dVector& axis_of_rotation,
const ON_3dPoint& center_of_rotation
);
bool Rotate(
double angle_in_radians,
const ON_3dVector& axis_of_rotation,
const ON_3dPoint& center_of_rotation
);
bool Translate(
const ON_3dVector& delta
);
// Description:
// Split the triangles into two, by choosing an edge and a new point that will appear along the edge.
// Parameters:
// edge - [in] Edge index as defined in Edge()
// pt - [in] Point to add as splitter along edge
// out_a - [out] First triangle
// out_b - [out] Second triangle
void Split(unsigned char edge, ON_3dPoint pt, ON_Triangle& out_a, ON_Triangle& out_b) const;
// Description:
// Flip the normal of the triangle, by swapping the points of an edge.
// Parameters:
// edge - [in] The edge, as defined in the Edge() method. I.e., edge 0 swaps m_V[1] and m_V[2]
void Flip(unsigned char edge = 0);
// Description:
// Circle the order of points in the triangle, without any influence to any geometric property.
// Parameters:
// move - [in] Amounts of rotations in the order of the three points.
// By means of examples, "move" of 1 will move m_V[0] to m_V[1],
// m_V[1] to m_V[2] and m_V[2] to m_V[0].
void Spin(unsigned char move);
public:
ON_3dPoint m_V[3]; // verticies
};
/*
Returns:
True if a and be are identical and no coordinate is a nan.
*/
ON_DECL
bool operator==(const ON_Triangle& a, const ON_Triangle& b);
/*
Returns:
True if a and be are not identical.
Remarks:
If a nan is involved in every coordinate compare,
the result will be false.
*/
ON_DECL
bool operator!=(const ON_Triangle& a, const ON_Triangle& b);
#endif
+385
View File
@@ -0,0 +1,385 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(ON_GEOMETRY_CURVE_LINE_INC_)
#define ON_GEOMETRY_CURVE_LINE_INC_
class ON_LineCurve;
class ON_CLASS ON_LineCurve : public ON_Curve
{
ON_OBJECT_DECLARE(ON_LineCurve);
public:
ON_LineCurve() ON_NOEXCEPT;
virtual ~ON_LineCurve();
ON_LineCurve(const ON_LineCurve&);
ON_LineCurve& operator=(const ON_LineCurve&);
#if defined(ON_HAS_RVALUEREF)
// rvalue copy constructor
ON_LineCurve( ON_LineCurve&& ) ON_NOEXCEPT;
// The rvalue assignment operator calls ON_Object::operator=(ON_Object&&)
// which could throw exceptions. See the implementation of
// ON_Object::operator=(ON_Object&&) for details.
ON_LineCurve& operator=( ON_LineCurve&& );
#endif
ON_LineCurve(const ON_2dPoint&,const ON_2dPoint&); // creates a 2d line curve
ON_LineCurve(const ON_3dPoint&,const ON_3dPoint&); // creates a 3d line curve
ON_LineCurve(const ON_Line&);
ON_LineCurve(const ON_Line&,
double,double // domain
);
ON_LineCurve& operator=(const ON_Line&);
/////////////////////////////////////////////////////////////////
// ON_Object overrides
// virtual ON_Object::SizeOf override
unsigned int SizeOf() const override;
// virtual ON_Object::DataCRC override
ON__UINT32 DataCRC(ON__UINT32 current_remainder) const override;
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
void Dump( ON_TextLog& ) const override; // for debugging
bool Write(
ON_BinaryArchive& // open binary file
) const override;
bool Read(
ON_BinaryArchive& // open binary file
) override;
/////////////////////////////////////////////////////////////////
// ON_Geometry overrides
int Dimension() const override;
// virtual ON_Geometry GetBBox override
bool GetBBox( double* boxmin, double* boxmax, bool bGrowBox = false ) const override;
// virtual ON_Geometry GetTightBoundingBox override
bool GetTightBoundingBox( class ON_BoundingBox& tight_bbox, bool bGrowBox = false, const class ON_Xform* xform = nullptr ) const override;
bool Transform(
const ON_Xform&
) override;
// virtual ON_Geometry::IsDeformable() override
bool IsDeformable() const override;
// virtual ON_Geometry::MakeDeformable() override
bool MakeDeformable() override;
bool SwapCoordinates(
int, int // indices of coords to swap
) override;
/////////////////////////////////////////////////////////////////
// ON_Curve overrides
ON_Interval Domain() const override;
// Description:
// Set the domain of the curve
// Parameters:
// t0 - [in]
// t1 - [in] new domain will be [t0,t1]
// Returns:
// true if successful.
bool SetDomain(
double t0,
double t1
) override;
bool ChangeDimension(
int desired_dimension
) override;
int SpanCount() const override; // number of smooth spans in curve
bool GetSpanVector( // span "knots"
double* // array of length SpanCount() + 1
) const override; //
int Degree( // returns maximum algebraic degree of any span
// ( or a good estimate if curve spans are not algebraic )
) const override;
bool IsLinear( // true if curve locus is a line segment between
// between specified points
double = ON_ZERO_TOLERANCE // tolerance to use when checking linearity
) const override;
/*
Description:
Several types of ON_Curve can have the form of a polyline including
a degree 1 ON_NurbsCurve, an ON_PolylineCurve, and an ON_PolyCurve
all of whose segments are some form of polyline. IsPolyline tests
a curve to see if it can be represented as a polyline.
Parameters:
pline_points - [out] if not nullptr and true is returned, then the
points of the polyline form are returned here.
t - [out] if not nullptr and true is returned, then the parameters of
the polyline points are returned here.
Returns:
@untitled table
0 curve is not some form of a polyline
>=2 number of points in polyline form
*/
//virtual
int IsPolyline(
ON_SimpleArray<ON_3dPoint>* pline_points = nullptr,
ON_SimpleArray<double>* pline_t = nullptr
) const override;
bool IsArc( // ON_Arc.m_angle > 0 if curve locus is an arc between
// specified points
const ON_Plane* = nullptr, // if not nullptr, test is performed in this plane
ON_Arc* = nullptr, // if not nullptr and true is returned, then arc parameters
// are filled in
double = ON_ZERO_TOLERANCE // tolerance to use when checking
) const override;
bool IsPlanar(
ON_Plane* = nullptr, // if not nullptr and true is returned, then plane parameters
// are filled in
double = ON_ZERO_TOLERANCE // tolerance to use when checking
) const override;
bool IsInPlane(
const ON_Plane&, // plane to test
double = ON_ZERO_TOLERANCE // tolerance to use when checking
) const override;
bool IsClosed( // true if curve is closed (either curve has
void // clamped end knots and euclidean location of start
) const override; // CV = euclidean location of end CV, or curve is
// periodic.)
bool IsPeriodic( // true if curve is a single periodic segment
void
) const override;
/*
Description:
Force the curve to start at a specified point.
Parameters:
start_point - [in]
Returns:
true if successful.
Remarks:
Some end points cannot be moved. Be sure to check return
code.
See Also:
ON_Curve::SetEndPoint
ON_Curve::PointAtStart
ON_Curve::PointAtEnd
*/
bool SetStartPoint(
ON_3dPoint start_point
) override;
/*
Description:
Force the curve to end at a specified point.
Parameters:
end_point - [in]
Returns:
true if successful.
Remarks:
Some end points cannot be moved. Be sure to check return
code.
See Also:
ON_Curve::SetStartPoint
ON_Curve::PointAtStart
ON_Curve::PointAtEnd
*/
bool SetEndPoint(
ON_3dPoint end_point
) override;
bool Reverse() override; // reverse parameterizatrion
// Domain changes from [a,b] to [-b,-a]
bool Evaluate( // returns false if unable to evaluate
double, // evaluation parameter
int, // number of derivatives (>=0)
int, // array stride (>=Dimension())
double*, // array of length stride*(ndir+1)
int = 0, // optional - determines which side to evaluate from
// 0 = default
// < 0 to evaluate from below,
// > 0 to evaluate from above
int* = 0 // optional - evaluation hint (int) used to speed
// repeated evaluations
) const override;
// Description:
// virtual ON_Curve::Trim override.
// Removes portions of the curve outside the specified interval.
// Parameters:
// domain - [in] interval of the curve to keep. Portions of the
// curve before curve(domain[0]) and after curve(domain[1]) are
// removed.
// Returns:
// true if successful.
bool Trim(
const ON_Interval& domain
) override;
// Description:
// Where possible, analytically extends curve to include domain.
// Parameters:
// domain - [in] if domain is not included in curve domain,
// curve will be extended so that its domain includes domain.
// Original curve is identical
// to the restriction of the resulting curve to the original curve domain,
// Returns:
// true if successful.
bool Extend(
const ON_Interval& domain
) override;
// Description:
// virtual ON_Curve::Split override.
// Divide the curve at the specified parameter. The parameter
// must be in the interior of the curve's domain. The pointers
// passed to Split must either be nullptr or point to an ON_Curve
// object of the same of the same type. If the pointer is nullptr,
// then a curve will be created in Split(). You may pass "this"
// as one of the pointers to Split().
// Parameters:
// t - [in] parameter in interval Domain().
// left_side - [out] left portion of curve
// right_side - [out] right portion of curve
// Example:
// For example, if crv were an ON_NurbsCurve, then
//
// ON_NurbsCurve right_side;
// crv.Split( crv.Domain().Mid() &crv, &right_side );
//
// would split crv at the parametric midpoint, put the left side
// in crv, and return the right side in right_side.
bool Split(
double t, // t = curve parameter to split curve at
ON_Curve*& left_side, // left portion returned here
ON_Curve*& right_side // right portion returned here
) const override;
// Description:
// virtual ON_Curve::GetNurbForm override.
// Get a NURBS curve representation of this curve.
// Parameters:
// nurbs_curve - [out] NURBS representation returned here
// tolerance - [in] tolerance to use when creating NURBS
// representation.
// subdomain - [in] if not nullptr, then the NURBS representation
// for this portion of the curve is returned.
// Returns:
// 0 unable to create NURBS representation
// with desired accuracy.
// 1 success - returned NURBS parameterization
// matches the curve's to wthe desired accuracy
// 2 success - returned NURBS point locus matches
// the curve's to the desired accuracy but, on
// the interior of the curve's domain, the
// curve's parameterization and the NURBS
// parameterization may not match to the
// desired accuracy.
int GetNurbForm(
ON_NurbsCurve&,
double = 0.0,
const ON_Interval* = nullptr
) const override;
// Description:
// virtual ON_Curve::HasNurbForm override.
// Does a NURBS curve representation of this curve exist.
// Parameters:
// Returns:
// 0 unable to create NURBS representation
// with desired accuracy.
// 1 success - returned NURBS parameterization
// matches the curve's to wthe desired accuracy
// 2 success - returned NURBS point locus matches
// the curve's to the desired accuracy but, on
// the interior of the curve's domain, the
// curve's parameterization and the NURBS
// parameterization may not match to the
// desired accuracy.
int HasNurbForm(
) const override;
// Description:
// virtual ON_Curve::GetCurveParameterFromNurbFormParameter override.
// Convert a NURBS curve parameter to a curve parameter
//
// Parameters:
// nurbs_t - [in] nurbs form parameter
// curve_t - [out] curve parameter
//
// Remarks:
// If GetNurbForm returns 2, this function converts the curve
// parameter to the NURBS curve parameter.
//
// See Also:
// ON_Curve::GetNurbForm, ON_Curve::GetNurbFormParameterFromCurveParameter
//virtual
bool GetCurveParameterFromNurbFormParameter(
double nurbs_t,
double* curve_t
) const override;
// Description:
// virtual ON_Curve::GetNurbFormParameterFromCurveParameter override.
// Convert a curve parameter to a NURBS curve parameter.
//
// Parameters:
// curve_t - [in] curve parameter
// nurbs_t - [out] nurbs form parameter
//
// Remarks:
// If GetNurbForm returns 2, this function converts the curve
// parameter to the NURBS curve parameter.
//
// See Also:
// ON_Curve::GetNurbForm, ON_Curve::GetCurveParameterFromNurbFormParameter
//virtual
bool GetNurbFormParameterFromCurveParameter(
double curve_t,
double* nurbs_t
) const override;
/////////////////////////////////////////////////////////////////
// Interface
ON_Line m_line;
ON_Interval m_t; // domain
int m_dim; // 2 or 3 (2 so ON_LineCurve can be uses as a trimming curve)
};
#endif
+139
View File
@@ -0,0 +1,139 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_LINESTYLE_INC_)
#define OPENNURBS_LINESTYLE_INC_
///////////////////////////////////////////////////////////////////////////////
//
// Class ON_DisplayMaterialRef
//
/*
Description:
Objects can have per viewport display properties
that override a viewport's default display
properties. These overrides are stored on
ON_3dmObjectAttributes as a list of
ON_DisplayMaterialRefs.
Example:
For example, by default a viewport
might display objects using a wireframe, but
one special object may need to be shaded.
In this case the special object would have
a display material ref with the "wireframe"
viewport's id and the id of a display material
that specified shading.
*/
class ON_CLASS ON_DisplayMaterialRef
{
public:
/*
Description:
Default constructor sets both ids to nil.
*/
ON_DisplayMaterialRef();
int Compare(const ON_DisplayMaterialRef& other) const;
bool operator==(const ON_DisplayMaterialRef& other) const;
bool operator!=(const ON_DisplayMaterialRef& other) const;
bool operator<(const ON_DisplayMaterialRef& other) const;
bool operator<=(const ON_DisplayMaterialRef& other) const;
bool operator>(const ON_DisplayMaterialRef& other) const;
bool operator>=(const ON_DisplayMaterialRef& other) const;
// C++ default destructor, copy constructor and operator=
// work fine.
ON_UUID m_viewport_id; // identifies the ON_Viewport
// If nil, then the display material
// will be used in all viewports
// that are not explictly referenced
// in other ON_DisplayMaterialRefs.
ON_UUID m_display_material_id; // id used to find display attributes
// For Rhino V4 the per detail visibility attribute is implemented
// through a display material reference on an object. This is ONLY
// for for detail viewports and only for V4. Keep this uuid around
// so the per detail attributes in future versions of Rhino can be
// implemented a different way.
// {1403A7E4-E7AD-4a01-A2AA-41DAE6BE7ECB}
static const ON_UUID m_invisible_in_detail_id;
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_DisplayMaterialRef>;
#endif
//////////////////////////////////////////////////////////////////////
// class ON_LinetypeSegment
class ON_CLASS ON_LinetypeSegment
{
public:
static const ON_LinetypeSegment Unset;
static const ON_LinetypeSegment OneMillimeterLine;
public:
ON_LinetypeSegment() = default;
~ON_LinetypeSegment() = default;
ON_LinetypeSegment(const ON_LinetypeSegment&) = default;
ON_LinetypeSegment& operator=(const ON_LinetypeSegment&) = default;
bool operator==( const ON_LinetypeSegment& src) const;
bool operator!=( const ON_LinetypeSegment& src) const;
// For a curve to be drawn starting at the start point
// and ending at the endpoint, the first segment
// in the pattern must be a stLine type
enum class eSegType : unsigned int
{
Unset = 0,
stLine = 1,
stSpace = 2
};
static ON_LinetypeSegment::eSegType SegmentTypeFromUnsigned(
unsigned int segment_type_as_unsigned
);
ON_LinetypeSegment(
double segment_length,
ON_LinetypeSegment::eSegType segment_type
);
void Dump( class ON_TextLog& ) const;
// do not add read/write functions to this class
double m_length = 0.0; // length in millimeters on printed output
eSegType m_seg_type = ON_LinetypeSegment::eSegType::Unset;
private:
unsigned int m_reserved2 = 0;
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_LinetypeSegment>;
#endif
#endif
+219
View File
@@ -0,0 +1,219 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_LINETYPE_INC_)
#define OPENNURBS_LINETYPE_INC_
// Description:
// Determine if a line width is deemed to be a "hairline width" in Rhino
// Any width that is >0 and < 0.001 mm is a hairline width for printing
// Parameters:
// width_mm: [in] the width to examine in millimeters
// Returns:
// true if this is a hairline width
ON_DECL bool ON_IsHairlinePrintWidth( double width_mm );
// Description:
// Return a width in millimeters that is a valid hairline width in rhino
ON_DECL double ON_HairlinePrintWidth();
//////////////////////////////////////////////////////////////////////
// class ON_Linetype
class ON_CLASS ON_Linetype : public ON_ModelComponent
{
ON_OBJECT_DECLARE(ON_Linetype);
public:
// no attributes are set.
static const ON_Linetype Unset;
// index = -1, id, name and pattern are set.
static const ON_Linetype Continuous;
// index = -2, id, name and pattern are set.
static const ON_Linetype ByLayer;
// index = -3, id, name and pattern are set.
static const ON_Linetype ByParent;
// index = -4, id, name and pattern are set.
static const ON_Linetype Hidden;
// index = -5, id, name and pattern are set.
static const ON_Linetype Dashed;
// index = -6, id, name and pattern are set.
static const ON_Linetype DashDot;
// index = -7, id, name and pattern are set.
static const ON_Linetype Center;
// index = -8, id, name and pattern are set.
static const ON_Linetype Border;
// index = -9, id, name and pattern are set.
static const ON_Linetype Dots;
/*
Parameters:
model_component_reference - [in]
none_return_value - [in]
value to return if ON_Linetype::Cast(model_component_ref.ModelComponent())
is nullptr
Returns:
If ON_Linetype::Cast(model_component_ref.ModelComponent()) is not nullptr,
that pointer is returned. Otherwise, none_return_value is returned.
*/
static const ON_Linetype* FromModelComponentRef(
const class ON_ModelComponentReference& model_component_reference,
const ON_Linetype* none_return_value
);
public:
ON_Linetype() ON_NOEXCEPT;
~ON_Linetype() = default;
ON_Linetype(const ON_Linetype&);
ON_Linetype& operator=(const ON_Linetype&) = default;
/*
Description:
Tests that name is set and there is at least one non-zero length segment
*/
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
void Dump( ON_TextLog& ) const override; // for debugging
/*
Description:
Write to file
*/
bool Write(
ON_BinaryArchive& // serialize definition to binary archive
) const override;
/*
Description:
Read from file
*/
bool Read(
ON_BinaryArchive& // restore definition from binary archive
) override;
//////////////////////////////////////////////////////////////////////
//
// Interface
bool PatternIsSet() const;
bool ClearPattern();
bool PatternIsLocked() const;
void LockPattern();
/*
Description:
Returns the total length of one repeat of the pattern
*/
double PatternLength() const;
/*
Description:
Returns the number of segments in the pattern
*/
int SegmentCount() const;
/*
Description:
Adds a segment to the pattern
Returns:
Index of the added segment.
*/
int AppendSegment( const ON_LinetypeSegment& segment);
/*
Description:
Removes a segment in the linetype.
Parameters:
index - [in]
Zero based index of the segment to remove.
Returns:
True if the segment index was removed.
*/
bool RemoveSegment( int index );
/*
Description:
Sets the segment at index to match segment
*/
bool SetSegment( int index, const ON_LinetypeSegment& segment);
/*
Description:
Sets the length and type of the segment at index
*/
bool SetSegment( int index, double length, ON_LinetypeSegment::eSegType type);
/*
Description:
Set all segments
Parameters:
segments - [in]
*/
bool SetSegments(const ON_SimpleArray<ON_LinetypeSegment>& segments);
/*
Description:
Returns a copy of the segment at index
*/
ON_LinetypeSegment Segment( int index) const;
/*
Description:
Expert user function to get access to the segment array
for rapid calculations.
*/
// Returns nullptr if the line pattern is locked.
ON_SimpleArray<ON_LinetypeSegment>* ExpertSegments();
const ON_SimpleArray<ON_LinetypeSegment>& Segments() const;
private:
enum : unsigned char
{
pattern_bit = 1
};
unsigned char m_is_set_bits = 0;
unsigned char m_is_locked_bits = 0;
unsigned short m_reserved1 = 0;
unsigned int m_reserved2 = 0;
ON_SimpleArray<ON_LinetypeSegment> m_segments;
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_Linetype*>;
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<const ON_Linetype*>;
ON_DLL_TEMPLATE template class ON_CLASS ON_ObjectArray<ON_Linetype>;
#endif
#endif
+713
View File
@@ -0,0 +1,713 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2014 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_LOCALE_INC_)
#define OPENNURBS_LOCALE_INC_
typedef
#if defined(ON_RUNTIME_WIN)
_locale_t
#elif defined(ON_RUNTIME_APPLE)
locale_t
#elif defined(ON_RUNTIME_ANDROID)
locale_t
#else
ON__UINT_PTR
#endif
ON_CRT_locale_t;
class ON_CLASS ON_Locale
{
public:
enum WindowsLCID : unsigned int
{
OrdinalLCID = 0, // not a real Windows LCID
InvariantCultureLCID = 0x0027, // 39 decimal
// Windows LCID for languages Rhino supports
// "cs-CZ" Czech, ???? script implied
cs_CZ_LCID = 0x0405, //1029 decimal
// "de-DE" German, Germany, Latn script implied
de_DE_LCID = 0x0407, // 1031 decimal
// "en-US" English, US, Latn script implied
en_US_LCID = 0x0409, // 1033 decimal
// "en-CA" English, Canada, Latn script implied
en_CA_LCID = 0x1009, // 4105 decimal
// "es-ES_tradnl" Spanish, Spain, Latn script implied, traditional sort
es_ES_tradnl_LCID = 0x040A, // 1034 decimal
// "es-ES" Spanish, Spain, Latn script implied, modern sort
es_ES_LCID = 0x0c0a, // 3082 decimal
// "fr-FR" French, France, Latn script implied
fr_FR_LCID = 0x040c, // 1036 decimal
// "it-IT" Italian, Italy, Latn script implied
it_IT_LCID = 0x0410, // 1040 decimal
// "ja-JP" Japanese, Japan, ???? script implied
ja_JP_LCID = 0x0411, // 1041 decimal
// Korean, Republic of Korea, ???? script implied
ko_KR_LCID = 0x0412, // 1042 decimal
// Polish, Poland, ???? script implied
pl_PL_LCID = 0x0415, // 1045 decimal
// Portuguese, Portugal, Latn script implied
pt_PT_LCID = 0x0816, // 2070 decimal
// According to https://en.wikipedia.org/wiki/Chinese_language, Chinese is a family of language
// varieties, often mutually unintelligible. Specifying both Script and REGION
// (zh-Hans-CN or zh-Hant-TW) doesn't narrow things down nearly enough.
//
// Basically we have to hope the string collate and mapping functions supplied by the OS and
// the translations supplied by our staff work well for our customers who select from the
// two types of "Chinese" Rhino offers.
//
// Standard Chinese (Mandarin), Peoples Republic of China, Hans script implied (simplified characters)
zh_CN_LCID = 0x0804, // 2052 decimal
// Standard Chinese (Mandarin), Taiwan, Hant script implied (traditional characters)
zh_TW_LCID = 0x0404 // 1028 decimal
};
// The ordinal locale.
// String compares use ordinal element values.
// The decimal point is a period.
static const ON_Locale Ordinal;
// The invariant culture locale.
// The decimal point is a period.
static const ON_Locale InvariantCulture;
private:
static ON_Locale m_CurrentCulture;
public:
// Reference to ON_Locale::m_CurrentCulture.
// The value is set by calling ON_Locale::SetCurrentCulture();
// The default is a copy of ON_Locale::Ordinal.
static const ON_Locale& CurrentCulture;
/*
Description:
Set the current culture locale
Parameters:
current_culture_locale - [in]
*/
static bool SetCurrentCulture(
const ON_Locale& current_culture_locale
);
// Default construction creates a copy of ON_Local::Ordinal
ON_Locale() ON_NOEXCEPT;
~ON_Locale() = default;
ON_Locale(const ON_Locale&) = default;
ON_Locale& operator=(const ON_Locale&) = default;
// Maximum buffer capacity for any ON_Locale functions
// that return string information in a buffer.
enum
{
BUFFER_MAXIMUM_CAPACITY = 128
};
/*
Description:
Get the language id.
Parameters:
buffer - [out]
A null terminated string containing the language id is returned in this buffer.
The string has the form:
<language>[-<Script>][-<REGION>]
<language>
ISO 639 language code.
http://www.iso.org/iso/language_codes
<Script> is optional.
If present, it is a 4 alpha letter ISO 15924 script code
http://www.unicode.org/iso15924/iso15924-codes.html
<REGION>
ISO 3166-1 country/region identifier. (2 alpha letters)
or UN M.49 code (3 digits)
http://www.iso.org/iso/home/standards/country_codes.htm
buffer_capacity - [in]
number of elements in the buffer.
A capacity >= ON_Locale::BUFFER_MAXIMUM_CAPACITY will be large enough to
hold all possible output.
Returns:
If buffer_capacity is to small or buffer is nullptr, then nullptr is returned.
Otherwise the pointer to buffer is returned.
Remarks:
The Invariant language name is the empty string "".
*/
const char* GetBCP47LanguageTag(
char* buffer,
size_t buffer_capacity
) const;
const wchar_t* GetBCP47LanguageTag(
wchar_t* buffer,
size_t buffer_capacity
) const;
/*
Parameters:
A string of the form
<language>[-<Script>][-<REGION>]
<language>
ISO 639 language code.
http://www.iso.org/iso/language_codes
<Script> is optional.
If present, it is a 4 alpha letter ISO 15924 script code
http://www.unicode.org/iso15924/iso15924-codes.html
<REGION>
ISO 3166-1 country/region identifier. (2 alpha letters)
or UN M.49 code (3 digits)
http://www.iso.org/iso/home/standards/country_codes.htm
Remarks:
ON_Locale::InvariantCulture.BCP47LanguageName() = "";
ON_Locale::Oridnal.BCP47LanguageName() = "";
*/
const char* BCP47LanguageTag() const;
/*
Returns:
ISO 639 language code.
When avilable, two letter codes from ISO 639-1 are prefered.
Remarks:
The InvariantCulture.LanguageCode() is "".
See Also:
http://www.iso.org/iso/language_codes
*/
const char* LanguageCode() const;
/*
Returns:
ISO 3166-1 country/region identifier (2 alpha) or UN M.49 code (3 digits)
Remarks:
The returned string can be "" if the no region is specified.
The InvariantCulture.RegionCode() is "".
See Also:
http://www.iso.org/iso/home/standards/country_codes.htm
*/
const char* RegionCode() const;
/*
Returns:
A 4 letter ISO 15924 script code
Remarks:
The returned string can be "" if the no script is specified for the locale.
The InvariantCulture.ScriptCode() is "".
See Also:
http://www.unicode.org/iso15924/iso15924-codes.html
*/
const char* ScriptCode() const;
/*
Returns:
Microsoft Windows LCID value
ON_LocaleLCID::OrdinalLCID (=0)
The locale is a copy of ON_Locale::Ordinal.
ON_Locale::InvariantCultureLCID (=0x00000027U)
The locale is a copy of ON_Locale::InvariantCulture.
*/
ON__UINT32 WindowsLCID() const;
/*
Description:
Get the Microsoft Windows locale id.
Parameters:
buffer - [out]
A null terminated string containing the Microsoft Windows locale id is returned in this buffer.
The string has the form:
<language>[-<Script>][-<REGION>][_<sort_order>] (UTF-8 string encoding)
<language>
ISO 639 language code.
http://www.iso.org/iso/language_codes
<Script> is optional.
If present, it is a 4 alpha letter ISO 15924 script code
http://www.unicode.org/iso15924/iso15924-codes.html
<REGION>
ISO 3166-1 country/region identifier. (2 alpha letters)
or UN M.49 code (3 digits)
http://www.iso.org/iso/home/standards/country_codes.htm
<sort_order>
Up to six letters specifying a sort order.
Microsoft Windows codes are used.
buffer_capacity - [in]
number of elements in the buffer.
A capacity >= ON_Locale::BUFFER_MAXIMUM_CAPACITY will be large enough to
hold all possible output.
Returns:
If buffer_capacity is to small or buffer is nullptr, then nullptr is returned.
Otherwise the pointer to buffer is returned.
Remarks:
The Invariant locale name is the empty string "".
*/
const char* GetWindowsLocaleName(
char* buffer,
size_t buffer_capacity
) const;
const wchar_t* GetWindowsLocaleName(
wchar_t* buffer,
size_t buffer_capacity
) const;
/*
Returns:
Apple OS X / iOS locale name in the form
<language>[-<Script>][_<REGION>]
<language>
ISO 639 language code.
When avilable, two letter codes from ISO 639-1 are prefered.
http://www.iso.org/iso/language_codes
<Script> is optional.
If present, it is a 4 alpha letter ISO 15924 script code
http://www.unicode.org/iso15924/iso15924-codes.html
<REGION>
ISO 3166-1 country/region identifier. (2 alpha letters)
or UN M.49 code (3 digits)
http://www.iso.org/iso/home/standards/country_codes.htm
Remarks:
The Invariant locale name is the empty string "".
Apple language names have a hyphen (-) before the region.
Apple locale names have an underbar (_) before the region.
*/
const char* GetAppleLocaleName(
char* buffer,
size_t buffer_capacity
) const;
const wchar_t* GetAppleLocaleName(
wchar_t* buffer,
size_t buffer_capacity
) const;
/*
Returns:
Apple OS X / iOS locale name in the form
<language>[-<Script>][-<REGION>]
<language>
ISO 639 language code.
When avilable, two letter codes from ISO 639-1 are prefered.
http://www.iso.org/iso/language_codes
<Script> is optional.
If present, it is a 4 alpha letter ISO 15924 script code
http://www.unicode.org/iso15924/iso15924-codes.html
<REGION>
ISO 3166-1 country/region identifier. (2 alpha letters)
or UN M.49 code (3 digits)
http://www.iso.org/iso/home/standards/country_codes.htm
Remarks:
The Invariant locale name is the empty string "".
Apple language names have a hyphen (-) before the region.
Apple locale names have an underbar (_) before the region.
*/
const char* GetAppleLanguageName(
char* buffer,
size_t buffer_capacity
) const;
const wchar_t* GetAppleLanguageName(
wchar_t* buffer,
size_t buffer_capacity
) const;
/*
Returns:
A 6 letter locale sort order.
Remarks:
The returned string can be "" if the no sort order is specified for the locale.
The InvariantCulture.WindowsSortOrder() is "".
See Also:
https://msdn.microsoft.com/en-us/library/windows/desktop/dd374060(v=vs.85).aspx
*/
const char* WindowsSortOrder() const;
/*
Returns:
True if the C runtime formatted printing and scanning functions
are using the period character as the decimal point for
doubles and floats.
*/
static bool PeriodIsCRuntimeDecimalPoint();
/*
Description:
Use a call like setlocale(LC_NUMERIC,"C") to configure the
C runtime formatted printing and scanning functions to use the
period character as the decimal point for doubles and floats.
Returns:
True if successful.
*/
static bool SetPeriodAsCRuntimeDecimalPoint();
/*
Description:
Use a call like setlocale(LC_NUMERIC,"C") to configure the
C runtime formatted printing and scanning functions to use the
period character as the decimal point for doubles and floats.
Returns:
0: failed
1: success
Currently The decimal piont is a period in the C-runtime
formatted printing and scanning functions.
2: success
When called, the decimal piont was not a period, but
a call to ON_Locale::SetPeriodAsCRuntimeDecimalPoint()
restored the defaut behavior.
*/
static unsigned int EnforcePeriodAsCRuntimeDecimalPoint();
/*
Returns:
True if this is ON_Locale:InvariantCulture or a copy.
*/
bool IsInvariantCulture() const;
/*
Returns:
True if this is ON_Locale:Ordinal or a copy.
*/
bool IsOrdinal() const;
/*
Returns:
True if this is ON_Locale:Ordinal, ON_Locale:InvariantCulture or a copy
of one of them.
*/
bool IsOrdinalOrInvariantCulture() const;
/*
Description:
NumericLocalePtr() is an expert user function needed
to call C-runtime functions that format or parse numbers.
This locale must never be used to collate or map strings.
The primary use for this function is in opennurbs implementations
of ON_String and ON_wString number formatting and parsing functions.
Example:
// Call _sprintf_p_l
ON_CRT_locale_t numeric_locale = ON_Locale::CurrentCulture::NumericLocalePtr();
_sprintf_p_l(....,locale,...);
Returns:
A value that can be passed into C-runtime functions that take
a locale parameter.
*/
ON_CRT_locale_t NumericLocalePtr() const;
/*
Description:
StringCollateAndMapLocalePtr() is an expert user function needed
to call C-runtime functions that collate (compare)
and map (toupper/tolower) strings. This locale must never be used
for formatting or parsing numbers.
The primary use for this function is in opennurbs implementations
of ON_String and ON_wString collate and map functions.
Example:
// Call _wcsicoll_l
ON_CRT_locale_t coll_locale = ON_Locale::CurrentCulture::StringCollateAndMapLocalePtr();
_wcsicoll_l(....,coll_locale);
Returns:
A value that can be passed into C-runtime functions that take
a locale parameter.
*/
ON_CRT_locale_t StringCollateAndMapLocalePtr() const;
/*
Description:
Create a locale from a Windows locale id.
Parameters:
lcid - [in]
Windows LCID value or zero for the "ordinal" locale.
Returns:
ON_Locale identified by lcid.
If lcid is not valid or not supported, a copy of ON_Locale::Ordinal is returned.
*/
static ON_Locale FromWindowsLCID(
ON__UINT32 windows_lcid
);
/*
Description:
Create a locale from a BCP 47 language name.
Parameters:
language_name - [in]
The language name has the form
<language>[-<Script>][-<REGION>]
Case is not important.
Returns:
ON_Locale identified by language_name.
If locale_name is not valid or not supported, a copy of ON_Locale::Ordinal is returned.
*/
static ON_Locale FromBCP47LanguageName(
const char* language_name
);
static ON_Locale FromBCP47LanguageName(
const wchar_t* language_name
);
/*
Description:
Create a locale from a Windows locale name.
Parameters:
windows_name - [in]
The Windows name has the form
<language>[-<Script>][-<REGION>][_<sort_order>]
Case is not important.
Returns:
ON_Locale identified by locale_name.
If locale_name is not valid or not supported, a copy of ON_Locale::Ordinal is returned.
*/
static ON_Locale FromWindowsName(
const char* windows_name
);
static ON_Locale FromWindowsName(
const wchar_t* windows_name
);
/*
Description:
Create a locale from an Apple locale or language name
Parameters:
apple_name - [in]
The Apple name has the form <language>[-<Script>][-<REGION>].
An underbar (_) may be used in place of a hyphen (-).
Case is not important.
Returns:
ON_Locale identified by locale_name.
If locale_name is not valid or not supported, a copy of ON_Locale::Ordinal is returned.
*/
static ON_Locale FromAppleName(
const char* apple_name
);
static ON_Locale FromAppleName(
const wchar_t* apple_name
);
/*
Description:
Create a locale from BCP 47 lanugage code, script code and region code.
Parameters:
language_code - [in]
ISO 639 language code.
When avilable, two letter codes from ISO 639-1 are prefered.
http://www.iso.org/iso/language_codes
script - [in]
nullptr, empty string, or a 4 letter ISO 15924 script code
http://www.unicode.org/iso15924/iso15924-codes.html
<REGION>
nullptr, empty string, or an ISO 3166 country/region identifier.
http://www.iso.org/iso/home/standards/country_codes.htm
Returns:
ON_Locale identified by the locale name.
If the locale name is not valid or not supported, a copy of ON_Locale::Ordinal is returned.
*/
static ON_Locale FromSubtags(
const char* language_code,
const char* script_code,
const char* region_code
);
static ON_Locale FromSubtags(
const wchar_t* language_code,
const wchar_t* script_code,
const wchar_t* region_code
);
/*
Description:
Attempt to parse a string that is a language name or locale name
and extract language code, extlang code script code, region code
and Windows sort order.
The language name has the form <language>[<-extlang>][-<Script>][-<REGION>]
If the Microsoft [_<windows_sort_order>] appears after the language name,
it is parsed.
Apple "locale ids" of the form <language>_<REGION>" are parsed as well
(an underbar separator instead of a hyphen before <REGION>).
Parameters:
locale_name - [in]
name to parse. Case is ignored.
locale_name_element_count - [in]
number of elements to parse in locale_name[]
If locale_name_element_count < 0, then a null terminator ends parsing.
language_code - [out]
language_code_capacity - [in]
number of elements available in language_code[].
extlang_code - [out]
extlang_code_capacity - [in]
number of elements available in extlang_code[].
script_code - [out]
script_code_capacity - [in]
number of elements available in script_code[].
region_code - [out]
region_code_capacity - [in]
number of elements available in region_code[].
windows_sortorder - [out]
windows_sortorder_capacity - [in]
number of elements available in windows_sortorder[].
Remarks:
The standards for language identifiers (RFC 5646 and BCP 47) states that a hyphen
( Unicode U+002D ) is supposed to be the separator between subtags.
ftp://ftp.isi.edu/in-notes/bcp/bcp47.txt
*/
static bool ParseName(
const wchar_t* locale_name,
int locale_name_element_count,
wchar_t* language_code,
size_t language_code_capacity,
wchar_t* extlang_code,
size_t extlang_code_capacity,
wchar_t* script_code,
size_t script_code_capacity,
wchar_t* region_code,
size_t region_code_capacity,
wchar_t* windows_sortorder,
size_t windows_sortorder_capacity
);
static bool ParseName(
const char* locale_name,
int locale_name_element_count,
char* language_code,
size_t language_code_capacity,
char* extlang_code,
size_t extlang_code_capacity,
char* script_code,
size_t script_code_capacity,
char* region_code,
size_t region_code_capacity,
char* windows_sortorder,
size_t windows_sortorder_capacity
);
private:
ON_CRT_locale_t m_numeric_locale = 0; // pointer to a C runtime locale type
ON_CRT_locale_t m_string_coll_map_locale = 0; // pointer to a C runtime locale type
char m_bcp47_language_tag[85]; // <language>-<Script>-<REGION>
// RFC 4646 language identifier
char m_language_subtag[9]; // ISO 639 code (RFC 4646 reserves 8 alpha elements)
char m_script_subtag[5]; // ISO 15924 code
char m_region_subtag[5]; // ISO 3166 code (2 alpha) or UN M.49 code (3 digit)
char m_windows_sortorder[7]; // Windows sort order
char m_reserved2[21];
// Values needed to use Windows tools
ON__UINT32 m_windows_lcid = 0; // Microsoft Windows LCID values (0 = ordinal, 0x0027 = invariant culture)
ON__UINT32 m_reserved3 = 0;
private:
// Construct from lcid and matching name
static ON_Locale FromWindowsLCIDAndName(
ON__UINT32 windows_lcid,
const char* name
);
// Construct from perfect input
//ON_Locale(
// ON__UINT_PTR string_coll_map_locale_ptr,
// ON__UINT32 windows_lcid,
// const char* language_name,
// const char* language_code,
// const char* script_code,
// const char* region_code,
// const char* windows_sortorder
// );
};
#endif
+123
View File
@@ -0,0 +1,123 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2013 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_LOCK_INC_)
#define OPENNURBS_LOCK_INC_
/*
Description:
ON_Lock is a thread safe lock semephore. It is implemented using
platform specfic compare and set functions.
*/
class ON_CLASS ON_Lock
{
public:
#if defined(ON_COMPILER_CLANG)
ON_Lock() ON_NOEXCEPT;
#else
ON_Lock() = default;
#endif
~ON_Lock() = default;
ON_Lock(const ON_Lock&) = default;
ON_Lock& operator=(const ON_Lock&) = default;
// ON_Lock::InvalidLockValue (= -1) may never be used as a lock value.
enum : int
{
UnlockedValue = 0,
DefaultLockedValue = 1,
InvalidLockValue = -1
};
/*
Returns:
Current lock value
ON_Lock::UnlockedValue indicates the the resource protected by the lock is available.
*/
int IsLocked();
/*
Description:
Calls GetLock(ON_Lock::DefaultLockedValue);
Returns:
True if the lock state was unlocked
and the current lock value was changed from ON_Lock::UnlockedValue to ON_Lock::DefaultLockedValue.
False otherwise.
*/
bool GetDefaultLock();
/*
Description:
Calls ReturnLock(ON_Lock::DefaultLockedValue);
Returns:
True if the lock state was locked with a locak value = ON_Lock::DefaultLockedValue
and the current lock value was changed from ON_Lock::DefaultLockedValue to ON_Lock::UnlockedValue.
False otherwise.
*/
bool ReturnDefaultLock();
/*
Parameters:
lock_value - [in]
any value except ON_Lock::UnlockedValue or ON_Lock::InvalidLockValue.
Typically ON_Lock::DefaultLockedValue is used.
Returns:
True if the lock_value parameter was valid and the current
lock value was changed from ON_Lock::UnlockedValue to lock_value.
False otherwise.
*/
bool GetLock(int lock_value);
/*
Parameters:
lock_value - [in]
any value except ON_Lock::UnlockedValue or ON_Lock::InvalidLockValue.
Typically this is the value that was passed to GetLock().
Returns:
True if the lock_value parameter was valid and the current
lock value was changed from that value to zero.
False otherwise.
*/
bool ReturnLock(int lock_value);
/*
Description:
Unconditionally sets the lock value to ON_Lock::UnlockedValue.
Returns:
previous value of the lock.
ON_Lock::UnlockedValue indicates the lock was available
otherwise the lock passed to GetLock() is returned
*/
int BreakLock();
private:
// It is important that sizeof(ON_Lock) = sizeof(int)
// and that m_lock_value be an int.
#pragma ON_PRAGMA_WARNING_PUSH
#pragma ON_PRAGMA_WARNING_DISABLE_MSC( 4251 )
// C4251: 'ON_Lock::m_lock_value': struct 'std::atomic<int>'
// needs to have dll-interface to be used by clients of class 'ON_Lock'
// m_lock_value is private and all code that manages m_lock_value is explicitly implemented in the DLL.
private:
#if defined(ON_COMPILER_CLANG)
std::atomic<int> m_lock_value;
#else
std::atomic<int> m_lock_value = {ON_Lock::UnlockedValue};
#endif
#pragma ON_PRAGMA_WARNING_POP
};
#endif
+461
View File
@@ -0,0 +1,461 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_MAP_INC_)
#define OPENNURBS_MAP_INC_
/*
Description:
ON_SerialNumberMap provides a way to map set of unique
serial number - uuid pairs to application defined values
so that adding, finding and removing serial numbers is
fast and efficient. The class is designed to handle
several millions of unique serial numbers. There are no
restrictions on what order numbers are added and removed.
The minimum memory footprint is less than 150KB and doesn't
increase until you have more than 8000 serial numbers.
It is possible to have an active serial number and an
inactive id.
*/
class ON_CLASS ON_SerialNumberMap
{
public:
ON_SerialNumberMap();
~ON_SerialNumberMap();
struct MAP_VALUE
{
ON__UINT32 m_u_type;
ON__UINT32 m_u32;
union
{
ON__UINT64 u64;
ON__INT64 i64;
void* ptr;
ON__UINT32 ui[2];
ON__INT32 i[2];
} m_u;
};
struct SN_ELEMENT
{
////////////////////////////////////////////////////////////
//
// ID
//
ON_UUID m_id;
////////////////////////////////////////////////////////////
//
// Serial number:
//
ON__UINT64 m_sn;
////////////////////////////////////////////////////////////
//
// Status flags:
//
// If m_id_active is 1, then m_sn_active must be 1.
// If m_sn_active = 1, then m_id_active can be 0 or 1.
ON__UINT8 m_sn_active; // 1 = serial number is active
ON__UINT8 m_id_active; // 1 = id is active
ON__UINT8 m_reserved1;
ON__UINT8 m_reserved2;
ON__UINT32 m_id_crc32; // id hash = IdCRC(id)
struct SN_ELEMENT* m_next; // id hash table linked list
////////////////////////////////////////////////////////////
//
// User information:
//
// ON_SerialNumberMap does not use the m_value field.
// When a new element is added, m_value is memset to
// zero. Other than that, m_value is not changed by
// this class. The location of m_value in memory,
// (&m_value) may change at any time.
struct MAP_VALUE m_value;
void Dump(ON_TextLog&) const;
};
/*
Returns:
Number of active serial numbers in the list.
*/
ON__UINT64 ActiveSerialNumberCount() const;
/*
Returns:
Number of active ids in the list. This number
is less than or equal to ActiveSerialNumberCount().
*/
ON__UINT64 ActiveIdCount() const;
/*
Returns:
The active element with the smallest serial number,
or null if the list is empty.
Restrictions:
The returned pointer may become invalid after any
subsequent calls to any function in this class.
If you need to save information in the returned
SN_ELEMENT for future use, you must copy the
information into storage you are managing.
You may change the value of the SN_ELEMENT's m_value
field. You must NEVER change any other SN_ELEMENT
fields or you will break searching and possibly cause
crashes.
*/
struct SN_ELEMENT* FirstElement() const;
/*
Returns:
The active element with the biggest serial number,
or null if the list is empty.
Restrictions:
The returned pointer may become invalid after any
subsequent calls to any function in this class.
If you need to save information in the returned
SN_ELEMENT for future use, you must copy the
information into storage you are managing.
You may change the value of the SN_ELEMENT's m_value
field. You must NEVER change any other SN_ELEMENT
fields or you will break searching and possibly cause
crashes.
*/
struct SN_ELEMENT* LastElement() const;
/*
Parameters:
sn - [in] serial number to search for.
Returns:
If the serial number is active, a pointer to
its element is returned.
Restrictions:
The returned pointer may become invalid after any
subsequent calls to any function in this class.
If you need to save information in the returned
SN_ELEMENT for future use, you must copy the
information into storage you are managing.
You may change the value of the SN_ELEMENT's m_value
field. You must NEVER change any other SN_ELEMENT
fields or you will break searching and possibly cause
crashes.
*/
struct SN_ELEMENT* FindSerialNumber(ON__UINT64 sn) const;
/*
Parameters:
id - [in] id number to search for.
Returns:
If the id is active, a pointer to
its element is returned.
Restrictions:
The returned pointer may become invalid after any
subsequent calls to any function in this class.
If you need to save information in the returned
SN_ELEMENT for future use, you must copy the
information into storage you are managing.
You may change the value of the SN_ELEMENT's m_value
field. You must NEVER change any other SN_ELEMENT
fields or you will break searching and possibly cause
crashes.
*/
struct SN_ELEMENT* FindId(ON_UUID) const;
/*
Description:
Add a serial number to the map.
Parameters:
sn - [in] serial number to add.
Returns:
If the serial number is valid (>0), a pointer to its
element is returned. When a new element is added,
every byte of the m_value field is set to 0.
If the serial number was already active, its element is
also returned. If you need to distinguish between new
and previously existing elements, then set an
m_value field to something besides 0 after you add
a new serial number. The id associated with this
serial number will be zero and cannot be found using
FindId().
Restrictions:
The returned pointer may become invalid after any
subsequent calls to any function in this class.
If you need to save information in the returned
SN_ELEMENT for future use, you must copy the
information into storage you are managing.
You may change the value of the SN_ELEMENT's m_value
field. You must NEVER change any other SN_ELEMENT
fields or you will break searching and possibly cause
crashes.
*/
struct SN_ELEMENT* AddSerialNumber(ON__UINT64 sn);
/*
Parameters:
sn - [in] serial number to add.
id - [in] suggested id to add. If id is zero or
already in use, another id will be assigned
to the element.
Returns:
If the serial number is valid (>0), a pointer to its
element is returned. When a new element is added,
every byte of the m_value field is set to 0.
If the serial number was already active, its element is
also returned. If you need to distinguish between new
and previously existing elements, then set an
m_value field to something besides 0 after you add
a new serial number.
If the id parameter is nil, then a new uuid is created
and added. If the id parameter is not nil but is active
on another element, a new uuid is created and added.
You can inspect the value of m_id on the returned element
to determine the id AddSerialNumberAndId() assigned to
the element.
Restrictions:
The returned pointer may become invalid after any
subsequent calls to any function in this class.
If you need to save information in the returned
SN_ELEMENT for future use, you must copy the
information into storage you are managing.
You may change the value of the SN_ELEMENT's m_value
field. You must NEVER change any other SN_ELEMENT
fields or you will break searching and possibly cause
crashes.
*/
struct SN_ELEMENT* AddSerialNumberAndId(ON__UINT64 sn, ON_UUID id);
/*
Parameters:
sn - [in] serial number of the element to remove.
Returns:
If the serial number was active, it is removed
and a pointer to its element is returned. If
the element's id was active, the id is also removed.
Restrictions:
The returned pointer may become invalid after any
subsequent calls to any function in this class.
If you need to save information in the returned
SN_ELEMENT for future use, you must copy the
information into storage you are managing.
You may change the value of the SN_ELEMENT's m_value
field. You must NEVER change any other SN_ELEMENT
fields or you will break searching and possibly cause
crashes.
*/
struct SN_ELEMENT* RemoveSerialNumberAndId(ON__UINT64 sn);
/*
Parameters:
sn - [in] If > 0, this is the serial number
of the element with the id. If 0, the
field is ignored.
id - [in] id to search for.
Returns:
If the id was active, it is removed and a pointer
to its element is returned. The element's serial
remains active. To remove both the id and serial number,
use RemoveSerialNumberAndId().
Restrictions:
The returned pointer may become invalid after any
subsequent calls to any function in this class.
If you need to save information in the returned
SN_ELEMENT for future use, you must copy the
information into storage you are managing.
You may change the value of the SN_ELEMENT's m_value
field. You must NEVER change any other SN_ELEMENT
fields or you will break searching and possibly cause
crashes.
*/
struct SN_ELEMENT* RemoveId(ON__UINT64 sn, ON_UUID id);
/*
Description:
Finds all the elements whose serial numbers are
in the range sn0 <= sn <= sn1 and appends them
to the elements[] array. If max_count > 0, it
specifies the maximum number of elements to append.
Parameters:
sn0 - [in]
Minimum serial number.
sn1 - [in]
Maximum serial number
max_count - [in]
If max_count > 0, this parameter specifies the
maximum number of elements to append.
elements - [out]
Elements are appended to this array
Returns:
Number of elements appended to elements[] array.
Remarks:
When many elements are returned, GetElements() can be
substantially faster than repeated calls to FindElement().
*/
ON__UINT64 GetElements(
ON__UINT64 sn0,
ON__UINT64 sn1,
ON__UINT64 max_count,
ON_SimpleArray<SN_ELEMENT>& elements
) const;
/*
Description:
Empties the list.
*/
void EmptyList();
/*
Description:
Returns true if the map is valid. Returns false if the
map is not valid. If an error is found and textlog
is not null, then a description of the problem is sent
to textlog.
Returns:
true if the list if valid.
*/
bool IsValid(
bool bBuildHashTable,
ON_TextLog* textlog
) const;
void Dump(ON_TextLog& text_log) const;
private:
// prohibit copy construction and operator=
// no implementation
ON_SerialNumberMap(const ON_SerialNumberMap&) = delete;
ON_SerialNumberMap& operator=(const ON_SerialNumberMap&) = delete;
private:
ON__UINT64 m_maxsn = 0; // largest sn stored anywhere
// Serial Number list counts
ON__UINT64 m_sn_count = 0; // total number of elements
ON__UINT64 m_sn_purged = 0; // total number of purged elements
// The blocks in m_sn_list[] are always sorted, disjoint,
// and in increasing order. m_sn_list is used when
// m_sn_block0.m_sn[] is not large enough.
// The sn list is partitioned into blocks to avoid
// requiring large amounts of contiguous memory for
// situations with millions of serial numbers.
ON__UINT64 m_snblk_list_capacity = 0; // capacity of m_blk_list[]
ON__UINT64 m_snblk_list_count = 0; // used elements in m_snblk_list[]
class ON_SN_BLOCK** m_snblk_list = nullptr;
// If FindElementHelper() returns a non-null pointer
// to an element, then m_e_blk points to the ON_SN_BLOCK
// that contains the returned element. In all other
// situations the value in m_e_blk is undefined and
// m_e_blk must not be dereferenced.
class ON_SN_BLOCK* m_e_blk = nullptr;
private:
class ON_SN_BLOCK& m_sn_block0;
private:
struct SN_ELEMENT* FindElementHelper(ON__UINT64 sn);
void UpdateMaxSNHelper();
void GarbageCollectHelper();
ON__UINT64 GarbageCollectMoveHelper(ON_SN_BLOCK* dst,ON_SN_BLOCK* src);
ON__UINT8 m_reserved1 = 0;
ON__UINT8 m_reserved2 = 0;
ON__UINT8 m_reserved3 = 0;
// When m_bHashTableIsValid == 1, the id hash table is valid.
// Otherwise it is not built or out of date.
// When m_bHashTableIsValid and nullptr != m_hash_table,
// then m_hash1_count > 0 and m_hash_table[i][j] is a
// linked list of elements whose id satisfies
// i = e->m_id_crc32 % m_hash_block_count
// j = (e->m_id_crc32/ID_HASH_BLOCK_CAPACITY) % ID_HASH_BLOCK_CAPACITY
mutable ON__UINT8 m_bHashTableIsValid = 0;
mutable ON__UINT32 m_hash_block_count = 0; // number of blocks in m_hash_tableX[]
mutable ON__UINT64 m_hash_capacity = 0; // == m_hash_block_count*ID_HASH_BLOCK_CAPACITY
// ideally, m_active_id_count/m_hash_capacity is close to 4
mutable struct SN_ELEMENT*** m_hash_table_blocks = nullptr;
// ID hash table counts (all ids in the hash table are active)
ON__UINT64 m_active_id_count = 0; // number of active ids in the hash table
ON_UUID m_inactive_id = ON_nil_uuid; // frequently an id is removed and
// then added back. m_inactive_id
// records the most recently removed
// id so we don't have to waste time
// searching the hash table for
// an id that is not there.
void Internal_HashTableInvalidate(); // marks table as dirty
bool Internal_HashTableRemoveSerialNumberBlock(
const class ON_SN_BLOCK* blk
);
/*
Returns:
Number of active ids added to hash table.
*/
ON__UINT64 Internal_HashTableAddSerialNumberBlock(
class ON_SN_BLOCK* blk
) const;
void Internal_HashTableBuild() const; // prepares table for use
struct SN_ELEMENT** Internal_HashTableBlock(
ON__UINT32 id_crc32
) const;
ON__UINT32 Internal_HashTableBlockIndex(
ON__UINT32 id_crc32
) const;
static ON__UINT32 Internal_HashTableBlockRowIndex(
ON__UINT32 id_crc32
);
struct SN_ELEMENT* Internal_HashTableFindId(
ON_UUID id,
ON__UINT32 id_crc32,
bool bBuildTableIfNeeded
) const;
struct SN_ELEMENT* Internal_HashTableRemoveElement(
struct SN_ELEMENT* e,
bool bRemoveFromHashBlock
);
void Internal_HashTableGrow() const;
void Internal_HashTableInitialize() const;
};
#endif
+224
View File
@@ -0,0 +1,224 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_MAPPING_CHANNEL_INC_)
#define OPENNURBS_MAPPING_CHANNEL_INC_
///////////////////////////////////////////////////////////////////////////////
//
// Class ON_MappingChannel
//
// Description:
// ON_3dmObjectAttributes uses ON_MappingChannel to record
// which texture mapping function to use when applying a texture
// with a matching mapping channel id.
// When an object is rendered, if the material has textures and
// ON_Texture::m_mapping_channel_id = ON_MappingChannel::m_mapping_channel_id,
// then the mapping with id m_mapping_id is used to map the texture.
// Otherwise, the mesh m_T[] texture coordinates are used to
// apply the texture.
//
class ON_CLASS ON_MappingChannel
{
public:
ON_MappingChannel();
void Default();
int Compare( const ON_MappingChannel& other ) const;
bool Write( ON_BinaryArchive& archive ) const;
bool Read( ON_BinaryArchive& archive );
ON_UUID m_mapping_id; // Identifies an ON_TextureMapping
// RUNTIME textrure mapping table index.
// If -1, it needs to be set. This value is not saved int files.
int m_mapping_index;
// ON_Texture's with a matching m_mapping_channel_id value
// use the mapping identified by m_mapping_id. This id
// must be > 0 and <= 2147483647 (0x7FFFFFFF)
int m_mapping_channel_id;
// The default value of m_object_xform is the identity.
// When an object that uses this mapping is transformed
// by "T", m_object_xform is updated using the formula
// m_object_xform = T*m_object_xform. If texture coordinates
// are lost and need to be recalculated and m_object_xform
// is not the identity, then m_object_xform should be passed
// to ON_TextureMapping::Evaluate() as the mesh_xform parameter.
// When validating mapping coordinates, m_object_xform itself
// be passed to HasMatchingTextureCoordinates() as the
// object_transform parameter.
ON_Xform m_object_xform;
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_MappingChannel>;
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Class ON_MaterialRef
//
// Description:
// ON_3dmObjectAttributes uses ON_MaterialRef to record which
// rendering material and mappings a rendering plug-in wants to
// use. This allows different rendering plug-ins to have different
// materials on the same object. The values of
// ON_3dmObjectAttributes.m_material_index and
// ON_3dmObjectAttributes.m_matrial_source reflect the settings
// of the renderer that is currently active.
//
class ON_CLASS ON_MappingRef
{
public:
ON_MappingRef();
void Default();
int Compare( const ON_MappingRef& other ) const;
bool Write( ON_BinaryArchive& archive ) const;
bool Read( ON_BinaryArchive& archive );
bool IsValid( ON_TextLog* text_log ) const;
bool Transform( const ON_Xform& xform );
ON_UUID m_plugin_id; // Identifies a rendering plugin
/*
Parameters:
mapping_channel_id - [in]
mapping_id - [in]
ON_TextureMapping id
Returns:
A pointer to the plug-in's mapping channel, if there
is one. Otherwise nullptr is returned.
*/
const ON_MappingChannel* MappingChannel(
int mapping_channel_id
) const;
const ON_MappingChannel* MappingChannel(
const ON_UUID& mapping_id
) const;
/*
Parameters:
mapping_channel_id - [in]
mapping_id - [in]
ON_TextureMapping id
Returns:
True if the mapping channel was added or a pefect
match already existed. False if a mapping channel
with a different mapping_id already exists for this
plug-in and channel.
*/
bool AddMappingChannel(
int mapping_channel_id,
const ON_UUID& mapping_id
);
/*
Parameters:
mapping_channel_id - [in]
mapping_id - [in]
ON_TextureMapping id
Returns:
True if a matching mapping channel was deleted.
*/
bool DeleteMappingChannel(
int mapping_channel_id
);
bool DeleteMappingChannel(
const ON_UUID& mapping_id
);
/*
Parameters:
old_mapping_channel_id - [in]
new_mapping_channel_id - [in]
Returns:
True if a matching mapping channel was found and changed.
*/
bool ChangeMappingChannel(
int old_mapping_channel_id,
int new_mapping_channel_id
);
// Use AddMappingChannel() if you want to add an
// element to this array.
//
// Every mapping channel in this array must have
// a distinct value of ON_MappingChannel.m_mapping_channel_id
ON_SimpleArray<ON_MappingChannel> m_mapping_channels;
};
class ON_CLASS ON_MaterialRef
{
public:
// If m_material_id = ON_MaterialRef::material_from_layer,
// then the object's layer determine the material.
// See ON::material_from_layer.
//static const ON_UUID material_from_layer; // TOD0 - remove this
// If m_material_id = ON_MaterialRef::material_from_layer,
// then the object's parent determine the material.
// See ON::material_from_parent.
//static const ON_UUID material_from_parent; // TODO - remove this
ON_MaterialRef();
void Default();
int Compare( const ON_MaterialRef& other ) const;
bool Write( ON_BinaryArchive& archive ) const;
bool Read( ON_BinaryArchive& archive );
ON_UUID m_plugin_id; // Identifies a rendering plugin
ON_UUID m_material_id; // Identifies an ON_Material
// If nil, then m_material_id is used for front and back faces
ON_UUID m_material_backface_id; // Identifies an ON_Material
ON::object_material_source MaterialSource() const;
void SetMaterialSource(
ON::object_material_source
);
unsigned char m_material_source; // ON::object_material_source values
unsigned char m_reserved1;
unsigned char m_reserved2;
unsigned char m_reserved3;
// RUNTIME material table index for m_material_id.
// This value is not saved in files. If -1, then it
// needs to be set.
int m_material_index;
// RUNTIME material table index for m_material_id.
// This value is not saved in files. If -1, then it
// needs to be set.
int m_material_backface_index;
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_ClassArray<ON_MaterialRef>;
ON_DLL_TEMPLATE template class ON_CLASS ON_ClassArray<ON_MappingRef>;
#endif
#endif
+796
View File
@@ -0,0 +1,796 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_MATERIAL_INC_)
#define OPENNURBS_MATERIAL_INC_
class ON_PhysicallyBasedMaterial;
///////////////////////////////////////////////////////////////////////////////
//
// Class ON_Material
//
class ON_CLASS ON_Material : public ON_ModelComponent
{
ON_OBJECT_DECLARE(ON_Material);
public:
static const double MaxShine; // maximum value of shine exponent = 255.0
static const ON_Material Unset; // nil id
static const ON_Material Default; // index = -1, persistent id
// Default material for locked objects
static const ON_Material DefaultLockedObject; // index = -2, persistent id
/*
Parameters:
model_component_reference - [in]
none_return_value - [in]
value to return if ON_Material::Cast(model_component_ref.ModelComponent())
is nullptr
Returns:
If ON_Material::Cast(model_component_ref.ModelComponent()) is not nullptr,
that pointer is returned. Otherwise, none_return_value is returned.
*/
static const ON_Material* FromModelComponentRef(
const class ON_ModelComponentReference& model_component_reference,
const ON_Material* none_return_value
);
// compare everything except Index() value.
static int Compare(
const ON_Material& a,
const ON_Material& b
);
// compare Id(), Name(), m_rdk_material_instance_id
static int CompareNameAndIds(
const ON_Material& a,
const ON_Material& b
);
// Compare all settings (color, reflection, texture, plug-in id)
// that affect the appearance.
// Ignore Index(), Id(), Name(), m_rdk_material_instance_id.
static int CompareAppearance(
const ON_Material& a,
const ON_Material& b
);
static int CompareColorAttributes(
const ON_Material& a,
const ON_Material& b
);
static int CompareReflectionAttributes(
const ON_Material& a,
const ON_Material& b
);
static int CompareTextureAttributes(
const ON_Material& a,
const ON_Material& b
);
static int CompareTextureAttributesAppearance(
const ON_Material& a,
const ON_Material& b
);
/*
Parameters:
fresnel_index_of_refraction - [in]
ON_Material::Material::Default.m_fresnel_index_of_refraction
is a good default
N - [in]
3d surface normal
R - [in]
3d reflection direction
Returns:
1.0:
The input values were not valid or the calculation failed due to
a divide by zero or some other numerical arithmetic failure.
fresnel reflection coefficient
1/2 * ((g-c)/(g+c))^2 * (1 + ( (c*(g+c) -1)/(c*(g+c) + 1) )^2)
where
c = N o (N-R); // c = 3d vector dot product of N and (N-R)
and
g = sqrt(fresnel_index_of_refraction*fresnel_index_of_refraction + c*c - 1.0).
*/
static double FresnelReflectionCoefficient(
double fresnel_index_of_refraction,
const double N[3],
const double R[3]
);
public:
ON_Material() ON_NOEXCEPT;
ON_Material(const ON_Material& src);
~ON_Material() = default;
ON_Material& operator=(const ON_Material& src) = default;
private:
void Internal_CopyFrom(
const ON_Material& src
);
public:
/////////////////////////////////////////////////////////////////
// ON_Object overrides
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
void Dump(
ON_TextLog& text_log
) const override;
bool Write(
ON_BinaryArchive& archive
) const override;
bool Read(
ON_BinaryArchive& archive
) override;
ON::object_type ObjectType() const override;
/////////////////////////////////////////////////////////////////
// Interface
ON_Color Ambient() const;
ON_Color Diffuse() const;
ON_Color Emission() const;
ON_Color Specular() const;
void SetAmbient( ON_Color );
void SetDiffuse( ON_Color );
void SetEmission( ON_Color );
void SetSpecular( ON_Color );
// Shine values are in range 0.0 to ON_Material::MaxShine
double Shine() const;
void SetShine( double ); // 0 to ON_Material::MaxShine
// Transparency values are in range 0.0 = opaque to 1.0 = transparent
double Transparency() const;
void SetTransparency( double ); // 0.0 = opaque, 1.0 = transparent
// Transparency values are in range 0.0 = opaque to 1.0 = transparent
double Reflectivity() const;
void SetReflectivity( double ); // 0.0 = opaque, 1.0 = transparent
// ID of the last plug-in to modify this material
ON_UUID MaterialPlugInId() const;
void SetMaterialPlugInId(
ON_UUID plugin_id
);
public:
/*
Description:
Get the RDK material id.
Returns:
The RDK material id for this material.
Remarks:
The RDK material id identifies a material definition managed by
the RDK (rendering development kit). Multiple materials in
a Rhino or opennurbs model can reference the same RDK material.
*/
ON_UUID RdkMaterialInstanceId() const;
/*
Description:
Set this material's RDK material id.
Parameters:
rdk_material_id - [in]
RDK material id value.
Remarks:
The RDK material id identifies a material definition managed by
the RDK (rendering development kit). Multiple materials in
a Rhino or opennurbs model can reference the same RDK material.
*/
void SetRdkMaterialInstanceId(
ON_UUID rdk_material_instance_id
);
bool RdkMaterialInstanceIdIsNotNil() const;
bool RdkMaterialInstanceIdIsNil() const;
/*
Returns:
True if the material can be shared.
Remarks:
If true, when an object using this material is copied,
the copy references the same material.
*/
bool Shareable() const;
void SetShareable(
bool bShareable
);
/*
Returns:
True if lighting is disabled.
Remarks:
True means render this object without
applying any modulation based on lights.
Basically, the diffuse, ambient, specular and
emissive channels get combined additively, clamped,
and then get treated as an emissive channel.
Another way to think about it is when
m_bDisableLighting is true, render the same way
OpenGL does when ::glDisable( GL_LIGHTING ) is called.
*/
bool DisableLighting() const;
void SetDisableLighting(
bool bDisableLighting
);
//If m_bUseDiffuseTextureAlphaForObjectTransparencyTexture is true, the alpha channel
//of the texture in m_textures with m_type=bitmap_texture is used in addition to any
//textures with m_type=transparency_texture.
bool UseDiffuseTextureAlphaForObjectTransparencyTexture() const;
void SetUseDiffuseTextureAlphaForObjectTransparencyTexture(
bool bUseDiffuseTextureAlphaForObjectTransparencyTexture
);
//////////////////////////////////////////////////////////////
//
// Reflection and Refraction settings
//
// The bool m_bFresnelReflections enables fresnel scaling
// of reflection contributions to the diffuse color.
// True:
// The fresnel term is used to scale the reflection contribution
// before addition to the diffuse component.
// False:
// The reflection contribution is simply added to the diffuse component.
bool FresnelReflections() const;
void SetFresnelReflections(
bool bFresnelReflections
);
//Returns a color that can be used as a simple preview of the material in GUIs. This is
//the function that the layer manager uses to color the little material swatch, for example.
ON_Color PreviewColor() const;
//Call this function to determine if the material should be treated as Physically Based (ie - a PBR material)
//If this function returns true, the call to PhysicallyBased will return a non-null pointer.
//If the function returns false, use the legacy interface (Diffuse etc). Conversion of a non-PBR material to PBR
//is possible by calling ConvertToPhysicallyBased.
bool IsPhysicallyBased(void) const;
//Physically based material interface. Use this interface to set and get PBR parameters
//and to check if this material supports PBR.
//Note - it is very important that the lifetime of the returned pointer is the same as the ON_Material
//it was called on. Once the material is deleted, this pointer is no longer valid.
const std::shared_ptr<ON_PhysicallyBasedMaterial> PhysicallyBased(void) const;
std::shared_ptr <ON_PhysicallyBasedMaterial> PhysicallyBased(void);
//Convert a legacy material to a PBR material that is the best approximation of the original.
//After calling this function, the material is guaranteed to return true to material.IsPhysicallyBased()
void ToPhysicallyBased(void);
//Internal use only
static ON_UUID PhysicallyBasedUserdataId(void);
private:
// The value of m_rdk_material_id idetifies an RDK (rendering development kit)
// material. Multiple materials in a Rhino model can refer to the same
// RDK material id. In V5 this value is stored in user data. In V6 it is
// saved in the m_rdk_material_id field.
ON_UUID m_rdk_material_instance_id = ON_nil_uuid;
public:
ON_Color m_ambient = ON_Color::Black;
ON_Color m_diffuse = ON_Color::Gray126;
ON_Color m_emission = ON_Color::Black;
ON_Color m_specular = ON_Color::White;
ON_Color m_reflection = ON_Color::White;
ON_Color m_transparent = ON_Color::White;
private:
bool m_bShareable = false;
private:
bool m_bDisableLighting = false;
private:
bool m_bUseDiffuseTextureAlphaForObjectTransparencyTexture = false;
private:
bool m_bFresnelReflections = false;
private:
unsigned int m_reserved1 = 0;
public:
double m_reflectivity = 0.0; // 0.0 = none, 1.0 = 100%
double m_shine = 0.0; // 0.0 = none to GetMaxShine()=maximum
double m_transparency = 0.0; // 0.0 = opaque to 1.0 = transparent (1.0-alpha)
/*
m_reflection_glossiness:
Default is 0.0.
Values from 0.0 to 1.0 make sense.
- 0.0 reflections are perfectly specular.
- t > 0.0 permits reflection ray direction to vary
from the specular direction by up to t*pi/2.
*/
double m_reflection_glossiness = 0.0;
/*
m_refraction_glossiness:
Default is 0.0.
Values from 0.0 to 1.0 make sense.
- 0.0 refractions are perfectly specular.
- t > 0.0 permits refraction ray direction to vary
from the specular direction by up to t*pi/2.
*/
double m_refraction_glossiness = 0.0;
/*
m_index_of_refraction:
Default is 1.0.
Physically, the index of refraction is >= 1.0 and is
the value (speed of light in vacum)/(speed of light in material).
Some rendering algorithms set m_index_of_refraction to zero or
values < 1.0 to generate desirable effects.
*/
double m_index_of_refraction = 1.0;
/*
m_fresnel_index_of_refraction:
Default is 1.56.
This is the value ON:Material::FresnelReflectionCoefficient() passes
as the first parameter to ON_FresnelReflectionCoefficient().
- Glass material types can be simulated with
m_index_of_refraction ~ 1.56
m_fresnel_index_of_refraction ~ 1.56
- Thin glass can be simulated with
m_fresnel_index_of_refraction = 1.56
m_index_of_refraction = 0.0
- Porcelain type materials can be simulated with
m_fresnel_index_of_refraction = 1.56
m_index_of_refraction = 1.0
m_transparency = 0.0
*/
double m_fresnel_index_of_refraction = 1.56;
/*
Parameters:
N - [in]
3d surface normal
R - [in]
3d reflection direction
Returns:
If m_bFresnelReflections is false, then 1.0 is returned.
If m_bFresnelReflections is true, then the value of the fresnel
reflection coefficient is returned. In typical rendering applications,
the reflection term is multiplied by the fresnel reflection coefficient
before it is added to the diffuse color.
If any input is not valid or the calculation fails, then 1.0 is returned.
Remarks:
When m_bFresnelReflections is true, the calculation is performed by
calling ON_FresnelReflectionCoefficient() with m_fresnel_index_of_refraction
as the fresnel index of refraction.
*/
double FresnelReflectionCoefficient(
ON_3dVector N,
ON_3dVector R
) const;
/*
Description:
Searches for a texure with matching texture_id.
If more than one texture matches, the first match
is returned.
Parameters:
texture_id - [in]
Returns:
>=0 m_textures[] index of matching texture
-1 if no match is found.
*/
int FindTexture(
ON_UUID texture_id
) const;
/*
Description:
Searches for a texure with matching filename and type.
If more than one texture matches, the first match
is returned.
Parameters:
filename - [in] If nullptr, then any filename matches.
type - [in] If ON_Texture::no_texture_type, then
any texture type matches.
i0 - [in] If i0 is < 0, the search begins at
m_textures[0], if i0 >= m_textures.Count(),
-1 is returnd, otherwise, the search begins
at m_textures[i0+1].
Example:
Iterate through all the the bitmap textures on
a material.
ON_Material& mat = ...;
int ti = -1;
int bitmap_texture_count = 0;
for(;;)
{
ti = mat.FindTexture(
nullptr,
ON_Texture::TYPE::bitmap_texture,
ti );
if ( ti < 0 )
{
// no more bitmap textures
break;
}
// we have a bitmap texture
bitmap_texture_count++;
const ON_Texture& bitmap_texture = mat.m_textures[ti];
...
}
Returns:
>=0 m_textures[] index of matching texture
-1 if no match is found.
*/
int FindTexture(
const wchar_t* filename,
ON_Texture::TYPE type,
int i0 = -1
) const;
/*
Description:
If there is already a texture with the same file name and
type, then that texture is modified, otherwise a new texture
is added. If tx has user data, the user data is copied
to the m_textures[] element.
Parameters:
tx - [in]
Returns:
Index of the added texture in the m_textures[] array.
Remarks:
This is intended to be a quick and simple way to add
textures to the material. If you need to do something
different, then just work on the m_textures[] array.
*/
int AddTexture(
const ON_Texture& tx
);
/*
Description:
If there is a texture with a matching type, that texture's
filename is modified, otherwise a new texture is added.
Parameters:
filename - [in] new filename
type - [in]
Returns:
Index of the added texture in the m_textures[] array.
Remarks:
This is intended to be a quick and simple way to add
textures to the material. If you need to do something
different, then just work on the m_textures[] array.
*/
int AddTexture(
const wchar_t* filename,
ON_Texture::TYPE type
);
/*
Description:
Deletes all texures with matching filenames and types.
Parameters:
filename - [in] If nullptr, then any filename matches.
type - [in] If ON_Texture::no_texture_type, then
any texture type matches.
Returns:
Number of textures deleted.
*/
int DeleteTexture(
const wchar_t* filename,
ON_Texture::TYPE type
);
ON_ObjectArray<ON_Texture> m_textures;
/*
Description:
The m_material_channel[] array is used to provide per face rendering material support for ON_SubD and ON_Brep objects.
ON_Mesh objects to not support per face render materials.
The application specifies a base ON_Material for rendering the subd or brep and a way to find materials from ON_UUID values.
ON_Material.Id() retuns the id for any given material.
ON_BrepFace::MaterialChannelIndex() and ON_SubDFace::MaterialChannelIndex()
specify a material channel index. If this value is 0, then the base
material is used to render the face. Otherwise the material with
id = base.MaterialChannelIdFromIndex( face.MaterialChannelIndex() )
is used to render the face.
*/
ON_SimpleArray<ON_UuidIndex> m_material_channel;
enum : int
{
///<summary>
/// Material channel index values stored in the ON_UuidIndex.m_i field of elements in the m_material_channel[] array
/// must be between 0 and ON_Material::MaximumMaterialChannelIndex, inclusive.
///</summary>
MaximumMaterialChannelIndex = 65535
};
/*
Parameters:
material_channel_index - [in]
Returns:
If material_channel_index > 0, the m_id ON_UUID value of the first element in the
m_material_channel[] array with material_channel_index = ON_Uuid_index.m_i is returned.
This id identifies an ON_Material.
Otherwise ON_nil_uuid is returned.
*/
const ON_UUID MaterialChannelIdFromIndex(
int material_channel_index
) const;
/*
Parameters:
material_channel_id - [in]
Returns:
If material_channel_id is not nil, the m_i index value of the first element in the
m_material_channel[] array with material_channel_id = ON_Uuid_index.m_id is returned.
Otherwise 0 is returned.
*/
int MaterialChannelIndexFromId(
ON_UUID material_channel_id
) const;
/*
Parameters:
material_channel_id - [in]
bAddIdIfNotPresent - [in]
Returns:
If material_channel_id is not nil, the m_i index value of the first element in the
m_material_channel[] array with material_channel_id = ON_Uuid_index.m_id is returned.
If material_channel_id is not nil an no element of the m_material_channel[] array
has a matching id, a new element is added with a unique channel index > 0 and that
index is returned.
Otherwise 0 is returned.
*/
int MaterialChannelIndexFromId(
ON_UUID material_channel_id,
bool bAddIdIfNotPresent
);
private:
ON_UUID m_plugin_id = ON_nil_uuid;
private:
bool Internal_ReadV3( ON_BinaryArchive& archive, int minor_version );
bool Internal_WriteV3( ON_BinaryArchive& archive ) const;
bool Internal_ReadV5( ON_BinaryArchive& archive );
bool Internal_WriteV5( ON_BinaryArchive& archive ) const;
};
ON_DECL
bool operator==(const ON_Material&, const ON_Material&);
ON_DECL
bool operator!=(const ON_Material&, const ON_Material&);
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_Material*>;
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<const ON_Material*>;
ON_DLL_TEMPLATE template class ON_CLASS ON_ObjectArray<ON_Material>;
// NO! // ON_DLL_TEMPLATE template class ON_CLASS ON_ClassArray<ON_Material>;
// It is a serious error to have an ON_ClassArray<ON_Material> and crashes
// will occur when user data back pointers are not updated.
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Class ON_PBRMaterial
//
class ON_CLASS ON_PhysicallyBasedMaterial
{
public:
ON_PhysicallyBasedMaterial(const ON_Material& src);
ON_PhysicallyBasedMaterial(const ON_PhysicallyBasedMaterial& src);
virtual ~ON_PhysicallyBasedMaterial();
virtual bool IsValid(class ON_TextLog* text_log = nullptr) const;
/////////////////////////////////////////////////////////////////
// Interface
public:
//Reflectance model to use. Default is GGX. Renderers do not need to support a specific
//model, but certain material definitions may specify in the hope that a renderer will support.
//GGX support is built into Rhino (Cycles, display)
enum class BRDFs : int
{
GGX = 0, //http://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf
Ward = 1, //https://pdfs.semanticscholar.org/330e/59117d7da6c794750730a15f9a178391b9fe.pdf
};
virtual BRDFs BRDF(void) const;
virtual void SetBRDF(const BRDFs&);
virtual ON_4fColor BaseColor(void) const;
virtual void SetBaseColor(const ON_4fColor&);
//Controls diffuse shape using a subsurface approximation. If full subsurface transport is
//implemented, acts as a mix between diffuse and SSS
virtual double Subsurface(void) const;
virtual void SetSubsurface(double);
//Color for full subsurface transport if implemented
virtual ON_4fColor SubsurfaceScatteringColor(void) const;
virtual void SetSubsurfaceScatteringColor(const ON_4fColor&);
//Radius for full subsurface transport if implemented
virtual double SubsurfaceScatteringRadius(void) const;
virtual void SetSubsurfaceScatteringRadius(double);
//The metallic-ness (0 = dielectric, 1 = metallic). This is a linear blend between two
//different models.The metallic model has no diffuse component and also has a tinted incident
//specular, equal to the base color
virtual double Metallic(void) const;
virtual void SetMetallic(double);
//Incident specular amount. Linked to Ior property below.
//specular=((ior1)/(ior+1))2/0.08
virtual double Specular(void) const;
virtual void SetSpecular(double);
//Reflective Ior - see specular amount above. Linked to Specular property
virtual double ReflectiveIOR(void) const;
virtual void SetReflectiveIOR(double);
//A concession for artistic control that tints incident specular towards the base color.
//Grazing specular is still achromatic.
//Tints the facing specular reflection using the base color, while glancing reflection remains white.
//Normal dielectrics have colorless reflection, so this parameter is not technically physically correct and is provided for faking the appearance of materials with complex surface structure.
virtual double SpecularTint(void) const;
virtual void SetSpecularTint(double);
//Surface roughness, controls both diffuse and specular response
virtual double Roughness(void) const;
virtual void SetRoughness(double);
//Degree of anisotropy. This controls the aspect ratio of the specular highlight. (0 = isotropic, 1 = maximally anisotropic)
virtual double Anisotropic(void) const;
virtual void SetAnisotropic(double);
//Rotates the direction of anisotropy, with 1.0 going full circle.
virtual double AnisotropicRotation(void) const;
virtual void SetAnisotropicRotation(double);
//An additional grazing component, primarily intended for cloth.
//Amount of soft velvet like reflection near edges, for simulating materials such as cloth.
virtual double Sheen(void) const;
virtual void SetSheen(double);
//Amount to tint sheen towards base color
virtual double SheenTint(void) const;
virtual void SetSheenTint(double);
//A second, special-purpose specular lobe - Extra white specular layer on top of others. This is useful for materials like car paint and the like.
virtual double Clearcoat(void) const;
virtual void SetClearcoat(double);
//Controls clearcoat glossiness (0 = a “satin” appearance, 1 = a “gloss” appearance)
virtual double ClearcoatRoughness(void) const;
virtual void SetClearcoatRoughness(double);
//Index of refraction for transmission.
virtual double OpacityIOR(void) const;
virtual void SetOpacityIOR(double);
//Mix between fully opaque surface at zero and fully glass like transmission at one.
virtual double Opacity(void) const;
virtual void SetOpacity(double);
//Controls roughness used for transmitted light.
virtual double OpacityRoughness(void) const;
virtual void SetOpacityRoughness(double);
//Controls emission - uses base color.
virtual ON_4fColor Emission(void) const;
virtual void SetEmission(ON_4fColor);
//Controls Alpha transparency - 1.0 is fully opaque, 0.0 is non-visible. Use opacity for refraction - this overrides all other shading.
/*virtual*/ double Alpha(void) const;
/*virtual*/ void SetAlpha(double);
//Texture access functions - exactly the same as ON_Material. Provided for ease of use.
virtual int FindTexture(const wchar_t* filename, ON_Texture::TYPE type, int i0 = -1) const;
virtual int AddTexture(const ON_Texture& tx);
virtual int AddTexture( const wchar_t* filename, ON_Texture::TYPE type);
virtual int DeleteTexture(const wchar_t* filename, ON_Texture::TYPE type);
//Access the referenced ON_Material.
virtual ON_Material& Material(void);
virtual const ON_Material& Material(void) const;
//Call this function to set the ON_Material up to represent the PBR material as well as possible.
virtual void SynchronizeLegacyMaterial(void);
//Expert function to remove all PBR data from a material
virtual void ToLegacy(void);
//These function just route through to ON_Material - PBR materials need to support the same functionality.
//
//If UseBaseColorTextureAlphaForObjectAlphaTransparencyTexture returns true, the alpha channel
//of the texture in m_textures with m_type=pbr_base_color is used in addition to any
//textures with m_type=pbr_alpha_texture.
bool UseBaseColorTextureAlphaForObjectAlphaTransparencyTexture() const;
void SetUseBaseColorTextureAlphaForObjectAlphaTransparencyTexture(bool);
public:
class ON_CLASS ParametersNames
{
public:
ON_DEPRECATED_MSG("Use CRhRdkMaterial::PhysicallyBased::ParameterNames") static ON_wString BaseColor(void);
ON_DEPRECATED_MSG("Use CRhRdkMaterial::PhysicallyBased::ParameterNames") static ON_wString BRDF(void);
ON_DEPRECATED_MSG("Use CRhRdkMaterial::PhysicallyBased::ParameterNames") static ON_wString Subsurface(void);
ON_DEPRECATED_MSG("Use CRhRdkMaterial::PhysicallyBased::ParameterNames") static ON_wString SubsurfaceScatteringColor(void);
ON_DEPRECATED_MSG("Use CRhRdkMaterial::PhysicallyBased::ParameterNames") static ON_wString SubsurfaceScatteringRadius(void);
ON_DEPRECATED_MSG("Use CRhRdkMaterial::PhysicallyBased::ParameterNames") static ON_wString Specular(void);
ON_DEPRECATED_MSG("Use CRhRdkMaterial::PhysicallyBased::ParameterNames") static ON_wString SpecularTint(void);
ON_DEPRECATED_MSG("Use CRhRdkMaterial::PhysicallyBased::ParameterNames") static ON_wString Metallic(void);
ON_DEPRECATED_MSG("Use CRhRdkMaterial::PhysicallyBased::ParameterNames") static ON_wString Roughness(void);
ON_DEPRECATED_MSG("Use CRhRdkMaterial::PhysicallyBased::ParameterNames") static ON_wString Anisotropic(void);
ON_DEPRECATED_MSG("Use CRhRdkMaterial::PhysicallyBased::ParameterNames") static ON_wString AnisotropicRotation(void);
ON_DEPRECATED_MSG("Use CRhRdkMaterial::PhysicallyBased::ParameterNames") static ON_wString Sheen(void);
ON_DEPRECATED_MSG("Use CRhRdkMaterial::PhysicallyBased::ParameterNames") static ON_wString SheenTint(void);
ON_DEPRECATED_MSG("Use CRhRdkMaterial::PhysicallyBased::ParameterNames") static ON_wString Clearcoat(void);
ON_DEPRECATED_MSG("Use CRhRdkMaterial::PhysicallyBased::ParameterNames") static ON_wString ClearcoatRoughness(void);
ON_DEPRECATED_MSG("Use CRhRdkMaterial::PhysicallyBased::ParameterNames") static ON_wString ClearcoatBump(void);
ON_DEPRECATED_MSG("Use CRhRdkMaterial::PhysicallyBased::ParameterNames") static ON_wString OpacityIor(void);
ON_DEPRECATED_MSG("Use CRhRdkMaterial::PhysicallyBased::ParameterNames") static ON_wString Opacity(void);
ON_DEPRECATED_MSG("Use CRhRdkMaterial::PhysicallyBased::ParameterNames") static ON_wString OpacityRoughness(void);
ON_DEPRECATED_MSG("Use CRhRdkMaterial::PhysicallyBased::ParameterNames") static ON_wString Emission(void);
};
private:
class Impl;
const Impl& Implementation(void) const;
Impl& Implementation(void);
unsigned char _impl[64];
//Ban copying - usage should be material.PhysicallyBased().Function()
ON_PhysicallyBasedMaterial& operator=(const ON_Material& src) = delete;
ON_PhysicallyBasedMaterial& operator=(const ON_PhysicallyBasedMaterial& src) = delete;
friend ON_Material;
friend bool ON_PhysicallyBasedMaterial_Supported(const ON_PhysicallyBasedMaterial& material);
};
#endif
File diff suppressed because it is too large Load Diff
+614
View File
@@ -0,0 +1,614 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(ON_MATRIX_INC_)
#define ON_MATRIX_INC_
class ON_Xform;
class ON_CLASS ON_Matrix
{
public:
ON_Matrix();
ON_Matrix(
int row_count,
int col_count
);
ON_Matrix( // see ON_Matrix::Create(int,int,int,int) for details
int, // first valid row index
int, // last valid row index
int, // first valid column index
int // last valid column index
);
ON_Matrix( const ON_Xform& );
ON_Matrix( const ON_Matrix& );
#if defined(ON_HAS_RVALUEREF)
// rvalue copy constructor
ON_Matrix(ON_Matrix&&) ON_NOEXCEPT;
// The rvalue assignment operator calls ON_Object::operator=(ON_Object&&)
// which could throw exceptions. See the implementation of
// ON_Object::operator=(ON_Object&&) for details.
ON_Matrix& operator=(ON_Matrix&&);
#endif
/*
Description:
This constructor is for experts who have storage for a matrix
and need to use it in ON_Matrix form.
Parameters:
row_count - [in]
col_count - [in]
M - [in]
bDestructorFreeM - [in]
If true, ~ON_Matrix will call onfree(M).
If false, caller is managing M's memory.
Remarks:
ON_Matrix functions that increase the value of row_count or col_count
will fail on a matrix created with this constructor.
*/
ON_Matrix(
int row_count,
int col_count,
double** M,
bool bDestructorFreeM
);
/*
Returns:
A row_count X col_count martix on the heap that can be
deleted by calling ON_Matrix::Deallocate().
*/
static double** Allocate(
unsigned int row_count,
unsigned int col_count
);
static void Deallocate(
double** M
);
virtual ~ON_Matrix();
void EmergencyDestroy(); // call if memory pool used matrix by becomes invalid
// ON_Matrix[i][j] = value at row i and column j
// 0 <= i < RowCount()
// 0 <= j < ColCount()
double* operator[](int);
const double* operator[](int) const;
ON_Matrix& operator=(const ON_Matrix&);
ON_Matrix& operator=(const ON_Xform&);
bool IsValid() const;
int IsSquare() const; // returns 0 for no and m_row_count (= m_col_count) for yes
int RowCount() const;
int ColCount() const;
int MinCount() const; // smallest of row and column count
int MaxCount() const; // largest of row and column count
unsigned int UnsignedRowCount() const;
unsigned int UnsignedColCount() const;
unsigned int UnsignedMinCount() const; // smallest of row and column count
unsigned int UnsignedMaxCount() const; // largest of row and column count
void RowScale(int,double);
void ColScale(int,double);
void RowOp(int,double,int);
void ColOp(int,double,int);
bool Create(
int, // number of rows
int // number of columns
);
bool Create( // E.g., Create(1,5,1,7) creates a 5x7 sized matrix that with
// "top" row = m[1][1],...,m[1][7] and "bottom" row
// = m[5][1],...,m[5][7]. The result of Create(0,m,0,n) is
// identical to the result of Create(m+1,n+1).
int, // first valid row index
int, // last valid row index
int, // first valid column index
int // last valid column index
);
/*
Description:
This constructor is for experts who have storage for a matrix
and need to use it in ON_Matrix form.
Parameters:
row_count - [in]
col_count - [in]
M - [in]
bDestructorFreeM - [in]
If true, ~ON_Matrix will call onfree(M).
If false, caller is managing M's memory.
Remarks:
ON_Matrix functions that increase the value of row_count or col_count
will fail on a matrix created with this constructor.
*/
bool Create(
int row_count,
int col_count,
double** M,
bool bDestructorFreeM
);
void Destroy();
void Zero();
void SetDiagonal(double); // sets diagonal value and zeros off diagonal values
void SetDiagonal(const double*); // sets diagonal values and zeros off diagonal values
void SetDiagonal(int, const double*); // sets size to count x count and diagonal values and zeros off diagonal values
void SetDiagonal(const ON_SimpleArray<double>&); // sets size to length X lengthdiagonal values and zeros off diagonal values
bool Transpose();
bool SwapRows( int, int ); // ints are row indices to swap
bool SwapCols( int, int ); // ints are col indices to swap
bool Invert(
double // zero tolerance
);
/*
Description:
Set this = A*B.
Parameters:
A - [in]
(Can be this)
B - [in]
(Can be this)
Returns:
True when A is an mXk matrix and B is a k X n matrix; in which case
"this" will be an mXn matrix = A*B.
False when A.ColCount() != B.RowCount().
*/
bool Multiply( const ON_Matrix& A, const ON_Matrix& B );
/*
Description:
Set this = A+B.
Parameters:
A - [in]
(Can be this)
B - [in]
(Can be this)
Returns:
True when A and B are mXn matrices; in which case
"this" will be an mXn matrix = A+B.
False when A and B have different sizes.
*/
bool Add( const ON_Matrix& A, const ON_Matrix& B );
/*
Description:
Set this = s*this.
Parameters:
s - [in]
Returns:
True when A and s are valid.
*/
bool Scale( double s );
// Description:
// Row reduce a matrix to calculate rank and determinant.
// Parameters:
// zero_tolerance - [in] (>=0.0) zero tolerance for pivot test
// If the absolute value of a pivot is <= zero_tolerance,
// then the pivot is assumed to be zero.
// determinant - [out] value of determinant is returned here.
// pivot - [out] value of the smallest pivot is returned here
// Returns:
// Rank of the matrix.
// Remarks:
// The matrix itself is row reduced so that the result is
// an upper triangular matrix with 1's on the diagonal.
int RowReduce( // returns rank
double, // zero_tolerance
double&, // determinant
double& // pivot
);
// Description:
// Row reduce a matrix as the first step in solving M*X=B where
// B is a column of values.
// Parameters:
// zero_tolerance - [in] (>=0.0) zero tolerance for pivot test
// If the absolute value of a pivot is <= zero_tolerance,
// then the pivot is assumed to be zero.
// B - [in/out] an array of m_row_count values that is row reduced
// with the matrix.
// determinant - [out] value of determinant is returned here.
// pivot - [out] If not nullptr, then the value of the smallest
// pivot is returned here
// Returns:
// Rank of the matrix.
// Remarks:
// The matrix itself is row reduced so that the result is
// an upper triangular matrix with 1's on the diagonal.
// Example:
// Solve M*X=B;
// double B[m] = ...;
// double B[n] = ...;
// ON_Matrix M(m,n) = ...;
// M.RowReduce(ON_ZERO_TOLERANCE,B); // modifies M and B
// M.BackSolve(m,B,X); // solution is in X
// See Also:
// ON_Matrix::BackSolve
int RowReduce(
double, // zero_tolerance
double*, // B
double* = nullptr // pivot
);
// Description:
// Row reduce a matrix as the first step in solving M*X=B where
// B is a column of 3d points
// Parameters:
// zero_tolerance - [in] (>=0.0) zero tolerance for pivot test
// If the absolute value of a pivot is <= zero_tolerance,
// then the pivot is assumed to be zero.
// B - [in/out] an array of m_row_count 3d points that is
// row reduced with the matrix.
// determinant - [out] value of determinant is returned here.
// pivot - [out] If not nullptr, then the value of the smallest
// pivot is returned here
// Returns:
// Rank of the matrix.
// Remarks:
// The matrix itself is row reduced so that the result is
// an upper triangular matrix with 1's on the diagonal.
// See Also:
// ON_Matrix::BackSolve
int RowReduce(
double, // zero_tolerance
ON_3dPoint*, // B
double* = nullptr // pivot
);
// Description:
// Row reduce a matrix as the first step in solving M*X=B where
// B is a column arbitrary dimension points.
// Parameters:
// zero_tolerance - [in] (>=0.0) zero tolerance for pivot test
// If a the absolute value of a pivot is <= zero_tolerance,
// then the pivoit is assumed to be zero.
// pt_dim - [in] dimension of points
// pt_stride - [in] stride between points (>=pt_dim)
// pt - [in/out] array of m_row_count*pt_stride values.
// The i-th point is
// (pt[i*pt_stride],...,pt[i*pt_stride+pt_dim-1]).
// This array of points is row reduced along with the
// matrix.
// pivot - [out] If not nullptr, then the value of the smallest
// pivot is returned here
// Returns:
// Rank of the matrix.
// Remarks:
// The matrix itself is row reduced so that the result is
// an upper triangular matrix with 1's on the diagonal.
// See Also:
// ON_Matrix::BackSolve
int RowReduce( // returns rank
double, // zero_tolerance
int, // pt_dim
int, // pt_stride
double*, // pt
double* = nullptr // pivot
);
// Description:
// Solve M*X=B where M is upper triangular with a unit diagonal and
// B is a column of values.
// Parameters:
// zero_tolerance - [in] (>=0.0) used to test for "zero" values in B
// in under determined systems of equations.
// Bsize - [in] (>=m_row_count) length of B. The values in
// B[m_row_count],...,B[Bsize-1] are tested to make sure they are
// "zero".
// B - [in] array of length Bsize.
// X - [out] array of length m_col_count. Solutions returned here.
// Remarks:
// Actual values M[i][j] with i <= j are ignored.
// M[i][i] is assumed to be one and M[i][j] i<j is assumed to be zero.
// For square M, B and X can point to the same memory.
// See Also:
// ON_Matrix::RowReduce
bool BackSolve(
double, // zero_tolerance
int, // Bsize
const double*, // B
double* // X
) const;
// Description:
// Solve M*X=B where M is upper triangular with a unit diagonal and
// B is a column of 3d points.
// Parameters:
// zero_tolerance - [in] (>=0.0) used to test for "zero" values in B
// in under determined systems of equations.
// Bsize - [in] (>=m_row_count) length of B. The values in
// B[m_row_count],...,B[Bsize-1] are tested to make sure they are
// "zero".
// B - [in] array of length Bsize.
// X - [out] array of length m_col_count. Solutions returned here.
// Remarks:
// Actual values M[i][j] with i <= j are ignored.
// M[i][i] is assumed to be one and M[i][j] i<j is assumed to be zero.
// For square M, B and X can point to the same memory.
// See Also:
// ON_Matrix::RowReduce
bool BackSolve(
double, // zero_tolerance
int, // Bsize
const ON_3dPoint*, // B
ON_3dPoint* // X
) const;
// Description:
// Solve M*X=B where M is upper triangular with a unit diagonal and
// B is a column of points
// Parameters:
// zero_tolerance - [in] (>=0.0) used to test for "zero" values in B
// in under determined systems of equations.
// pt_dim - [in] dimension of points
// Bsize - [in] (>=m_row_count) number of points in B[]. The points
// correspoinding to indices m_row_count, ..., (Bsize-1)
// are tested to make sure they are "zero".
// Bpt_stride - [in] stride between B points (>=pt_dim)
// Bpt - [in/out] array of m_row_count*Bpt_stride values.
// The i-th B point is
// (Bpt[i*Bpt_stride],...,Bpt[i*Bpt_stride+pt_dim-1]).
// Xpt_stride - [in] stride between X points (>=pt_dim)
// Xpt - [out] array of m_col_count*Xpt_stride values.
// The i-th X point is
// (Xpt[i*Xpt_stride],...,Xpt[i*Xpt_stride+pt_dim-1]).
// Remarks:
// Actual values M[i][j] with i <= j are ignored.
// M[i][i] is assumed to be one and M[i][j] i<j is assumed to be zero.
// For square M, B and X can point to the same memory.
// See Also:
// ON_Matrix::RowReduce
bool BackSolve(
double, // zero_tolerance
int, // pt_dim
int, // Bsize
int, // Bpt_stride
const double*,// Bpt
int, // Xpt_stride
double* // Xpt
) const;
bool IsRowOrthoganal() const;
bool IsRowOrthoNormal() const;
bool IsColOrthoganal() const;
bool IsColOrthoNormal() const;
double** m = nullptr; // m[i][j] = value at row i and column j
// 0 <= i < RowCount()
// 0 <= j < ColCount()
private:
int m_row_count = 0;
int m_col_count = 0;
// m_rowmem[i][j] = row i+m_row_offset and column j+m_col_offset.
ON_SimpleArray<double*> m_rowmem;
double** m_Mmem = nullptr; // used by Create(row_count,col_count,user_memory,true);
int m_row_offset = 0; // = ri0 when sub-matrix constructor is used
int m_col_offset = 0; // = ci0 when sub-matrix constructor is used
void* m_cmem = nullptr;
// returns 0 based arrays, even in submatrix case.
double const * const * ThisM() const;
double * * ThisM();
};
/*
Description:
Perform simple row reduction on a matrix. If A is square, positive
definite, and really really nice, then the returned B is the inverse
of A. If A is not positive definite and really really nice, then it
is probably a waste of time to call this function.
Parameters:
row_count - [in]
col_count - [in]
zero_pivot - [in]
absolute values <= zero_pivot are considered to be zero
A - [in/out]
A row_count X col_count matrix. Input is the matrix to be
row reduced. The calculation destroys A, so output A is garbage.
B - [out]
A a row_count X row_count matrix. That records the row reduction.
pivots - [out]
minimum and maximum absolute values of pivots.
Returns:
Rank of A. If the returned value < min(row_count,col_count),
then a zero pivot was encountered.
If C = input value of A, then B*C = (I,*)
*/
ON_DECL
int ON_RowReduce(
int row_count,
int col_count,
double zero_pivot,
double** A,
double** B,
double pivots[2]
);
/*
Description:
Calculate a row reduction matrix so that R*M = upper triangular matrixPerform simple row reduction on a matrix. If A is square, positive
definite, and really really nice, then the returned B is the inverse
of A. If A is not positive definite and really really nice, then it
is probably a waste of time to call this function.
Parameters:
row_count - [in]
col_count - [in]
zero_pivot - [in]
absolute values <= zero_pivot_tolerance are considered to be zero
constA - [in]
nullptr or a row_count x col_count matrix.
bInitializeB - [in]
If true, then B is set to the rox_count x row_count identity
before the calculation begins.
bInitializeColumnPermutation - [in]
If true and nullptr != column_permutation, then
column_permutation[] is initialized to (0, 1, ..., col_count-1)
before the calculation begins.
A - [in/out]
A row_count X col_count matrix.
If constA is not null, then A can be null or is the workspace used
to row reduce.
If constA is null, then the input A must not be null and must be initialized.
In all cases, the calculation destroys the contents of A and
output A contains garbage.
B - [in/out]
A a row_count X row_count matrix
The row operations applied to A are also applied to B.
If the input B is the identity, then R*(input A) would have zeros below the diagonal.
column_permutation - [in/out]
The permutation applied to the columns of A is also applied to
the column_permutation[] array.
pivots - [out]
pivots[0] = maximum nonzero pivot
pivots[1] = minimum nonzero pivot
pivots[2] = largest pivot that was treated as zero
Returns:
Rank of A. If the returned value < min(row_count,col_count),
then a zero pivot was encountered.
If C = input value of A, then B*C = (I,*)
*/
ON_DECL
unsigned int ON_RowReduce(
unsigned int row_count,
unsigned col_count,
double zero_pivot_tolerance,
const double*const* constA,
bool bInitializeB,
bool bInitializeColumnPermutation,
double** A,
double** B,
unsigned int* column_permutation,
double pivots[3]
);
/*
Parameters:
N - [in] >= 1
M - [in]
M is an NxN matrix
bTransposeM - [in]
If true, the eigenvectors of the transpose of M are calculated.
Put another way, if bTransposeM is false, then the "right"
eigenvectors are calculated; if bTransposeM is true, then the "left"
eigenvectors are calculated.
lambda - [in]
known eigenvalue of M
lambda_multiplicity - [in]
> 0: known algebraic multiplicity of lambda
0: algebraic multiplicity is unknown.
termination_tolerances - [in]
An array of three tolerances that control when the calculation
will stop searching for eigenvectors.
If you do not understand what pivot values are, then pass nullptr
and the values (1.0e-12, 1.0e-3, 1.0e4) will be used.
If termination_tolerances[0] is not strictly positive, then 1.0e-12 is used.
If termination_tolerances[1] is not strictly positive, then 1.0e-3 is used.
If termination_tolerances[2] is not strictly positive, then 1.0e4 is used.
The search for eigenvectors will continue if condition 1,
and condition 2, and condition 3a or 3b is true.
1) The number of found eigenvectors is < lambda_multiplicity.
2) eigenpivots[0] >= eigenpivots[1] > eigenpivots[2] >= 0.
3a) eigenpivots[1]/eigenpivots[0] < termination_tolerance[0].
3b) eigenpivots[1]/eigenpivots[0] > termination_tolerance[1]
or
eigenpivots[0] - eigenpivots[1] <= termination_tolerance[2]*eigenpivots[1].
eigenvectors - [out]
eigenvectors[0,...,eigendim-1][0,...,N-1]
a basis for the lambda eigenspace. The eigenvectors are generally
neither normalized nor orthoganal.
eigenprecision - [out]
eigenprecision[i] = maximum value of fabs(lambda*E[j] = E[j])/length(E) 0 <= j < N,
where E = eigenvectors[i].
If eigenprecision[i] is not "small" compared to nonzero coefficients in M and E,
then E is not precise.
eigenpivots - [out]
eigenpivots[0] = maximum nonzero pivot
eigenpivots[1] = minimum nonzero pivot
eigenpivots[2] = maximum "zero" pivot
When eigenpivots[2] s not "small" compared to eigenpivots[1],
the answer is suspect.
Returns:
Number of eigenvectors found. In stable cases, this is the geometric
multiplicity of the eigenvalue.
*/
ON_DECL
unsigned int ON_GetEigenvectors(
const unsigned int N,
const double*const* M,
bool bTransposeM,
double lambda,
unsigned int lambda_multiplicity,
const double* termination_tolerances,
double** eigenvectors,
double* eigenprecision,
double* eigenpivots
);
ON_DECL
double ON_EigenvectorPrecision(
const unsigned int N,
const double*const* M,
bool bTransposeM,
double lambda,
const double* eigenvector
);
/*
Returns:
Maximum of fabs( ((M-lambda*I)*X)[i] - B[i] ) for 0 <= i < N
Pass lambda = 0.0 if you're not testing some type of generalized eigenvalue.
*/
ON_DECL
double ON_MatrixSolutionPrecision(
const unsigned int N,
const double*const* M,
bool bTransposeM,
double lambda,
const double* X,
const double* B
);
#endif
+320
View File
@@ -0,0 +1,320 @@
/*
//
// Copyright (c) 1993-2015 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_MD5_INC_)
#define OPENNURBS_MD5_INC_
/*
The ON_MD5 class is based on code that is modified from C code with the following copyright.
Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights reserved.
License to copy and use this software is granted provided that it
is identified as the "RSA Data Security, Inc. MD5 Message-Digest
Algorithm" in all material mentioning or referencing this software
or this function.
License is also granted to make and use derivative works provided
that such works are identified as "derived from the RSA Data
Security, Inc. MD5 Message-Digest Algorithm" in all material
mentioning or referencing the derived work.
RSA Data Security, Inc. makes no representations concerning either
the merchantability of this software or the suitability of this
software for any particular purpose. It is provided "as is"
without express or implied warranty of any kind.
These notices must be retained in any copies of any part of this
documentation and/or software.
*/
class ON_CLASS ON_MD5_Hash
{
public:
static const ON_MD5_Hash ZeroDigest; // all digest bytes are zero
static const ON_MD5_Hash EmptyContentHash; // MD5 hash of zero bytes
// Default constructor is the zero digest hash
ON_MD5_Hash();
~ON_MD5_Hash() = default;
ON_MD5_Hash(const ON_MD5_Hash&) = default;
ON_MD5_Hash& operator=(const ON_MD5_Hash&) = default;
/*
Parameters:
buffer - [in]
sizeof_buffer - [in]
number of bytes in buffer
Returns:
MD5 hash of the buffer.
*/
static ON_MD5_Hash BufferHash(
const void* buffer,
size_t sizeof_buffer
);
/*
Parameters:
filename - [in]
Name of file
sizeof_file - [out]
number of bytes in file
Returns:
MD5 hash of the buffer.
*/
static ON_MD5_Hash FileHash(
const wchar_t* filename,
ON__UINT64& sizeof_file
);
static ON_MD5_Hash FileHash(
const char* filename,
ON__UINT64& sizeof_file
);
/*
Parameters:
file - [in]
File stream from ON_FileStream::Open(...,L"rb");
sizeof_file - [out]
number of bytes in file
Returns:
MD5 hash of the file stream from the current
offset to the end of the file.
*/
static ON_MD5_Hash FileHash(
FILE* file,
ON__UINT64& sizeof_file
);
/*
Parameters:
str - [in]
string
byte_count - [out]
number of bytes in UTF-8 encoding of the string.
Returns:
MD5 hash of the UTF-8 encoding of the string. (Platforms and endian independent.)
*/
static ON_MD5_Hash StringHash(
const ON_wString& str,
ON__UINT64& byte_count
);
static ON_MD5_Hash StringHash(
const wchar_t* str,
size_t str_length,
ON__UINT64& byte_count
);
/*
Parameters:
str - [in]
byte_count - [out]
number of bytes in the string.
Returns:
MD5 hash of the UTF-8 encoding of the string. (Platforms and endian independent.)
*/
static ON_MD5_Hash StringHash(
const ON_String& str,
ON__UINT64& byte_count
);
static ON_MD5_Hash StringHash(
const char* str,
size_t str_length,
ON__UINT64& byte_count
);
static int Compare(
const ON_MD5_Hash& a,
const ON_MD5_Hash& b
);
/*
Parameters:
bUpperCaseHexadecimalDigits - [in]
false - use 0-9, a-f
true - use 0-9, A-F
Returns:
The MD5 hash value as a 32 hexadecimal digits.
The first digit in the string is the hexadecimal value of m_digest[0].
*/
const ON_String ToUTF8String(
bool bUpperCaseHexadecimalDigits
) const;
/*
Parameters:
bUpperCaseHexadecimalDigits - [in]
false - use 0-9, a-f
true - use 0-9, A-F
Returns:
The MD5 hash value as a 32 hexadecimal digits.
The first digit in the string is the hexadecimal value of m_digest[0].
*/
const ON_wString ToString(
bool bUpperCaseHexadecimalDigits
) const;
bool Read(
class ON_BinaryArchive& archive
);
bool Write(
class ON_BinaryArchive& archive
) const;
void Dump(
class ON_TextLog& text_log
) const;
ON__UINT8 m_digest[16];
};
ON_DECL
bool operator==(const ON_MD5_Hash& a, const ON_MD5_Hash& b);
ON_DECL
bool operator!=(const ON_MD5_Hash& a, const ON_MD5_Hash& b);
/*
Description:
ON_MD5 is a small class for calculating the MD5 hash of a sequence of bytes.
It may be use incrementally (the bytes do not have to be in a contiguous
array in memory at one time).
Remarks:
The ON_MD5 class cannot be used for cryptographic or security applications.
The MD5 hash algorithm is not suitable for cryptographic or security applications.
The ON_MD5 class does not "wipe" intermediate results.
The probability of two different randomly selected seqences of N bytes to have the
same value MD5 hash depends on N, but it is roughly 2^-64 ~ 10^-19.
MD5 hash values are 16 bytes. SHA-1 hash values are 20 bytes. If you need a hash
and have room for 20 bytes, then ON_SHA1 is preferred over ON_MD5.
Legal:
Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights reserved.
License to copy and use this software is granted provided that it
is identified as the "RSA Data Security, Inc. MD5 Message-Digest
Algorithm" in all material mentioning or referencing this software
or this function.
License is also granted to make and use derivative works provided
that such works are identified as "derived from the RSA Data
Security, Inc. MD5 Message-Digest Algorithm" in all material
mentioning or referencing the derived work.
RSA Data Security, Inc. makes no representations concerning either
the merchantability of this software or the suitability of this
software for any particular purpose. It is provided "as is"
without express or implied warranty of any kind.
These notices must be retained in any copies of any part of this
documentation and/or software.
*/
class ON_CLASS ON_MD5
{
public:
ON_MD5() = default;
~ON_MD5() = default;
ON_MD5(const ON_MD5&) = default;
ON_MD5& operator=(const ON_MD5&) = default;
/*
Description:
Make one or more calls to AccumulateBytes() as the sequenence of bytes is available.
Parameters:
buffer - [in]
sizeof_buffer - [in]
number of bytes in buffer
*/
#if defined(ON_COMPILER_MSC) && defined(NDEBUG)
// Reduces release build link time optimization by several hours for
// large programs that make lots of calls to ON_MD5.Accumulate*() functions.
__declspec(noinline)
#endif
void AccumulateBytes(
const void* buffer,
ON__UINT64 sizeof_buffer
);
/*
Returns:
Total number of bytes passed to Update().
*/
ON__UINT64 ByteCount() const;
/*
Returns:
MD5 hash value of the sequenence of ByteCount() bytes that have been
passed to this ON_MD5 classe's Update() function since construction
or the last call to Reset().
Remarks:
You may use Hash() to compute intermediate MD5 hash values.
Put another way, you may call Update() zero or more times passing in N1 bytes,
call Digest() to get the MD5 hash of those N1 bytes, make zero or more additional
calls to Update() passing in N2 additional bytes, call digest to get the MD5 hash
of the seqence of (N1 + N2) bytes, and so on.
*/
ON_MD5_Hash Hash() const;
/*
Description:
Reset this ON_MD5 class so it can be reused.
*/
void Reset();
/*
Description:
This is a static function that uses ON_MD5 to compute MD5 hash values
of sequences of bytes with known MD5 hash values and compares the
results from ON_SHA1 with the known MD5 hash values.
This function can be used to validate the ON_MD5 class compiled correctly.
Returns:
true
All validation tests passed.
false
At least one validation test failed.
*/
static bool Validate();
private:
void Internal_Accumulate(const ON__UINT8* input, ON__UINT32 length);
void set_final_hash();
ON__UINT64 m_byte_count = 0; // number of bytes that have passed through calls to Update().
// if 1 == m_status_bits & 1, then Update has been called at least once (perhaps with 0 bytes).
// if 2 == m_status_bits & 2, then m_md5_hash is current.
mutable ON__UINT32 m_status_bits = 0;
ON__UINT32 m_reserved = 0;
// current "remainder"
ON__UINT8 m_buffer[64]; // bytes that didn't fit in last 64 byte chunk
ON__UINT32 m_bit_count[2]; // number of bits (lo, hi)
ON__UINT32 m_state[4]; // current state
// chached MD5 hash - valid if 2 = (2 & m_status_bits)
mutable ON_MD5_Hash m_md5_hash;
};
#endif
+101
View File
@@ -0,0 +1,101 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_MEMORY_INC_)
#define OPENNURBS_MEMORY_INC_
#if defined (cplusplus) || defined(_cplusplus) || defined(__cplusplus)
extern "C" {
#endif
ON_DECL
size_t ON_MemoryPageSize();
/*
Allocate memory that is intentionally never returned
should not be considered a memory leak. Typically this is
for an application workspace.
*/
ON_DECL
void* onmalloc_forever( size_t );
ON_DECL
void* onmalloc( size_t );
ON_DECL
void* oncalloc( size_t, size_t );
ON_DECL
void onfree( void* );
ON_DECL
void* onrealloc( void*, size_t );
ON_DECL
void* onmemdup( const void*, size_t );
ON_DECL
char* onstrdup( const char* );
ON_DECL
wchar_t* onwcsdup( const wchar_t* );
ON_DECL
unsigned char* onmbsdup( const unsigned char* );
#if defined (cplusplus) || defined(_cplusplus) || defined(__cplusplus)
}
class ON_CLASS ON_MemoryAllocationTracking
{
public:
/*
Descrption:
Windows Debug Builds:
The constructor saves the current state of memory allocation tracking
and then enables/disables memory allocation tracking.
Otherwise:
Does nothting.
*/
ON_MemoryAllocationTracking(
bool bEnableAllocationTracking
);
/*
Descrption:
Windows Debug Builds:
The desctructor restores the saved state of memory allocation tracking.
Otherwise:
Does nothting.
*/
~ON_MemoryAllocationTracking();
private:
static unsigned int m_g_stack_depth;
static int m_g_crt_dbg_flag0;
const unsigned int m_this_statck_depth;
const int m_this_crt_dbg_flag0;
private:
ON_MemoryAllocationTracking() = delete;
ON_MemoryAllocationTracking(const ON_MemoryAllocationTracking&) = delete;
ON_MemoryAllocationTracking& operator=(const ON_MemoryAllocationTracking&) = delete;
};
#endif
#endif
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,250 @@
/*
//
// Copyright (c) 1993-2016 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(ON_MODEL_GEOMETRY_INC_)
#define ON_MODEL_GEOMETRY_INC_
/*
Description:
Used to store geometry table object definition and attributes in an ONX_Model.
*/
class ON_CLASS ON_ModelGeometryComponent : public ON_ModelComponent
{
ON_OBJECT_DECLARE(ON_ModelGeometryComponent);
public:
static const ON_ModelGeometryComponent Unset;
static const ON_ModelGeometryComponent* FromModelComponentRef(
const class ON_ModelComponentReference& model_component_reference,
const ON_ModelGeometryComponent* none_return_value
);
bool UpdateReferencedComponents(
const class ON_ComponentManifest& source_manifest,
const class ON_ComponentManifest& destination_manifest,
const class ON_ManifestMap& manifest_map
) override;
bool IsEmpty() const;
bool IsInstanceDefinitionGeometry() const;
private:
public:
ON_ModelGeometryComponent() ON_NOEXCEPT;
ON_ModelGeometryComponent(
ON_ModelComponent::Type type
) ON_NOEXCEPT;
~ON_ModelGeometryComponent();
ON_ModelGeometryComponent(const ON_ModelGeometryComponent&);
ON_ModelGeometryComponent& operator=(const ON_ModelGeometryComponent&);
#if defined(ON_HAS_RVALUEREF)
// rvalue copy constructor
ON_ModelGeometryComponent( ON_ModelGeometryComponent&& ) ON_NOEXCEPT;
// rvalue assignment operator
ON_ModelGeometryComponent& operator=( ON_ModelGeometryComponent&& );
#endif
void Dump(
ON_TextLog& text_log
) const override;
/*
Parameters:
geometry - [in]
ON_Curve, ON_Surface, ON_Brep, ON_Mesh, ON_Light, annotation, detail, ...
A new copy of the geometry is managed by the ON_ModelGeometryComponent class.
attributes - [in]
nullptr if not available.
A new copy of the attributes is managed by the ON_ModelGeometryComponent class.
model_geometry_component - [in]
If not nullptr, this class is set. Otherwise operator new allocates
an ON_ModelGeometryComponent class.
Remarks:
The returned ON_ModelGeometryComponent manages geometry and attributes and will
eventually delete them.
*/
static ON_ModelGeometryComponent* Create(
const class ON_Object& model_geometry,
const class ON_3dmObjectAttributes* attributes,
ON_ModelGeometryComponent* model_geometry_component
);
/*
Parameters:
geometry_object - [in]
ON_Curve, ON_Surface, ON_Brep, ON_Mesh, ON_Light, annotation, detail, ...
geometry_object was created on the heap using operator new and
the ON_ModelGeometryComponent destructor will delete geometry_object.
attributes - [in]
attributes is nullptr or was created on the heap using operator new
and the ON_ModelGeometryComponent destructor will delete attributes.
model_geometry - [in]
If not nullptr, this class is set. Otherwise operator new allocates
an ON_ModelGeometryComponent class.
Remarks:
The returned ON_ModelGeometryComponent manages geometry_object and attributes and will
eventually delete them.
*/
static ON_ModelGeometryComponent* CreateManaged(
class ON_Object* geometry_object,
class ON_3dmObjectAttributes* attributes,
ON_ModelGeometryComponent* model_geometry_component
);
/*
Parameters:
bManageGeometry - [in]
If true, geometry_object was created on the heap using operator new and
the ON_ModelGeometryComponent destructor will delete geometry_object. Othewise
the expert caller is carefully managing the geometry_object instance and memory.
geometry_object - [in]
ON_Curve, ON_Surface, ON_Brep, ON_Mesh, ON_Light, annotation, detail, ...
bManageAttributes - [in]
If true, attributes is nullptr or was created on the heap using operator new
and the ON_ModelGeometryComponent destructor will delete attributes. Othewise
the expert caller is carefully managing the attributes instance and memory.
attributes - [in]
nullptr if not available
model_geometry_component - [in]
If not nullptr, this class is set. Otherwise operator new allocates
an ON_ModelGeometryComponent class.
*/
static ON_ModelGeometryComponent* CreateForExperts(
bool bManageGeometry,
class ON_Object* geometry_object,
bool bManageAttributes,
class ON_3dmObjectAttributes* attributes,
ON_ModelGeometryComponent* model_geometry_component
);
/*
Description:
Get a pointer to geometry. The returned pointer may be shared
and should not be used to modify the geometry.
Parameters:
no_geometry_return_value - [in]
This value is returned if no geometric object has been set.
A good choices for this parameter's value depends on the context.
Common options are nullptr.
Returns:
The curve, surface, annotation, detail, light, ... geometry,
or no_geometry_return_value if the geometry has not been set.
If the geometry is a light, then ComponentType() will return ON_ModelComponent::Type::RenderLight.
If the geometry is set and something besides light, then ComponentType()
will return ON_ModelComponent::Type::ModelGeometry.
Otherwise, ComponentType() will return ON_ModelComponent::Type::ModelGeometry::Unset.
See Also:
ON_ModelGeometryComponent::Attributes()
ON_ModelGeometryComponent::Geometry()
ON_ModelGeometryComponent::ExclusiveAttributes()
ON_ModelGeometryComponent::ExclusiveGeometry();
ON_ModelComponentRef::ExclusiveModelComponent();
ONX_Model::ComponentFromRuntimeSerialNumber()
*/
const class ON_Geometry* Geometry(
const class ON_Geometry* no_geometry_return_value
) const;
/*
Description:
Get a pointer to geometry that can be used to modify the geometry.
The returned pointer is not shared at the time it is returned
and will not be shared until a copy of this ON_ModelGeometryComponent
is created.
Returns:
If this ON_ModelGeometryComponent is the only reference to the geometry,
then a pointer to the geometry is returned.
Otherwise, nullptr is returned.
See Also:
ON_ModelGeometryComponent::Attributes()
ON_ModelGeometryComponent::Geometry()
ON_ModelGeometryComponent::ExclusiveAttributes()
ON_ModelGeometryComponent::ExclusiveGeometry();
ON_ModelComponentRef::ExclusiveModelComponent();
ONX_Model::ComponentFromRuntimeSerialNumber()
*/
class ON_Geometry* ExclusiveGeometry() const;
/*
Description:
Get a pointer to attributes. The returned pointer may be shared
and should not be used to modify the attributes.
Parameters:
no_attributes_return_value - [in]
This value is returned if no attributes have been set.
A good choices for this parameter's value depends on the context.
Common options are nullptr, &ON_3dmObjectAttributes::Unset,
&ON_3dmObjectAttributes::Default, or the model's current default attributes.
Returns:
The layer, rendering and other attributes for this element,
or no_attributes_return_value if the attributes have not been set.
See Also:
ON_ModelGeometryComponent::Attributes()
ON_ModelGeometryComponent::Geometry()
ON_ModelGeometryComponent::ExclusiveAttributes()
ON_ModelGeometryComponent::ExclusiveGeometry();
ON_ModelComponentRef::ExclusiveModelComponent();
ONX_Model::ComponentFromRuntimeSerialNumber()
*/
const ON_3dmObjectAttributes* Attributes(
const ON_3dmObjectAttributes* no_attributes_return_value
) const;
/*
Description:
Get a pointer to attributes that can be used to modify the attributes.
The returned pointer is not shared at the time it is returned
and will not be shared until a copy of this ON_ModelGeometryComponent
is created.
Returns:
If this ON_ModelGeometryComponent is the only reference to the attributes,
then a pointer to the attributes is returned.
Otherwise, nullptr is returned.
See Also:
ON_ModelGeometryComponent::Attributes()
ON_ModelGeometryComponent::Geometry()
ON_ModelGeometryComponent::ExclusiveAttributes()
ON_ModelGeometryComponent::ExclusiveGeometry();
ON_ModelComponentRef::ExclusiveModelComponent();
ONX_Model::ComponentFromRuntimeSerialNumber()
*/
class ON_3dmObjectAttributes* ExclusiveAttributes() const;
private:
#pragma ON_PRAGMA_WARNING_PUSH
#pragma ON_PRAGMA_WARNING_DISABLE_MSC( 4251 )
// C4251: ... needs to have dll-interface to be used by clients of class ...
// m_geometry_sp is private and all code that manages m_sp is explicitly implemented in the DLL.
// m_attributes_sp is private and all code that manages m_sp is explicitly implemented in the DLL.
private:
std::shared_ptr<ON_Geometry> m_geometry_sp;
private:
std::shared_ptr<ON_3dmObjectAttributes> m_attributes_sp;
#pragma ON_PRAGMA_WARNING_POP
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_ModelGeometryComponent*>;
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<const ON_ModelGeometryComponent*>;
#endif
#endif
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,359 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(ON_OBJECT_HISTORY_INC_)
#define ON_OBJECT_HISTORY_INC_
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray< class ON_Value* >;
#endif
class ON_CLASS ON_CurveProxyHistory
{
public:
// Used to save information needed to create an ON_CurveProxy
// reference in history records.
ON_CurveProxyHistory();
~ON_CurveProxyHistory();
ON_CurveProxyHistory(const ON_CurveProxyHistory&) = default;
ON_CurveProxyHistory& operator=(const ON_CurveProxyHistory&) = default;
ON_ObjRef m_curve_ref; // from ON_CurveProxy.m_real_curve
bool m_bReversed; // from ON_CurveProxy.m_bReversed
ON_Interval m_full_real_curve_domain; // from ON_CurveProxy.m_real_curve.Domain()
ON_Interval m_sub_real_curve_domain; // from ON_CurveProxy.m_real_curve_domain
ON_Interval m_proxy_curve_domain; // from ON_CurveProxy.m_this_domain
// If these are empty intervals, they are from old files. Ignore them.
ON_Interval m_segment_edge_domain;
ON_Interval m_segment_trim_domain;
void Destroy();
bool Write( ON_BinaryArchive& ) const;
bool Read( ON_BinaryArchive& );
void Dump( ON_TextLog& ) const;
private:
ON__UINT8 m_reserved[32];
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_ClassArray<ON_CurveProxyHistory>;
#endif
class ON_CLASS ON_PolyEdgeHistory
{
public:
// Used to save information needed to create an CRhinoPolyEdge
// reference in history records.
ON_PolyEdgeHistory();
~ON_PolyEdgeHistory();
void Destroy();
bool Write( ON_BinaryArchive& ) const;
bool Read( ON_BinaryArchive& );
void Dump( ON_TextLog& ) const;
ON_ClassArray< ON_CurveProxyHistory > m_segment;
ON_SimpleArray<double> m_t;
int m_evaluation_mode;
private:
ON__UINT8 m_reserved[64];
};
class ON_CLASS ON_HistoryRecord : public ON_ModelComponent
{
ON_OBJECT_DECLARE(ON_HistoryRecord);
public:
static const ON_HistoryRecord Empty;
public:
ON_HistoryRecord() ON_NOEXCEPT;
~ON_HistoryRecord();
ON_HistoryRecord(const ON_HistoryRecord& src);
ON_HistoryRecord& operator=(const ON_HistoryRecord& src);
private:
void Internal_Destroy();
void Internal_Copy(
const ON_HistoryRecord& src
);
public:
bool IsValid( class ON_TextLog* text_log = nullptr ) const override;
void Dump( ON_TextLog& ) const override;
bool Write(ON_BinaryArchive& binary_archive) const override;
bool Read(ON_BinaryArchive& binary_archive) override;
private:
bool Internal_WriteV5(ON_BinaryArchive& binary_archive) const;
private:
bool Internal_ReadV5(ON_BinaryArchive& binary_archive);
public:
void DestroyValue( int value_id );
/*
Description:
For setting values.
Parameters:
value_id - [in]
If there a value with the same input
id exists, the old value is replaced.
count - [in]
Number of values
b - [in]
array of count bools
i - [in]
array of count ints
x - [in]
array of count doubles
p - [in]
array of count 3d points
v - [in]
array of count 3d vectors
xform - [in]
array of count xforms
c - [in]
array of count colors
or - [in]
array of count object references
g - [in]
array of count geometry pointers
u - [in]
array of uuids
s - [in]
string
*/
bool SetBoolValue( int value_id, bool b);
bool SetIntValue( int value_id, int i);
bool SetDoubleValue( int value_id, double x);
bool SetPointValue( int value_id, ON_3dPoint p);
bool SetVectorValue( int value_id, ON_3dVector v);
bool SetXformValue( int value_id, ON_Xform xform);
bool SetColorValue( int value_id, ON_Color c);
bool SetObjRefValue( int value_id, const ON_ObjRef& oref);
bool SetPointOnObjectValue( int value_id, const ON_ObjRef& oref, ON_3dPoint point );
bool SetUuidValue( int value_id, ON_UUID uuid );
bool SetStringValue( int value_id, const wchar_t* s );
/*
Parameters:
edge_chain - [in]
edge_chain.PersistentSubDId() must be non-nil and identify the parent subd in the model.
If the model is an ONX_Model, then the persistent id is the ON_ModelGeometryComponent.Id().
If the model is a CRhinoDoc, then the persistent id is CRhinoObject.ModelObjectId().
*/
bool SetSubDEdgeChainValue(int value_id, const ON_SubDEdgeChain& edge_chain);
bool SetGeometryValue( int value_id, ON_Geometry* g);
bool SetPolyEdgeValue( int value_id, const ON_PolyEdgeHistory& polyedge );
/*
Description:
For setting values.
Parameters:
value_id - [in]
If there a value with the same input
id exists, the old value is replaced.
count - [in]
Number of values
b - [in]
array of count bools
i - [in]
array of count ints
x - [in]
array of count doubles
P - [in]
array of count 3d points
V - [in]
array of count 3d vectors
xform - [in]
array of count xforms
c - [in]
array of count colors
or - [in]
array of count object references
g - [in]
array of count geometry pointers
u - [in]
array of uuids
s - [in]
array of strings
*/
bool SetBoolValues( int value_id, int count, const bool* b);
bool SetIntValues( int value_id, int count, const int* i);
bool SetDoubleValues( int value_id, int count, const double* x);
bool SetPointValues( int value_id, int count, const ON_3dPoint* P);
bool SetVectorValues( int value_id, int count, const ON_3dVector* V);
bool SetXformValues( int value_id, int count, const ON_Xform* xform);
bool SetColorValues( int value_id, int count, const ON_Color* c);
bool SetObjRefValues( int value_id, int count, const ON_ObjRef* oref);
bool SetUuidValues( int value_id, int count, const ON_UUID* u );
bool SetStringValues( int value_id, int count, const wchar_t* const* s );
bool SetStringValues( int value_id, const ON_ClassArray<ON_wString>& s );
bool SetGeometryValues( int value_id, const ON_SimpleArray<ON_Geometry*> a);
/*
Parameters:
edge_chain - [in]
edge_chain.PersistentSubDId() must be non-nil and identify the parent subd in the model.
If the model is an ONX_Model, then the persistent id is the ON_ModelGeometryComponent.Id().
If the model is a CRhinoDoc, then the persistent id is CRhinoObject.ModelObjectId().
*/
bool SetSubDEdgeChainValues(int value_id, const ON_ClassArray<ON_SubDEdgeChain>& edge_chains);
bool SetSubDEdgeChainValues(int value_id, const ON_SimpleArray<const ON_SubDEdgeChain*>& edge_chains);
bool SetPolyEdgeValues(int value_id, int count, const ON_PolyEdgeHistory* a);
/*
Description:
For retrieving values.
*/
bool GetStringValue( int value_id, ON_wString& str ) const;
bool GetBoolValue( int value_id, bool* b ) const;
bool GetIntValue( int value_id, int* i ) const;
bool GetDoubleValue( int value_id, double* number ) const;
bool GetPointValue( int value_id, ON_3dPoint& point ) const;
bool GetVectorValue( int value_id, ON_3dVector& point ) const;
bool GetXformValue( int value_id, ON_Xform& point ) const;
bool GetColorValue( int value_id, ON_Color* color ) const;
bool GetObjRefValue( int value_id, ON_ObjRef& oref ) const;
bool GetPointOnObjectValue( int value_id, ON_ObjRef& oref ) const;
bool GetCurveValue( int value_id, const ON_Curve*& ) const;
bool GetSurfaceValue( int value_id, const ON_Surface*& ) const;
bool GetBrepValue( int value_id, const ON_Brep*& ) const;
bool GetMeshValue( int value_id, const ON_Mesh*& ) const;
bool GetGeometryValue( int value_id, const ON_Geometry*& ) const;
bool GetSubDEdgeChainValue(int value_id, const ON_SubDEdgeChain*& edge_chain) const;
bool GetUuidValue( int value_id, ON_UUID* uuid ) const;
bool GetPolyEdgeValue( int value_id, const ON_PolyEdgeHistory*& polyedge ) const;
int GetStringValues( int value_id, ON_ClassArray<ON_wString>& string ) const;
int GetBoolValues( int value_id, ON_SimpleArray<bool>& ) const;
int GetIntValues( int value_id, ON_SimpleArray<int>& ) const;
int GetDoubleValues( int value_id, ON_SimpleArray<double>& ) const;
int GetPointValues( int value_id, ON_SimpleArray<ON_3dPoint>& ) const;
int GetVectorValues( int value_id, ON_SimpleArray<ON_3dVector>& ) const;
int GetXformValues( int value_id, ON_SimpleArray<ON_Xform>& ) const;
int GetColorValues( int value_id, ON_SimpleArray<ON_Color>& ) const;
int GetObjRefValues( int value_id, ON_ClassArray<ON_ObjRef>& objects ) const;
int GetGeometryValues( int value_id, ON_SimpleArray<const ON_Geometry*>& ) const;
int GetSubDEdgeChainValues(int value_id, ON_SimpleArray<const ON_SubDEdgeChain*>& edge_chains) const;
int GetUuidValues( int value_id, ON_SimpleArray<ON_UUID>& ) const;
int GetPolyEdgeValues( int value_id, ON_SimpleArray<const ON_PolyEdgeHistory*>& ) const;
/*
Desccription:
Determine if object is an antecedent (input) in this
history record.
Parameters:
object_uuid - [in]
Returns:
Returns true if object_uuid is the id of an input
object.
*/
bool IsAntecedent( ON_UUID object_uuid ) const;
/*
Description:
Print a list of the values in text_log.
Parameters:
text_log - [in]
Returns:
Number of values listed.
*/
int ValueReport( ON_TextLog& text_log ) const;
// CRhinoCommand::CommandId() value of the command that
// created this history record. Each time the command
// is run, it can create a history record.
ON_UUID m_command_id = ON_nil_uuid;
// A YYYYMMDDn version number that gets updated when
// a command changes. This version is checked so that
// new versions of a command's ReplayHistory don't
// attempt to use information saved in old files.
int m_version = 0;
enum class RECORD_TYPE : unsigned int
{
history_parameters = 0, // parameters for UpdateHistory
feature_parameters = 1 // parameters for a feature
};
RECORD_TYPE m_record_type = ON_HistoryRecord::RECORD_TYPE::history_parameters;
/*
Description:
Convert integer into an ON_HistoryRecord::RECORD_TYPE.
Parameters:
i - [in]
Returns:
ON_HistoryRecord::RECORD_TYPE enum with same value as i.
*/
static
ON_HistoryRecord::RECORD_TYPE RecordType(int i);
// List of object id values of antecedent objects that
// are referenced in the list of input events in m_value[].
// These were the command's "input" objects.
ON_UuidList m_antecedents;
// List of object id values of descendant objects that
// were created. These were the command's "output" objects
ON_UuidList m_descendants;
// Information needed to update the descendant objects
// when an antecedent object is modified.
ON_SimpleArray< class ON_Value* > m_value;
/*
Description:
This tool is used in rare situations when the object ids
stored in the uuid list need to be remapped.
Parameters:
uuid_remap - [in]
Is it critical that uuid_remap[] be sorted with respect
to ON_UuidPair::CompareFirstUuid.
*/
void RemapObjectIds( const ON_SimpleArray<ON_UuidPair>& uuid_remap );
/*
12 May, 2015 - Lowell
When an object is replaced and the old object has a history record with
CopyOnReplaceObject() set to tru, then history record is copied and
attached to the new object.
That allows a descendant object to continue the history linkage after
it is edited.
See http://mcneel.myjetbrains.com/youtrack/issue/RH-30399
*/
bool CopyOnReplaceObject() const;
void SetCopyOnReplaceObject(
bool bCopyOnReplaceObject
);
private:
bool m_bValuesSorted = true;
bool m_bCopyOnReplaceObject = false;
ON_Value* FindValueHelper( int, int, bool ) const;
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_HistoryRecord*>;
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<const ON_HistoryRecord*>;
ON_DLL_TEMPLATE template class ON_CLASS ON_ObjectArray<ON_HistoryRecord>;
#endif
#endif
+328
View File
@@ -0,0 +1,328 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(ON_OBJREF_INC_)
#define ON_OBJREF_INC_
class ON_CLASS ON_ObjRefEvaluationParameter
{
public:
ON_ObjRefEvaluationParameter();
~ON_ObjRefEvaluationParameter();
void Default();
bool Write( ON_BinaryArchive& ) const;
bool Read( ON_BinaryArchive& );
// If m_point != ON_3dPoint::UnsetPoint and m_t_type != 0, then
// m_t_type, m_t, and m_t_ci record the m_geometry evaluation
// parameters of the m_point.
//
// m_t_type values
//
// 0: no parameter values; m_t_ci and m_t[] have no meaning.
//
// 1: m_geometry points to a curve, m_t[0] is a curve
// parameter for m_point, and m_t_ci has no meaning.
//
// 2: m_geometry points to surface or single faced brep,
// (m_t[0],m_t[1]) is a surface parameter for m_point,
// and m_t_ci has no meaning.
// In this case, m_component_index may not be set or,
// if m_geometry points to a brep face, m_component_index
// may identify the face in the parent brep.
//
// 3: m_geometry points to a brep edge with an associated
// trim and m_t[0] is the edge parameter for m_point.
// m_t_ci is the ON_BrepTrim component index and m_t[1]
// is the ON_BrepTrim parameter that corresponds to the
// edge point. m_s[0] and m_s[1] are normalized parameters.
// In this case m_component_index identifies the
// the edge in the brep and m_t_ci identifies a trim.
//
// 4: m_geometry points to a mesh or mesh face and
// m_t_ci identifies the mesh face.
// If the face is a triangle, the barycentric coordinates
// of m_point are(m_t[0], m_t[1], m_t[2]) and m_t[3] is zero.
// If the mesh face is a quadrangle, the barycentric coordinates
// of m_point are (m_t[0], m_t[1], m_t[2], m_t[3]) and at least
// one of the coordinates is zero. In both cases, the point
// can be evaluated using the formula
// m_t[0]*mesh.m_V[f.vi[0]] + ... + m_t[3]*mesh.m_V[f.vi[3]],
// where f = mesh.m_F[m_component_index.m_index].
// In this case, if m_geometry points to a mesh, then
// m_component_index != m_t_ci.
//
// 5: m_geometry points to a mesh or mesh edge and m_t_ci
// identifies the mesh edge. The normalized coordinate of
// the point on the mesh edge is m_t[0]. The point can be evaluated
// using the formula
// m_t[0]*mesh.m_V[v0] + (1.0-m_t[0])*mesh.m_V[v1],
// where v0 and v1 are the indices of the mesh vertices at
// the edge's ends.
// In this case, if m_geometry points to a mesh, then
// m_component_index != m_t_ci.
//
// 6: m_geometry points to a NURBS cage and (m_t[0],m_t[1],m_t[2])
// are cage evaluation parameters.
//
// 7: m_geometry points to an annotation object and m_t_ci identifies
// a point on the annotation object.
//
// 8: m_geometry points to a mesh or mesh vertex object and m_t_ci
// identifies a vertex on the mesh object.
//
int m_t_type;
private:
int m_reserved; // for future use to record snap info.
public:
double m_t[4];
ON_Interval m_s[3]; // curve/surface/cage domains
ON_COMPONENT_INDEX m_t_ci; // Not necessarily the same as m_component_index
// See comment above for details.
};
class ON_CLASS ON_ObjRef_IRefID
{
public:
ON_ObjRef_IRefID() = default;
~ON_ObjRef_IRefID() = default;
ON_ObjRef_IRefID(const ON_ObjRef_IRefID&) = default;
ON_ObjRef_IRefID& operator=(const ON_ObjRef_IRefID&) = default;
bool Write(ON_BinaryArchive&) const;
bool Read(ON_BinaryArchive&);
void Default();
// m_iref_uuid is the CRhinoInstanceObject's uuid stored
// in its ON_3dmObjectAttributes.m_uuid.
ON_UUID m_iref_uuid = ON_nil_uuid;
// m_iref_xform is the value stored in ON_InstanceRef.m_xform.
ON_Xform m_iref_xform = ON_Xform::ZeroTransformation;
// m_idef_uuid is the instance definition id stored in
// ON_InstanceRef.m_instance_definition_uuid and
// ON_InstanceDefinition.m_uuid.
ON_UUID m_idef_uuid = ON_nil_uuid;
// m_geometry_index is the index of the uuid of the pertinent
// piece of geometry in the ON_InstanceRef.m_object_uuid[]
// array. This index is identical to the index of the
// geometry's CRhinoObject in the
// CRhinoInstanceDefinition.m_objects[] array.
int m_idef_geometry_index = 0;
// m_geometry_xform is the transformation to map the
// base geometry to world coordinates. If the
// instance reference is not nested, then
// m_geometry_xform = m_iref_xform. If the instance
// reference is nested, then
// m_geometry_xform = m_iref_xform * .... * T1
// where the Ts are the transformations from the children.
ON_Xform m_geometry_xform = ON_Xform::ZeroTransformation;
// If this ON_ObjRef_IRefID is the first entry in the
// ON_ObjRef.m__iref[] array, then it references a "real"
// piece of geometry (not a nested instance reference).
// If the reference is to a subobject of the real piece
// of geometry, then m_component_index records
// the subobject index.
// In all other cases, m_component_index is not set.
ON_COMPONENT_INDEX m_component_index;
// If this ON_ObjRef_IRefID is the first entry in the
// ON_ObjRef.m__iref[] array, then it references a "real"
// piece of geometry (not a nested instance reference).
// If there is an evaluation parameter for the geometry,
// it is saved in m_evp.
// In all other cases, m_evp is not set.
ON_ObjRefEvaluationParameter m_evp;
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_ObjRef_IRefID>;
#endif
class ON_CLASS ON_ObjRef
{
public:
ON_ObjRef();
ON_ObjRef(const ON_ObjRef& src);
ON_ObjRef& operator=(const ON_ObjRef& src);
~ON_ObjRef();
void Destroy();
bool Write( ON_BinaryArchive& ) const;
bool Read( ON_BinaryArchive& );
// In Rhino, this uuid is the persistent id of the CRhinoObject
// that owns the referenced geometry. The value of the
// CRhinoObject id is stored on ON_3dmObjectAttributes.m_uuid.
ON_UUID m_uuid;
// The m_geometry and m_parent_geometry pointers are runtime values
// that point to the object being referenced. The destructor
// ~ON_ObjRef does not delete the objects these pointers reference.
//
// m_geometry_type records the type of geometry m_geometry points to.
//
// When the referenced object is a subobject, like a part of a brep
// or mesh, m_geometry points to the subobject and m_parent_geometry
// points to the parent object, like the brep or mesh. In this case
// m_component_index records the location of the subobject.
//
// Parts of instance reference objects:
// When the geometry belongs to an instance reference
// m_uuid is the id of the CRhinoInstanceObject,
// m_parent_geometry points to the instance definition
// geometry or a transformed proxy, and m_geometry points
// to the piece of m_geometry. The m__iref[] array records
// the connection between the instance reference and the
// geometry the ON_ObjRef refers to.
//
// For example if the ON_ObjRef is to an edge of a brep in
// and instance reference, m_uuid would be the Rhino id of
// the CRhinoInstanceObject, m_parent_geometry would point
// to a, possibly proxy, ON_Brep object, m_geometry would point
// to the ON_BrepEdge in the ON_Brep, m_component_index would
// record the edge's index in the ON_Brep.m_E[] array and
// m_geometry_type would be ON::curve_object or ON::brep_edge.
// m__iref->Last() would contain the information about the
// top level instance reference. If the brep was at the bottom
// of a chain of instance references, m__iref[0] would be the
// reference that immediately used the brep.
const ON_Geometry* m_geometry;
const ON_Geometry* m_parent_geometry;
ON_COMPONENT_INDEX m_component_index;
int m_geometry_type;
// If m_runtime_sn > 0, then it is the value of a Rhino object's
// CRhinoObject::m_runtime_object_serial_number field.
// The serial number is used instead of the pointer to
// prevent crashes in cases when the CRhinoObject is deleted
// but an ON_ObjRef continues to reference the Rhino object.
// The value of m_runtime_sn is not saved in archives because
// it generally changes if you save and reload an archive.
unsigned int m_runtime_sn;
// If m_point != ON_3dPoint::UnsetPoint, then the ObjRef resolves to
// a point location. The point location is saved here so the
// information can persist if the object itself vanishes.
ON_3dPoint m_point;
// If the point was the result of some type of object snap, then
// the object snap is recorded here.
ON::osnap_mode m_osnap_mode;
// If m_point != ON_3dPoint::UnsetPoint and m_evp.m_t_type != 0, then
// m_evp records the records the m_geometry evaluation
// parameters for the m_point.
ON_ObjRefEvaluationParameter m_evp;
// If m__iref[] is not empty, then m_uuid identifies
// and instance reference (ON_InstanceRef/CRhinoInstanceObject)
// and m__iref[] records the chain of instance references from
// the base piece of geometry to the instance reference.
// The top level instance reference is last in the list.
ON_SimpleArray<ON_ObjRef_IRefID> m__iref;
/*
Description:
Expert user tool to decrement reference counts. Most
users will never need to call this tool. It is called
by ~ON_ObjRef and used in rare cases when a
ON_ObjRef needs to reference an object only by uuid
and component index.
*/
void DecrementProxyReferenceCount();
/*
Description:
Expert user tool to initialize the ON_ObjRef
m__proxy1, m__proxy2, and m__proxy_ref_count fields.
*/
void SetProxy(
ON_Object* proxy1,
ON_Object* proxy2,
bool bCountReferences
);
bool SetParentIRef( const ON_InstanceRef& iref,
ON_UUID iref_id,
int idef_geometry_index
);
/*
Returns:
0: This ON_ObjRef is not counting references.
>0: Number of references.
*/
int ProxyReferenceCount() const;
/*
Parameters:
proxy_object_index - [in] 1 or 2.
Returns:
A pointer to the requested proxy object.
*/
const ON_Object* ProxyObject(int proxy_object_index) const;
/*
Description:
This tool is used in rare situations when the object ids
stored in the uuid list need to be remapped.
Parameters:
uuid_remap - [in]
Is it critical that uuid_remap[] be sorted with respect
to ON_UuidPair::CompareFirstUuid.
*/
void RemapObjectId( const ON_SimpleArray<ON_UuidPair>& uuid_remap );
private:
// In simple (and the most common) cases where m_geometry
// is managed by something outside of the ON_ObjRef class,
// m__proxy_ref_count is nullptr. In this case, the m__proxy1
// and m__proxy2 pointers may still be used to store
// references to a parent object.
//
// In cases when the referenced geometry pointed at by
// m_geometry is not being managed by another class,
// m_proxy1 and m_proxy2 are not nullptr and *m_proxy_ref_count
// counts the number of ON_ObjRef classes that refer to m__proxy1/2.
// When the last ON_ObjRef is destroyed, m__proxy1/2 is deleted.
// When the ON_ObjRef is using reference counting and managing
// m__proxy1/2, m_geometry points to some part of m__proxy1/2 and
// m_geometry is destroyed when m__proxy1/2 is destroyed.
//
// The convention is to use m__proxy1 to store
// ON_MeshVertex/Edge/FaceRefs and CRhinoPolyEdges
// and m__proxy2 to store transformed copies if instance
// definition geometry.
ON_Object* m__proxy1;
ON_Object* m__proxy2;
int* m__proxy_ref_count;
//ON__INT_PTR m_reserved;
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_ClassArray<ON_ObjRef>;
#endif
#endif
+365
View File
@@ -0,0 +1,365 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(ON_OFFSETSURFACE_INC_)
#define ON_OFFSETSURFACE_INC_
class ON_CLASS ON_BumpFunction
{
public:
ON_BumpFunction();
~ON_BumpFunction() = default;
ON_BumpFunction(const ON_BumpFunction&) = default;
ON_BumpFunction& operator=(const ON_BumpFunction&) = default;
public:
double ValueAt(
double s,
double t
) const;
void Evaluate(
double s,
double t,
int der_count,
double* value
) const;
public:
ON_2dPoint m_point = ON_2dPoint::NanPoint; // center of bump
int m_type[2];// // = {0,0} // 1 = linear, 5 = quintic, else linear;
public:
// numbers used in evaluation
double m_x0 = 0.0;
double m_y0 = 0.0;
double m_sx[2]; // = {0.0, 0.0} // 1/(support radius)
double m_sy[2]; // = {0.0, 0.0} // 1/(support radius)
double m_a = 0.0; // evaluation coefficient
private:
void Internal_EvaluateLinearBump(double t, double dt, int der_count, double* value) const;
void Internal_EvaluateQuinticBump(double t, double dt, int der_count, double* value) const;
};
class ON_CLASS ON_OffsetSurfaceValue
{
public:
ON_OffsetSurfaceValue() = default;
~ON_OffsetSurfaceValue() = default;
ON_OffsetSurfaceValue(const ON_OffsetSurfaceValue&) = default;
ON_OffsetSurfaceValue& operator=(const ON_OffsetSurfaceValue&) = default;
public:
double m_s = ON_DBL_QNAN;
double m_t = ON_DBL_QNAN;
double m_distance = ON_DBL_QNAN;
double m_radius = ON_DBL_QNAN;
int m_index = ON_UNSET_INT_INDEX;
};
#if defined(ON_DLL_TEMPLATE)
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_BumpFunction>;
ON_DLL_TEMPLATE template class ON_CLASS ON_SimpleArray<ON_OffsetSurfaceValue>;
#endif
class ON_CLASS ON_OffsetSurfaceFunction
{
public:
ON_OffsetSurfaceFunction();
~ON_OffsetSurfaceFunction();
/*
Description:
Sets base surface for the offset function.
Parameters:
srf - [in] pointer to the base surface.
This surface must remain valid while
the ON_OffsetSurfaceFunction class is used.
Returns:
True if successful.
*/
bool SetBaseSurface(
const ON_Surface* srf
);
/*
Returns:
Base surface specified SetBaseSurface().
*/
const ON_Surface* BaseSurface() const;
/*
Description:
Use set SetSideTangency if you want the offset
surface and base surface to have the same unit
normals along a side of the surfaces's parameter
spaces.
Parameters:
side - [in]
0 = south side
1 = east side
2 = north side
3 = west side
bEnable - [in] true to enable tangency,
false to disable tangency
Returns:
True if successful.
*/
bool SetSideTangency(
int side,
bool bEnable
);
/*
Parameters:
side - [in]
0 = south side
1 = east side
2 = north side
3 = west side
Returns:
True if side tangency is enabled.
*/
bool SideTangency(int side) const;
/*
Description:
Sets the offset distance at a point. Call this function
once for each point wher the user specifies an offset.
Parameters:
s - [in]
t - [in] (s,t) is a base surface evaluation parameter
distance - [in] distance is the offset distance.
radius - [in] if radius>0, then this value will be the
the approximate radius of the offset "bump".
*/
bool SetOffsetPoint(
double s,
double t,
double distance,
double radius = 0.0
);
/*
Description:
Sets the surface parameters of an existing offset point.
Parameters:
index - [in] index of the point to set
s - [in]
t - [in] (s,t) is a base surface evaluation parameter
*/
bool SetPoint(
int index,
double s,
double t
);
/*
Description:
Set the offset distance for an existing point
Parameters:
index - [in] index of the point to set
distance - [in] new distance
*/
bool SetDistance(
int index,
double distance);
/*
Returns:
Number of points specified using SetOffsetPoint().
*/
int OffsetPointCount() const;
/*
Parameters:
i - [in] an index >= 0 and < OffsetPointCount()
Returns:
Surface parameter specified using SetOffsetPoint().
*/
ON_2dPoint OffsetSurfaceParameter(int i) const;
/*
Parameters:
i - [in] an index >= 0 and < OffsetPointCount()
Returns:
Offset distance specified using SetOffsetPoint().
*/
double OffsetDistance(int i) const;
/*
Description:
Value of the offset distance at any surface parameter.
Parameters:
s - [in]
t - [in] (s,t) is a base surface evaluation parameter
Returns:
offset distance at the surface parameter
*/
double DistanceAt(
double s,
double t
) const;
/*
Description:
Value of the offset distance at any surface parameter.
Parameters:
s - [in]
t - [in] (s,t) is a base surface evaluation parameter
num_der - [in] number of derivatives
value - [out] value and derivatives of distance function
value[0] = distance, value[1] = 1rst derivative,
value[2] = 2nd derivative, ...
Returns:
True if successful
*/
bool EvaluateDistance(
double s,
double t,
int num_der,
double* value
) const;
/*
Description:
Value of the offset function at any surface parameter.
Parameters:
s - [in]
t - [in] (s,t) is a base surface evaluation parameter
Returns:
Point on the offset surface.
*/
ON_3dPoint PointAt(
double s,
double t
) const;
/*
Description:
Resets this class if you want to reuse it.
*/
void Destroy();
private:
friend class ON_OffsetSurface;
bool Initialize();
const ON_Surface* m_srf;
ON_Interval m_domain[2];
bool m_bZeroSideDerivative[4]; // S,E,N,W side
ON_SimpleArray<ON_OffsetSurfaceValue> m_offset_value;
ON_SimpleArray<class ON_BumpFunction> m_bumps;
bool m_bValid;
};
class ON_CLASS ON_OffsetSurface : public ON_SurfaceProxy
{
// This is still a work in progress. In particular,
// this surface class can not be saved in files, used
// as a brep surface, added to Rhino, etc.
//
// As of January 2004, it is useful for calculating
// offset meshes and any other fitting and approximation
// tools that requires a surface evaluator but do not need
// NURBS forms, isocurves, and so on.
ON_OBJECT_DECLARE(ON_OffsetSurface);
public:
ON_OffsetSurface();
~ON_OffsetSurface();
ON_OffsetSurface( const ON_OffsetSurface& src);
ON_OffsetSurface& operator=(const ON_OffsetSurface& src);
// virtual ON_Geometry GetBBox override
bool GetBBox( double* boxmin, double* boxmax, bool bGrowBox = false ) const override;
bool Evaluate( // returns false if unable to evaluate
double, double, // evaluation parameters
int, // number of derivatives (>=0)
int, // array stride (>=Dimension())
double*, // array of length stride*(ndir+1)*(ndir+2)/2
int = 0, // optional - determines which quadrant to evaluate from
// 0 = default
// 1 from NE quadrant
// 2 from NW quadrant
// 3 from SW quadrant
// 4 from SE quadrant
int* = 0 // optional - evaluation hint (int[2]) used to speed
// repeated evaluations
) const override;
/*
Description:
Sets base surface to a surface that is not managed
by the ON_OffsetSurface class.
Parameters:
base_surface - [in] points to a base surface the
caller insures will exist for the lifetimes
of the ON_OffsetSurface class.
Returns:
True if successful.
*/
bool SetBaseSurface(
const ON_Surface* base_surface
);
/*
Description:
Sets base surface to a surface that is optionally managed
by the ON_OffsetSurface class.
Parameters:
base_surface - [in] points to a base surface the
caller insures will exist for the lifetimes
of the ON_OffsetSurface class.
bManage - [in] if true, the base_surface must point
to a surface that is on the heap and the surface
will be deleted by ~ON_OffsetSurface.
Returns:
True if successful.
*/
bool SetBaseSurface(
ON_Surface* base_surface,
bool bManage
);
/*
Returns:
Base surface;
*/
const ON_Surface* BaseSurface() const;
ON_OffsetSurfaceFunction& OffsetFunction();
const ON_OffsetSurfaceFunction& OffsetFunction() const;
private:
// If not nullptr, this points to the base surface
ON_Surface* m__pSrf;
ON_OffsetSurfaceFunction m_offset_function;
};
#endif
+101
View File
@@ -0,0 +1,101 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_OPTIMIZE_INC_)
#define OPENNURBS_OPTIMIZE_INC_
// find a local minimum of a 1 parameter function
int ON_FindLocalMinimum( // returns 0 - failed to converge, 1 - success, 2 - failed to converge to requested tolerances
int (*)(void*,double,double*,double*), // f(void*, double t, double* value, double* derivative );
void*, // passed as the void* argument to the above function
double, double, double, // ax,bx,cx, 3 abcissa ax<bx<cx or ax>bx>cx, and
// f(bx) < f(ax), and f(bx) < f(cx)
double, // tol > 0 (minimum relative step size (use ON_EPSILON when in doubt)
double, // zeps > 0 (minimum absolute step size (use 1/2*(desired absolute precision))
int, // maximum number of iterations ( use 100 when in doubt)
double* // abcissa of local minimum returned here
);
// find a local zero of a 1 parameter function
class ON_LocalZero1
{
public:
ON_LocalZero1();
virtual ~ON_LocalZero1();
virtual
bool Evaluate( // returns true if successful
double, // evaluation parameter
double*, // f(t) returned here - nullptr never passed
double*, // If not nullptr, then f'(t) returned here
int // < 0: evaluate from below
// >= 0: evaluate from above
) = 0;
bool FindZero( double* ); // Searches domain between m_t0 and m_t1
// domain for a root. Returns true if
// a root is found.
// m_t0 and m_t1 specify the domain to search and must satisfy
//
// 1) m_t0 != m_t1
// 2) f(m_t0) and f(m_t1) must have different signs
// or one must have absolute value <= m_f_tolerance
double m_t0, m_t1;
double m_f_tolerance; // (>= 0.0) If this value is > 0.0, then
// the search is terminated when a parameter
// "t" is found where |f(t)| <= m_f_tolerance.
double m_t_tolerance; // (>= 0.0) If this value is > 0.0, then
// the search is terminated when a parameter
// the root is bracketed in a domain with width
// <= m_t_tolerance.
// m_k[] is either nullptr or monotone increasing array of length m_k_count.
//
// This zero finder works on continuous piecewise c2 functions.
// If the function is c2 on the interior of the domain
//
// [min(t0,t1), max(m_t0,m_t1)]
//
// then there is no need to initialize m_k[]. If the function
// is not c2 on the domain in question, then the m_k[m_count] array
// is a list of parameters that define the c2 domains. When m_k[]
// is not nullptr, m_count must be >= 2 and m_k[] must be monotone
// increasing and satisfy
//
// m_k[0] <= min(m_t0,m_t1)
// and
// m_k[m_count-1] >= max(m_t0,m_t1).
//
// Duplicate values in m_k[] are permitted so that NURBS knot
// vector arrays may be used directly.
const double* m_k;
// length of m_k[] array ( 0 or >= 2 ).
int m_k_count;
private:
double m_s0, m_f0, m_s1, m_f1;
bool BracketZero(double,double,double,double,int=0);
bool BracketSpan(double,double,double,double);
bool NewtonRaphson( double, double, double, double, int, double* );
};
#endif
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,406 @@
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2013 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/
#if !defined(OPENNURBS_PHOTOGRAMMETRY_INC_)
#define OPENNURBS_PHOTOGRAMMETRY_INC_
class ON_CLASS ON_AerialPhotoImageFrustum
{
public:
ON_AerialPhotoImageFrustum();
bool IsSet() const;
bool HeightIsSet() const;
bool CornersAreSet() const;
bool UnitSystemIsSet() const;
void Unset();
// The frustum unit system must be set. It is common
// for the frustum unit system to be millimeters.
ON_UnitSystem m_unit_system;
// The frustum's apex height must be positive.
// It is common for the image frustum height
// to be a camera's focal length.
double m_height;
// The corners must be the vertices of a 3 or 4 sided
// convex region and must have counter-clockwise order
// in the 2d plane. It is common for the corners to be
// a rectangle (lower left, lower right, upper right,
// upper left) and for the rectangle to be symmetric
// about (0,0). However, when the image has been cropped,
// the frustum can be skew. The frustum's apex point is
// always directly above (0,0).
ON_2dPoint m_corners[4];
};
class ON_CLASS ON_AerialPhotoCameraPosition
{
public:
ON_AerialPhotoCameraPosition();
/*
Returns:
True if both the location and orientation are set.
*/
bool IsSet() const;
void Unset();
/////////////////////////////////////////////////////////
//
// Camera position unit system
//
bool UnitSystemIsSet() const;
bool SetUnitSystem( ON::LengthUnitSystem unit_system );
bool SetUnitSystem ( ON_UnitSystem unit_system );
ON_UnitSystem UnitSystem() const;
bool GetUnitSystem( ON_UnitSystem& unit_system ) const;
void UnsetUnitSystem();
/////////////////////////////////////////////////////////
//
// Location interface
//
bool LocationIsSet() const;
bool SetLocation(
ON_3dPoint camera_location
);
bool GetLocation(
ON_3dPoint& camera_location
) const;
ON_3dPoint Location() const;
void UnsetLocation();
/////////////////////////////////////////////////////////
//
// Orientation interface
//
bool OrientationIsSet() const;
bool GetOrientationAnglesDegrees(
double* omega_degrees,
double* phi_degrees,
double* kappa_degrees
) const;
bool GetOrientationAnglesRadians(
double* omega_radians,
double* phi_radians,
double* kappa_radians
) const;
/*
Description:
Get a right handed ortho normal camera frame.
Parameters:
camera_X - [out]
world coordinate unit vector pointing to the right in the camera image
camera_Y - [out]
world coordinate unit vector in the camera up direction.
camera_Z - [out]
world coordinate unit vector pointing into the cameara (from the
image toward the camera).
*/
bool GetOrientationFrame(
ON_3dVector& camera_X,
ON_3dVector& camera_Y,
ON_3dVector& camera_Z
) const;
bool GetOrientationUp(
ON_3dVector& camera_up
) const;
bool GetOrientationRight(
ON_3dVector& camera_right
) const;
bool GetOrientationDirection(
ON_3dVector& camera_direction
) const;
/*
Returns:
A rotation transformation "R" such that
camera right = R*ON_3dVector::XAxis
camera up = R*ON_3dVector::YAxis
camera direction = -R*ON_3dVector::ZAxis
*/
bool GetOrientationRotation(
ON_Xform& camera_rotaion
) const;
ON_Xform OrientationRotation() const;
/*
Description:
Set camera orientation information from rotation angles
in radians.
Remarks:
There are four ways to specify the camera's orientation.
1) Use SetOrientationAnglesRadians() to set
camera orientation information from rotation angles
in radians.
2) Use SetOrientationAnglesDegrees() to set
camera orientation information from rotation angles
in degrees.
3) Use SetOrientationVectors() to set
camera orientation information from vectors
that report the camera's up, right and direction.
3) Use SetOrientationRotation() to set
camera orientation information from a rotation
matrix.
Use the method for which you have the most accurate input
and the other values will be calculated as accurately as
possible.
*/
bool SetOrientationAnglesRadians(
double omega_radians,
double phi_radians,
double kappa_radians
);
/*
Description:
Set camera orientation information from rotation angles
in degrees.
Remarks:
There are four ways to specify the camera's orientation.
1) Use SetCameraOrientationAnglesRadians() to set
camera orientation information from rotation angles
in radians.
2) Use SetCameraOrientationAnglesDegrees() to set
camera orientation information from rotation angles
in degrees.
3) Use SetCameraOrientationVectors() to set
camera orientation information from vectors
that report the camera's up, right and direction.
3) Use SetCameraOrientationRotation() to set
camera orientation information from a rotation
matrix.
Use the method for which you have the most accurate input
and the other values will be calculated as accurately as
possible.
*/
bool SetOrientationAnglesDegrees(
double omega_degrees,
double phi_degrees,
double kappa_degrees
);
/*
Description:
Set camera orientation information from up, right
and direction vectors.
Remarks:
There are four ways to specify the camera's orientation.
1) Use SetCameraOrientationAnglesRadians() to set
camera orientation information from rotation angles
in radians.
2) Use SetCameraOrientationAnglesDegrees() to set
camera orientation information from rotation angles
in degrees.
3) Use SetCameraOrientationVectors() to set
camera orientation information from vectors
that report the camera's up, right and direction.
3) Use SetCameraOrientationRotation() to set
camera orientation information from a rotation
matrix.
Use the method for which you have the most accurate input
and the other values will be calculated as accurately as
possible.
*/
bool SetOrientationVectors(
ON_3dVector camera_up,
ON_3dVector camera_right,
ON_3dVector camera_direction
);
/*
Description:
Set camera orientation information from a rotation matrix.
Remarks:
There are four ways to specify the camera's orientation.
1) Use SetCameraOrientationAnglesRadians() to set
camera orientation information from rotation angles
in radians.
2) Use SetCameraOrientationAnglesDegrees() to set
camera orientation information from rotation angles
in degrees.
3) Use SetCameraOrientationVectors() to set
camera orientation information from vectors
that report the camera's up, right and direction.
3) Use SetCameraOrientationRotation() to set
camera orientation information from a rotation
matrix.
Use the method for which you have the most accurate input
and the other values will be calculated as accurately as
possible.
*/
bool SetOrientationRotation(
ON_Xform camera_rotation
);
void UnsetOrientation();
private:
unsigned char m_status;
unsigned char m_reserved1[3];
unsigned int m_reserved2;
ON_UnitSystem m_unit_system;
ON_3dPoint m_location;
ON_3dVector m_orientation_angles_degrees;
ON_3dVector m_orientation_angles_radians;
ON_3dVector m_orientation_direction;
ON_3dVector m_orientation_up;
ON_3dVector m_orientation_right;
ON_Xform m_orientation_rotation;
};
class ON_CLASS ON_AerialPhotoImage
{
public:
ON_AerialPhotoImage();
void Unset();
bool NameIsSet() const;
void SetName(
const wchar_t* name
);
void GetName(
ON_wString& name
) const;
void UnsetName();
void SetId( ON_UUID image_id );
ON_UUID Id() const;
/////////////////////////////////////////////////////////
//
// Camera position interface
//
bool CameraPositionIsSet() const;
bool CameraLocationIsSet() const;
bool CameraOrientationIsSet() const;
void SetCameraPosition(
ON_AerialPhotoCameraPosition camera_position
);
void GetCameraPosition(
ON_AerialPhotoCameraPosition& camera_position
) const;
void UnsetCameraPosition();
/////////////////////////////////////////////////////////
//
// Image frustum interface
//
bool ImageFrustumIsSet() const;
void SetImageFrustum(
ON_AerialPhotoImageFrustum image_frustum
);
void GetImageFrustum(
ON_AerialPhotoImageFrustum& image_frustum
) const;
void UnsetImageFrustum();
/////////////////////////////////////////////////////////
//
// Image frustum interface
//
bool ImageFileNameIsSet() const;
void SetImageFileName(
const wchar_t* image_file_name
);
void GetImageFileName(
ON_wString& image_file_name
) const;
void UnsetImageFileName();
bool ImageSizeIsSet() const;
bool SetImageSize(
int width_pixels,
int height_pixels
);
bool GetImageSize(
int* width_pixels,
int* height_pixels
) const;
void UnsetImageSize();
/////////////////////////////////////////////////////////
//
// General tools
//
bool GetViewProjection(
ON_BoundingBox target_bbox,
ON_Viewport& viewport
) const;
private:
ON_wString m_name;
ON_UUID m_id;
ON_AerialPhotoCameraPosition m_camera_position;
ON_AerialPhotoImageFrustum m_image_frustum;
ON_wString m_image_file_name;
int m_image_width_pixels;
int m_image_height_pixels;
};
#endif

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