mod container;
mod encode;
mod named;
mod oleps;
mod polyline;
mod raster;
mod raster_builtin;
mod raster_template;
mod seed_prepare;
mod strip;
mod tables;
mod text;
pub use seed_prepare::{DimensionPolicy, SeedPrepareOptions, V8Seed};
pub use strip::{StripSeedOptions, StripSeedReport, StrippedSeed, strip_seed_v8};
#[cfg(test)]
use crate::native::v8::RawElement;
use crate::{
le,
native::v8::{self, AuxRecord, ModelHeader, PageHeader, V8Model},
};
use cadkit_core::{
Attribute, Document, Entity, EntityKind, Error, GroupKind, LimitKind, Limits, Point3,
ReadOptions, Result, Value, Vec3,
};
use encode::*;
use flate2::{Compression, write::ZlibEncoder};
use std::{
collections::{BTreeMap, BTreeSet},
io::Write,
};
use tables::Tables;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(default)]
#[non_exhaustive]
pub struct WriteOptions {
pub limits: Limits,
pub codepage: Option<String>,
pub timestamp_ms: f64,
pub clear_seed_model: bool,
pub planarity_tolerance: f64,
pub preserve_seed_rasters: bool,
pub preserve_seed_controls: bool,
}
impl Default for WriteOptions {
fn default() -> Self {
Self {
limits: Limits::default(),
codepage: None,
timestamp_ms: 0.0,
clear_seed_model: false,
planarity_tolerance: 0.01,
preserve_seed_rasters: true,
preserve_seed_controls: true,
}
}
}
impl WriteOptions {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_limits(mut self, limits: Limits) -> Self {
self.limits = limits;
self
}
#[must_use]
pub fn with_codepage(mut self, codepage: Option<impl Into<String>>) -> Self {
self.codepage = codepage.map(Into::into);
self
}
#[must_use]
pub fn with_timestamp_ms(mut self, timestamp_ms: f64) -> Self {
self.timestamp_ms = timestamp_ms;
self
}
#[must_use]
pub fn with_clear_seed_model(mut self, clear: bool) -> Self {
self.clear_seed_model = clear;
self
}
#[must_use]
pub fn with_planarity_tolerance(mut self, tolerance: f64) -> Self {
self.planarity_tolerance = tolerance;
self
}
#[must_use]
pub fn with_preserve_seed_rasters(mut self, preserve: bool) -> Self {
self.preserve_seed_rasters = preserve;
self
}
#[must_use]
pub fn with_preserve_seed_controls(mut self, preserve: bool) -> Self {
self.preserve_seed_controls = preserve;
self
}
}
pub fn repack_v8(seed: &[u8], options: &ReadOptions) -> Result<Vec<u8>> {
let native = v8::read(seed, options)?;
if native.models.is_empty() {
return Err(Error::invalid(0, "DGN seed has no model"));
}
container::rewrite(seed, &BTreeMap::new(), options)
}
pub fn seed_has_raster_template(seed: &[u8], options: &ReadOptions) -> Result<bool> {
let native = v8::read(seed, options)?;
Ok(match native.models.as_slice() {
[model] => raster_template::Template::capture(model).is_some(),
_ => false,
})
}
fn graphic_page_version(model: &V8Model) -> u32 {
model
.graphic_pages
.first()
.map(|p| p.header.format_version)
.filter(|v| matches!(v, 2 | 3))
.unwrap_or(3)
}
fn compressed(bytes: &[u8]) -> Result<Vec<u8>> {
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
encoder.write_all(bytes)?;
Ok(encoder.finish()?)
}
fn page(records: &[Vec<u8>], version: u32, _number: u32) -> Result<Vec<u8>> {
let mut out = vec![0; 16];
u32_at(
&mut out,
0,
u32::try_from(records.len())
.map_err(|_| Error::limit(LimitKind::Capacity, "DGN page records".into()))?,
)?;
u32_at(&mut out, 4, version)?;
if records.is_empty() {
return Ok(out);
}
let mut data = vec![];
for b in records {
data.extend(0u32.to_le_bytes());
data.extend_from_slice(b);
}
out.extend(compressed(&data)?);
Ok(out)
}
fn validate_doc_and_options(doc: &Document, options: &WriteOptions) -> Result<()> {
cadkit_core::export::validate_limits(doc, &options.limits)?;
if doc
.units
.meters_per_unit
.is_some_and(|v| !v.is_finite() || v <= 0.0)
{
return Err(Error::invalid(0, "invalid source unit scale"));
}
if !options.timestamp_ms.is_finite() {
return Err(Error::invalid(0, "DGN timestamp must be finite"));
}
if !options.planarity_tolerance.is_finite() || options.planarity_tolerance <= 0.0 {
return Err(Error::invalid(
0,
"DGN planarity tolerance must be finite and positive",
));
}
if doc.models.len() != 1 {
return Err(Error::Unsupported(
"DGN writer requires exactly one source model".into(),
));
}
Ok(())
}
pub fn write_v8(doc: &Document, seed: &[u8], options: &WriteOptions) -> Result<Vec<u8>> {
validate_doc_and_options(doc, options)?;
let read = {
let mut new_options = ReadOptions::default()
.with_limits(options.limits)
.with_keep_raw(true);
new_options.fallback_codepage = options.codepage.clone();
new_options
};
let parsed_seed = V8Seed::parse(seed, &read)?;
write_v8_with_seed(doc, &parsed_seed, options)
}
pub fn write_v8_with_seed(
doc: &Document,
seed: &V8Seed,
options: &WriteOptions,
) -> Result<Vec<u8>> {
validate_doc_and_options(doc, options)?;
if seed.bytes.len() as u64 > options.limits.max_input_bytes {
return Err(Error::limit(
LimitKind::InputBytes,
"DGN seed input bytes".into(),
));
}
let read = {
let mut new_options = ReadOptions::default()
.with_limits(options.limits)
.with_keep_raw(true);
new_options.fallback_codepage = options.codepage.clone();
new_options
};
let native = &seed.native;
let model = seed.model()?;
let header = seed
.model_header()
.ok_or_else(|| Error::invalid(0, "missing seed model header"))?;
let source = doc
.models
.first()
.ok_or_else(|| Error::invalid(0, "missing source model"))?;
if source.kind != cadkit_core::ModelKind::Model {
return Err(Error::Unsupported(
"DGN writer accepts design models only".into(),
));
}
if source.is_3d != header.is_3d {
return Err(Error::invalid(0, "source and seed model dimensions differ"));
}
if let (Some(source), Some(target)) = (doc.units.meters_per_unit(), header.master.meters())
&& (!source.is_finite() || (source - target).abs() > target.abs() * 1e-12)
{
return Err(Error::invalid(
0,
"source and seed units differ; convert coordinates explicitly",
));
}
if seed.nonempty && !options.clear_seed_model {
return Err(Error::Unsupported(
"nonempty seed requires clear_seed_model=true".into(),
));
}
let max_id = seed.max_id;
let mut effective_options = options.clone();
if effective_options.timestamp_ms == 0.0 {
effective_options.timestamp_ms = seed.seed_timestamp_ms;
}
let options = &effective_options;
let rasters = raster::Preserved::prepare(doc, &seed.bytes, model, &read, options)?;
let mut tables = Tables::new(&native.named_pages, max_id, &read)?;
tables.observe_model_fonts(
model
.graphic_pages
.iter()
.chain(&model.control_pages)
.flat_map(|p| &p.elements),
&read,
);
let mut state = State {
tables,
model: header,
options,
wide_tags: wide_integer_tags(&source.entities),
layers: &doc.layers,
rasters: &rasters,
records: vec![],
tags: vec![],
new_controls: vec![],
new_xattributes: vec![],
work: 0,
vertices: 0,
bytes: rasters.bytes,
};
for layer in &doc.layers {
state
.tables
.level(Some(&layer.name), options.timestamp_ms)?;
}
for entity in &source.entities {
state.entity(entity, 0, false)?;
}
state.records.append(&mut state.tags);
let new_controls = std::mem::take(&mut state.new_controls);
let new_xattributes = std::mem::take(&mut state.new_xattributes);
let records = state.records;
let named = state.tables.finish(options.timestamp_ms)?;
let max_id = records
.iter()
.chain(named.iter().map(|r| &r.bytes))
.filter_map(|r| le::u64_at(r, 16))
.max()
.unwrap_or(max_id)
.max(max_id);
let mut replacements = BTreeMap::new();
for stream in &native.streams {
let model_stream = stream
.path
.starts_with(&format!("Dgn-Md/{}/Dgn^G/", model.storage))
|| stream
.path
.starts_with(&format!("Dgn-Md/{}/Dgn^C/", model.storage))
|| stream
.path
.starts_with(&format!("Dgn-Md/{}/Dgn^GA/", model.storage))
|| stream
.path
.starts_with(&format!("Dgn-Md/{}/Dgn^CA/", model.storage));
if model_stream {
replacements.insert(stream.path.clone(), None);
}
}
let version = graphic_page_version(model);
let record_pages = put_pages(
&mut replacements,
&format!("Dgn-Md/{}/Dgn^G", model.storage),
&records,
version,
options.limits.max_decompressed_bytes,
)?;
let control_pages = rasters.write_auxiliary(&mut replacements, &new_controls)?;
if let Some(template) = rasters
.template
.as_ref()
.filter(|_| !new_xattributes.is_empty())
{
let mut pages: BTreeMap<u32, Vec<AuxRecord>> = BTreeMap::new();
for (index, record) in new_xattributes {
let number = record_pages
.get(index)
.copied()
.ok_or_else(|| Error::invalid(0, "raster frame record outside the pages"))?;
pages.entry(number).or_default().push(record);
}
let mut last = 0;
for (number, records) in &pages {
let header = PageHeader {
record_count: 0,
format_version: template.aux_version,
page_number: 0,
population: 0,
};
replacements.insert(
format!("Dgn-Md/{}/Dgn^GA/${number}", model.storage),
Some(raster::aux_page(records, header)?),
);
last = *number;
}
replacements.insert(
format!("Dgn-Md/{}/Dgn^GA/^AH", model.storage),
Some(last.saturating_add(1).to_le_bytes().to_vec()),
);
}
if rasters.keep_control_counter {
replacements.remove(&format!("Dgn-Md/{}/Dgn^CA/^AH", model.storage));
}
named::write(
&mut replacements,
&native.named_pages,
&native.named_aux,
&named,
options.limits.max_decompressed_bytes,
)?;
let mut mh = header.raw.clone();
let mut low = [i64::MAX; 3];
let mut high = [i64::MIN; 3];
for b in &records {
let [record_low, record_high] = absolute_range(b)?;
for ((lo, hi), (record_lo, record_hi)) in low
.iter_mut()
.zip(high.iter_mut())
.zip(record_low.into_iter().zip(record_high))
{
*lo = (*lo).min(record_lo);
*hi = (*hi).max(record_hi);
}
}
if records.is_empty() {
low = [0; 3];
high = [0; 3];
}
for (i, n) in low.into_iter().chain(high).enumerate() {
put(&mut mh, 0x90 + i * 8, &n.to_le_bytes())?;
}
let mut full_header = seed.mh_prefix.clone();
if full_header.len() >= 4 {
let graphic_pages = if records.is_empty() {
0
} else {
record_pages.last().copied().unwrap_or(0)
};
u32_at(
&mut full_header,
0,
graphic_pages.saturating_add(control_pages),
)?;
}
full_header.extend(mh);
replacements.insert(seed.mh_path.clone(), Some(compressed(&full_header)?));
let mut data = seed.header_data.clone();
u64_at(&mut data, 0x128, max_id)?;
let mut h = seed.header_prefix.to_vec();
h.extend(compressed(&data)?);
replacements.insert("Dgn~H".into(), Some(h));
container::rewrite(&seed.bytes, &replacements, &read)
}
#[cfg(test)]
mod tests;
fn put_pages(
replacements: &mut BTreeMap<String, Option<Vec<u8>>>,
prefix: &str,
records: &[Vec<u8>],
version: u32,
max: u64,
) -> Result<Vec<u32>> {
let total = records
.iter()
.try_fold(0u64, |sum, r| sum.checked_add(r.len() as u64 + 4))
.ok_or_else(|| Error::limit(LimitKind::Output, "DGN output records".into()))?;
if total > max {
return Err(Error::limit(LimitKind::Output, "DGN output records".into()));
}
let mut first = 0;
let mut bytes = 0usize;
let mut number = 1u32;
let mut numbers = Vec::with_capacity(records.len());
for (i, r) in records.iter().enumerate() {
if bytes > 0 && bytes.saturating_add(r.len() + 4) > 256 * 1024 {
replacements.insert(
format!("{prefix}/${number}"),
Some(page(records.get(first..i).unwrap_or(&[]), version, number)?),
);
first = i;
bytes = 0;
number = number
.checked_add(1)
.ok_or_else(|| Error::limit(LimitKind::Capacity, "DGN page count".into()))?;
}
bytes = bytes.saturating_add(r.len() + 4);
numbers.push(number);
}
replacements.insert(
format!("{prefix}/${number}"),
Some(page(records.get(first..).unwrap_or(&[]), version, number)?),
);
Ok(numbers)
}
fn tag_key(a: &Attribute) -> (Option<String>, String) {
(a.set.clone(), a.tag.clone())
}
fn wide_integer_tags(entities: &[Entity]) -> BTreeSet<(Option<String>, String)> {
let mut wide = BTreeSet::new();
let mut todo: Vec<&Entity> = entities.iter().collect();
while let Some(e) = todo.pop() {
for a in &e.attributes {
if let Value::Int(n) = a.value
&& i32::try_from(n).is_err()
{
wide.insert(tag_key(a));
}
}
if let EntityKind::Group { children, .. } = &e.kind {
todo.extend(children);
}
}
wide
}
fn exact_f64(n: i64) -> Result<f64> {
const EXACT: u64 = 1 << f64::MANTISSA_DIGITS;
if n.unsigned_abs() > EXACT {
return Err(Error::invalid(
0,
"DGN integer tag exceeds the exact double range",
));
}
Ok(n as f64)
}
struct State<'a> {
tables: Tables,
model: &'a ModelHeader,
options: &'a WriteOptions,
wide_tags: BTreeSet<(Option<String>, String)>,
layers: &'a [cadkit_core::Layer],
rasters: &'a raster::Preserved,
records: Vec<Vec<u8>>,
tags: Vec<Vec<u8>>,
new_controls: Vec<Vec<u8>>,
new_xattributes: Vec<(usize, AuxRecord)>,
work: u64,
vertices: u64,
bytes: u64,
}
impl State<'_> {
#[allow(clippy::too_many_arguments)]
fn header(
&self,
kind: u32,
size: usize,
id: u64,
level: u32,
time: f64,
entity: &Entity,
three: bool,
) -> Result<Vec<u8>> {
let weight = self.lineweight(entity)?;
let mut b = encode::header(kind, size, id, level, time, entity, three, weight)?;
if !entity.props.contains_key("dgn.color_index") {
use cadkit_core::Color;
let layer = self
.layers
.iter()
.find(|l| Some(l.name.as_str()) == entity.layer.as_deref());
let layer_index = match layer.and_then(|l| l.props.get("dgn.color_index")) {
Some(Value::Int(n)) => u8::try_from(*n).ok(),
_ => None,
};
let color = match (entity.color, layer_index) {
(Color::ByLayer, Some(index)) => {
u32_at(&mut b, 0x34, u32::from(index))?;
Color::ByLayer
}
(Color::ByLayer, None) => layer.map_or(Color::ByLayer, |l| l.color),
(color, _) => color,
};
let rgb = match color {
Color::Aci { index } => {
let &(r, g, b) = cadkit_core::aci::TABLE
.get(usize::from(index))
.ok_or_else(|| Error::invalid(0, "ACI index"))?;
Some([r, g, b])
}
Color::Rgb { r, g, b } => Some([r, g, b]),
Color::ByLayer => None,
Color::ByBlock => {
return Err(Error::Unsupported(
"resolve ByBlock color before DGN export".into(),
));
}
};
if let Some(rgb) = rgb {
let index =
crate::palette::exact_index(&self.tables.palette, rgb).ok_or_else(|| {
Error::Unsupported(
"RGB color is absent from seed palette; provide dgn.color_index explicitly"
.into(),
)
})?;
u32_at(&mut b, 0x34, u32::from(index))?;
}
}
if entity.linetype.as_deref().is_some_and(|s| {
!s.eq_ignore_ascii_case("continuous") && !s.eq_ignore_ascii_case("bylayer")
}) && !entity.props.contains_key("dgn.style")
{
return Err(Error::Unsupported(
"custom linetype requires seed dgn.style index".into(),
));
}
Ok(b)
}
fn lineweight(&self, entity: &Entity) -> Result<u32> {
fn native(props: &cadkit_core::Props, element: bool) -> Result<Option<u32>> {
match props.get("dgn.weight") {
Some(Value::Int(n)) => {
let weight = u32::try_from(*n)
.map_err(|_| Error::invalid(0, "DGN weight must be a nonnegative index"))?;
if weight > 31 && !(element && weight == BY_LEVEL) {
return Err(Error::Unsupported("DGN lineweight indexes above 31".into()));
}
Ok(Some(weight))
}
Some(_) => Err(Error::invalid(0, "DGN weight must be an integer index")),
None => Ok(None),
}
}
if let Some(weight) = native(&entity.props, true)? {
return Ok(weight);
}
let weight = if entity.lineweight == cadkit_core::Lineweight::ByLayer {
match self
.layers
.iter()
.find(|layer| Some(layer.name.as_str()) == entity.layer.as_deref())
{
Some(layer) => {
if let Some(weight) = native(&layer.props, false)? {
return Ok(weight);
}
layer.lineweight
}
None => cadkit_core::Lineweight::Default,
}
} else {
entity.lineweight
};
match weight {
cadkit_core::Lineweight::Millimeters(_) => Err(Error::Unsupported(
"DGN lineweight needs an explicit entity/layer dgn.weight index; millimeter mapping is display-dependent".into(),
)),
cadkit_core::Lineweight::ByBlock => Err(Error::Unsupported(
"resolve ByBlock lineweight before DGN export".into(),
)),
cadkit_core::Lineweight::Default | cadkit_core::Lineweight::ByLayer => Ok(0),
}
}
fn add(&mut self, b: Vec<u8>, tag: bool) -> Result<()> {
self.bytes = self.bytes.saturating_add(b.len() as u64);
let new_rasters = self
.new_controls
.len()
.saturating_add(self.new_xattributes.len()) as u64;
if self.bytes > self.options.limits.max_decompressed_bytes
|| (self.records.len().saturating_add(self.tags.len()) as u64)
.saturating_add(self.rasters.objects)
.saturating_add(new_rasters)
>= self.options.limits.max_objects
{
return Err(Error::limit(
LimitKind::Objects,
"DGN output record budget".into(),
));
}
if tag {
self.tags.push(b);
} else {
self.records.push(b);
}
Ok(())
}
fn entity(&mut self, e: &Entity, depth: u32, component: bool) -> Result<()> {
if depth >= self.options.limits.max_depth || self.work >= self.options.limits.max_objects {
return Err(Error::limit(
LimitKind::Objects,
"DGN output depth/objects".into(),
));
}
self.work += 1;
let level = self
.tables
.level(e.layer.as_deref(), self.options.timestamp_ms)?;
if matches!(e.kind, EntityKind::Image { .. }) {
if e.id.is_none() {
return self.new_raster(e, level, component);
}
let (id, record) = self.rasters.frame(e, component)?;
self.add(record, false)?;
return self.attributes(e, id, level);
}
if matches!(&e.kind, EntityKind::Unknown { type_name } if type_name == "dgn.type_37") {
if e.attributes.len() != 1 {
return Err(Error::invalid(
0,
"standalone DGN tag requires exactly one attribute",
));
}
return self.write_attributes(e, None, level);
}
let id = self.tables.id()?;
let three = self.model.is_3d;
let psize = if three { 24 } else { 16 };
let flags = if component { 0x4000_0000 } else { 0 };
let mut links = vec![];
let mut b = match &e.kind {
EntityKind::Point { position } => {
let p = coordinate(*position, self.model)?;
let mut b = self.header(
3 | flags,
0x68 + psize * 2,
id,
level,
self.options.timestamp_ms,
e,
three,
)?;
point(&mut b, 0x68, p, three)?;
point(&mut b, 0x68 + psize, p, three)?;
range(&mut b, &[p, p])?;
b
}
EntityKind::Line { start, end } => {
let p = coordinate(*start, self.model)?;
let q = coordinate(*end, self.model)?;
let mut b = self.header(
3 | flags,
0x68 + psize * 2,
id,
level,
self.options.timestamp_ms,
e,
three,
)?;
point(&mut b, 0x68, p, three)?;
point(&mut b, 0x68 + psize, q, three)?;
range(&mut b, &[p, q])?;
b
}
EntityKind::Polyline {
vertices,
closed,
normal,
} => {
if vertices
.iter()
.any(|v| v.start_width != 0.0 || v.end_width != 0.0)
{
return Err(Error::Unsupported(
"DGN polyline widths require explicit conversion".into(),
));
}
if vertices.iter().any(|v| v.bulge != 0.0) {
let children = polyline::segments(e, vertices, *closed, *normal)?;
self.group(
e,
id,
level,
flags,
depth,
&children,
if *closed {
GroupKind::ComplexShape
} else {
GroupKind::ComplexChain
},
None,
)?;
self.attributes(e, id, level)?;
return Ok(());
}
self.points(
e,
id,
level,
flags,
&vertices.iter().map(|v| v.position).collect::<Vec<_>>(),
*closed,
)?
}
EntityKind::Face { points, .. } => self.points(e, id, level, flags, points, true)?,
EntityKind::Polygon {
exterior,
interiors,
} => {
cadkit_core::polygon::validate(
exterior,
interiors,
self.options.planarity_tolerance,
1e-6,
&mut 20_000_000,
)?;
if interiors.is_empty() {
self.points(e, id, level, flags, exterior, true)?
} else {
let mut children = vec![];
for (i, ring) in std::iter::once(exterior)
.chain(interiors.iter())
.enumerate()
{
let mut child = Entity::new(EntityKind::Point {
position: Point3::default(),
});
copy_symbology(e, &mut child);
child.kind = EntityKind::Polyline {
vertices: ring.iter().copied().map(cadkit_core::Vertex::at).collect(),
closed: true,
normal: Vec3::Z,
};
if i > 0 {
child.props.insert("dgn.hole".into(), Value::Bool(true));
}
children.push(child);
}
self.group(e, id, level, flags, depth, &children, GroupKind::Cell, None)?;
self.attributes(e, id, level)?;
return Ok(());
}
}
EntityKind::Group {
children,
group_kind,
name,
..
} => {
self.group(
e,
id,
level,
flags,
depth,
children,
*group_kind,
name.as_deref(),
)?;
self.attributes(e, id, level)?;
return Ok(());
}
EntityKind::Mesh { vertices, faces } => {
let mut children = vec![];
for face in faces {
let mut points = vec![];
for &i in face {
points.push(
*vertices.get(i as usize).ok_or_else(|| {
Error::invalid(0, "mesh index outside vertex array")
})?,
);
}
let mut child = Entity::new(EntityKind::Face {
points,
filled: true,
});
copy_symbology(e, &mut child);
children.push(child);
}
self.group(e, id, level, flags, depth, &children, GroupKind::Cell, None)?;
self.attributes(e, id, level)?;
return Ok(());
}
EntityKind::Circle {
center,
radius,
normal,
} => {
if normal.normalized().is_none() {
return Err(Error::invalid(0, "invalid normal"));
}
let (x, y, n) = cadkit_core::geom_ops::arbitrary_axes(*normal);
self.ellipse(
e, id, level, flags, *center, *radius, *radius, x, y, n, None,
)?
}
EntityKind::Arc {
center,
radius,
normal,
start_angle,
end_angle,
} => {
if normal.normalized().is_none() {
return Err(Error::invalid(0, "invalid normal"));
}
let (x, mut y, mut n) = cadkit_core::geom_ops::arbitrary_axes(*normal);
let mut start = *start_angle;
let mut sweep = cadkit_core::geom_ops::ccw_sweep(*start_angle, *end_angle);
if !three && n.z < -0.999999 {
y = y.scaled(-1.0);
n = n.scaled(-1.0);
start = -start;
sweep = -sweep;
}
self.ellipse(
e,
id,
level,
flags,
*center,
*radius,
*radius,
x,
y,
n,
Some((start, sweep)),
)?
}
EntityKind::Ellipse {
center,
major_axis,
ratio,
start_param,
end_param,
normal,
} => {
let n = normal
.normalized()
.ok_or_else(|| Error::invalid(0, "zero ellipse normal"))?;
let x = major_axis
.normalized()
.ok_or_else(|| Error::invalid(0, "zero ellipse axis"))?;
if n.dot(x).abs() > 1e-9 {
return Err(Error::invalid(0, "ellipse major axis is not in plane"));
}
let y = n.cross(x);
let a = major_axis.length();
let arc = ((*end_param - *start_param - std::f64::consts::TAU).abs() > 1e-12)
.then_some((*start_param, *end_param - *start_param));
self.ellipse(e, id, level, flags, *center, a, a * ratio, x, y, n, arc)?
}
EntityKind::Text {
position,
height,
rotation: angle,
width_factor,
oblique,
value,
style,
halign,
valign,
normal,
end_point,
} => {
if *oblique != 0.0 || end_point.is_some() {
return Err(Error::Unsupported(
"DGN text oblique and fit/aligned endpoints require explicit conversion"
.into(),
));
}
if !height.is_finite()
|| *height <= 0.0
|| !width_factor.is_finite()
|| *width_factor <= 0.0
|| normal.normalized().is_none()
{
return Err(Error::invalid(0, "invalid text dimensions or normal"));
}
let font = self.tables.font(e, style.as_deref())?;
let (justification, fx, fy) = text::justification(e, *halign, *valign)?;
let length = text::length(e, value, *height * *width_factor, fx)?;
let (x, y, n) = cadkit_core::geom_ops::arbitrary_axes(*normal);
let a = x.scaled(angle.cos()).plus(y.scaled(angle.sin()));
let c = x.scaled(-angle.sin()).plus(y.scaled(angle.cos()));
let shift = a.scaled(fx * length).plus(c.scaled(fy * *height));
let origin = coordinate(
Point3::new(
position.x - shift.x,
position.y - shift.y,
position.z - shift.z,
),
self.model,
)?;
let value = self.text(value, false)?;
let offset = if three { 0xca } else { 0xaa };
let mut b = self.header(
17 | flags,
offset + value.len(),
id,
level,
self.options.timestamp_ms,
e,
three,
)?;
u32_at(&mut b, 0x68, font)?;
put(&mut b, 0x6c, &justification.to_le_bytes())?;
put(
&mut b,
0x6e,
&u16::try_from(value.len())
.map_err(|_| Error::limit(LimitKind::Capacity, "DGN text length".into()))?
.to_le_bytes(),
)?;
f64_at(
&mut b,
0x70,
height * width_factor * self.model.uor_per_master / 0.006,
)?;
f64_at(&mut b, 0x78, height * self.model.uor_per_master / 0.006)?;
f64_at(&mut b, 0x80, length * self.model.uor_per_master)?;
f64_at(&mut b, 0x88, height * self.model.uor_per_master)?;
rotation(&mut b, 0x90, a, c, n, three)?;
point(&mut b, if three { 0xb0 } else { 0x98 }, origin, three)?;
put(&mut b, offset, &value)?;
text::range(
&mut b,
origin,
a,
c,
length * self.model.uor_per_master,
height * self.model.uor_per_master,
)?;
links.extend(self.codepage_link()?);
b
}
EntityKind::Spline {
degree,
knots,
control_points,
weights,
fit_points,
closed,
} => {
let sampled = if !control_points.is_empty() {
cadkit_core::geom_ops::nurbs_flatten(
*degree,
knots,
control_points,
weights,
16,
)
} else if !fit_points.is_empty() {
match cadkit_core::geom_ops::interpolate_fit_points(fit_points, *closed) {
Some((deg, k, ctrl)) => {
cadkit_core::geom_ops::nurbs_flatten(deg, &k, &ctrl, &[], 16)
}
None => fit_points.clone(),
}
} else {
return Err(Error::invalid(0, "empty spline cannot be written to DGN"));
};
if let [only] = sampled.as_slice() {
let p = coordinate(*only, self.model)?;
let mut b = self.header(
3 | flags,
0x68 + psize * 2,
id,
level,
self.options.timestamp_ms,
e,
three,
)?;
point(&mut b, 0x68, p, three)?;
point(&mut b, 0x68 + psize, p, three)?;
range(&mut b, &[p, p])?;
b
} else {
let close_shape = *closed && sampled.len() >= 3;
self.points(e, id, level, flags, &sampled, close_shape)?
}
}
other => {
return Err(Error::Unsupported(format!(
"DGN V8 writer: {} requires explicit conversion",
other.type_name()
)));
}
};
if matches!(e.props.get("dgn.hole"), Some(Value::Bool(true))) {
let props = le::u32_at(&b, 0x28).unwrap_or(0) | 0x8000;
u32_at(&mut b, 0x28, props)?;
}
self.add(finish(b, &links)?, false)?;
self.attributes(e, id, level)
}
fn new_raster(&mut self, e: &Entity, level: u32, component: bool) -> Result<()> {
if component {
return Err(Error::Unsupported(
"new DGN raster attachments cannot be complex group components".into(),
));
}
let template = self
.rasters
.template
.as_ref()
.ok_or_else(|| Error::invalid(0, "raster template missing for a new attachment"))?;
let mut ids = [0u64; 10];
for id in &mut ids {
*id = self.tables.id()?;
}
let group = template.instantiate(e, ids, level, self.model, self.options.timestamp_ms)?;
let extra = group
.controls
.iter()
.map(|c| c.len() as u64)
.sum::<u64>()
.saturating_add(group.xattribute.payload.len() as u64 + 28);
self.bytes = self.bytes.saturating_add(extra);
let index = self.records.len();
self.new_controls.extend(group.controls);
self.new_xattributes.push((index, group.xattribute));
self.add(group.frame, false)?;
self.attributes(e, group.frame_id, level)
}
fn points(
&mut self,
e: &Entity,
id: u64,
level: u32,
flags: u32,
points: &[Point3],
closed: bool,
) -> Result<Vec<u8>> {
if points.len() < if closed { 3 } else { 2 } {
return Err(Error::invalid(0, "too few DGN vertices"));
}
let count = points.len() + usize::from(closed && points.first() != points.last());
self.vertices = self.vertices.saturating_add(count as u64);
if count as u64 > u64::from(self.options.limits.max_vertices)
|| self.vertices > self.options.limits.max_total_vertices
{
return Err(Error::limit(
LimitKind::TotalVertices,
"DGN output vertices".into(),
));
}
let mut coordinates: Vec<_> = points
.iter()
.map(|p| coordinate(*p, self.model))
.collect::<Result<_>>()?;
if count > points.len()
&& let Some(first) = coordinates.first().copied()
{
coordinates.push(first);
}
let size = if self.model.is_3d { 24 } else { 16 };
let mut b = self.header(
if closed { 6 } else { 4 } | flags,
0x70 + count * size,
id,
level,
self.options.timestamp_ms,
e,
self.model.is_3d,
)?;
u32_at(&mut b, 0x68, count as u32)?;
for (i, p) in coordinates.iter().enumerate() {
point(&mut b, 0x70 + i * size, *p, self.model.is_3d)?;
}
range(&mut b, &coordinates)?;
Ok(b)
}
#[allow(clippy::too_many_arguments)]
fn ellipse(
&mut self,
e: &Entity,
id: u64,
level: u32,
flags: u32,
center: Point3,
a: f64,
b: f64,
x: Vec3,
y: Vec3,
n: Vec3,
arc: Option<(f64, f64)>,
) -> Result<Vec<u8>> {
if !(a > 0.0 && b > 0.0 && a.is_finite() && b.is_finite()) {
return Err(Error::invalid(0, "invalid DGN ellipse radii"));
}
let three = self.model.is_3d;
let p = coordinate(center, self.model)?;
let (axes, rot, origin, size) = if arc.is_some() {
(
0x78,
0x88,
if three { 0xa8 } else { 0x90 },
if three { 0xc0 } else { 0xa0 },
)
} else {
(
0x68,
0x78,
if three { 0x98 } else { 0x80 },
if three { 0xb0 } else { 0x90 },
)
};
let mut out = self.header(
if arc.is_some() { 16 } else { 15 } | flags,
size,
id,
level,
self.options.timestamp_ms,
e,
three,
)?;
if let Some((start, sweep)) = arc {
f64_at(&mut out, 0x68, start)?;
f64_at(&mut out, 0x70, sweep)?;
}
f64_at(&mut out, axes, a * self.model.uor_per_master)?;
f64_at(&mut out, axes + 8, b * self.model.uor_per_master)?;
rotation(&mut out, rot, x, y, n, three)?;
point(&mut out, origin, p, three)?;
let bounds = [
Point3::new(
center.x - (a * x.x).hypot(b * y.x),
center.y - (a * x.y).hypot(b * y.y),
center.z - (a * x.z).hypot(b * y.z),
),
Point3::new(
center.x + (a * x.x).hypot(b * y.x),
center.y + (a * x.y).hypot(b * y.y),
center.z + (a * x.z).hypot(b * y.z),
),
];
range(
&mut out,
&[
coordinate(bounds[0], self.model)?,
coordinate(bounds[1], self.model)?,
],
)?;
Ok(out)
}
#[allow(clippy::too_many_arguments)]
fn group(
&mut self,
e: &Entity,
id: u64,
level: u32,
flags: u32,
depth: u32,
children: &[Entity],
kind: GroupKind,
name: Option<&str>,
) -> Result<()> {
if children.len() as u64 > self.options.limits.max_objects {
return Err(Error::limit(
LimitKind::Objects,
"DGN group children".into(),
));
}
let cell = !matches!(kind, GroupKind::ComplexChain | GroupKind::ComplexShape);
let t = if cell {
2
} else if kind == GroupKind::ComplexShape {
14
} else {
12
};
let size = if cell {
if self.model.is_3d { 0x100 } else { 0xc0 }
} else {
0x70
};
let mut b = self.header(
t | flags | 0x2000_0000,
size,
id,
level,
self.options.timestamp_ms,
e,
self.model.is_3d,
)?;
u32_at(&mut b, 0x68, children.len() as u32)?;
if cell {
u32_at(&mut b, 0x6c, 1)?;
let off = if self.model.is_3d { 0xa0 } else { 0x90 };
let width = if self.model.is_3d { 3 } else { 2 };
for i in 0..width {
f64_at(&mut b, off + 8 * (i * width + i), 1.0)?;
}
}
let links = if let Some(name) = name {
string_link(1, name)?
} else {
vec![]
};
let index = self.records.len();
self.add(finish(b, &links)?, false)?;
let first = self.records.len();
for child in children {
self.entity(child, depth + 1, true)?;
}
let mut low = [i64::MAX; 3];
let mut high = [i64::MIN; 3];
for child in self.records.get(first..).unwrap_or(&[]) {
let [child_low, child_high] = absolute_range(child)?;
for axis in 0..3 {
if let (Some(lo), Some(hi), Some(cl), Some(ch)) = (
low.get_mut(axis),
high.get_mut(axis),
child_low.get(axis),
child_high.get(axis),
) {
*lo = (*lo).min(*cl);
*hi = (*hi).max(*ch);
}
}
}
if children.is_empty() || self.records.len() == first {
low = [0; 3];
high = [0; 3];
}
if let Some(parent) = self.records.get_mut(index) {
put_range(parent, low, high)?;
if cell {
point(parent, 0x70, low.map(|v| v as f64), self.model.is_3d)?;
point(
parent,
if self.model.is_3d { 0x88 } else { 0x80 },
high.map(|v| v as f64),
self.model.is_3d,
)?;
}
}
Ok(())
}
fn text(&self, value: &str, terminated: bool) -> Result<Vec<u8>> {
if value.len() as u64 > u64::from(self.options.limits.max_string_bytes)
|| value.contains('\0')
{
return Err(Error::limit(
LimitKind::StringBytes,
"DGN string bytes/NUL".into(),
));
}
if let Some(label) = &self.options.codepage {
let enc = encoding_rs::Encoding::for_label(label.as_bytes())
.ok_or_else(|| Error::Unsupported("unknown DGN codepage".into()))?;
let (bytes, _, errors) = enc.encode(value);
if errors {
return Err(Error::Unsupported(
"text cannot be represented in selected DGN codepage".into(),
));
}
let mut bytes = bytes.into_owned();
if terminated {
bytes.push(0);
}
Ok(bytes)
} else if terminated {
utf16(value)
} else {
utf16_unterminated(value)
}
}
fn codepage_link(&self) -> Result<Vec<u8>> {
let Some(label) = &self.options.codepage else {
return Ok(vec![]);
};
let number = label
.strip_prefix("windows-")
.and_then(|s| s.parse::<u32>().ok())
.filter(|n| (1250..=1258).contains(n))
.ok_or_else(|| {
Error::Unsupported("DGN writer codepage must be windows-1250..1258".into())
})?;
let mut b = vec![0; 16];
put(&mut b, 0, &[7, 0x10])?;
put(&mut b, 2, &0x80d4u16.to_le_bytes())?;
put(&mut b, 5, &[2])?;
u32_at(&mut b, 12, number)?;
Ok(b)
}
fn attributes(&mut self, e: &Entity, target: u64, level: u32) -> Result<()> {
self.write_attributes(e, Some(target), level)
}
fn write_attributes(&mut self, e: &Entity, target: Option<u64>, level: u32) -> Result<()> {
for a in &e.attributes {
let widened;
let a = match a.value {
Value::Int(n) if self.wide_tags.contains(&tag_key(a)) => {
widened = {
let mut attribute = a.clone();
attribute.value = Value::Float(exact_f64(n)?);
attribute
};
&widened
}
_ => a,
};
let (set, index, kind) = self.tables.tag(a)?;
let id = self.tables.id()?;
let value = match &a.value {
Value::Text(s) => self.text(s, true)?,
Value::Int(n) => i32::try_from(*n)
.map_err(|_| Error::invalid(0, "DGN integer tag exceeds i32"))?
.to_le_bytes()
.to_vec(),
Value::Float(n) if n.is_finite() => n.to_le_bytes().to_vec(),
_ => return Err(Error::Unsupported("DGN tag type".into())),
};
let level = match a.layer.as_deref() {
Some(name) => self.tables.level(Some(name), self.options.timestamp_ms)?,
None => level,
};
let symbology = attribute_symbology(e, a);
let mut b = self.header(
37,
0x14a + value.len(),
id,
level,
self.options.timestamp_ms,
&symbology,
self.model.is_3d,
)?;
let flags = le::u32_at(&b, 0x28).unwrap_or(0) | if a.invisible { 0x80 } else { 0 };
u32_at(&mut b, 0x28, flags)?;
put(&mut b, 0x98, &3u16.to_le_bytes())?;
put(
&mut b,
0x9a,
&(if a.invisible { 3u16 } else { 11u16 }).to_le_bytes(),
)?;
put(&mut b, 0xd0, &index.to_le_bytes())?;
put(&mut b, 0xd2, &kind.to_le_bytes())?;
u32_at(
&mut b,
0x138,
u32::try_from(value.len())
.map_err(|_| Error::limit(LimitKind::Capacity, "DGN tag value".into()))?,
)?;
put(&mut b, 0x140, &value)?;
match &a.display {
Some(display) => self.tag_display(&mut b, e, a, display)?,
None => {
let p = coordinate(a.position.unwrap_or(Point3::default()), self.model)?;
point(&mut b, 0xa0, p, true)?;
put_range(&mut b, [0; 3], [0; 3])?;
}
}
let mut links = dependency(0x2717, set)?;
if let Some(target) = target {
links.extend(tag_target_dependency(target)?);
}
self.add(finish_aligned(b, &links, 2)?, target.is_some())?;
}
Ok(())
}
fn tag_display(
&self,
b: &mut [u8],
owner: &Entity,
a: &Attribute,
display: &cadkit_core::AttributeDisplay,
) -> Result<()> {
let anchor = a
.position
.ok_or_else(|| Error::invalid(0, "displayed DGN tag needs a position"))?;
if !(display.height.is_finite()
&& display.height > 0.0
&& display.width.is_finite()
&& display.width > 0.0
&& display.rotation.is_finite())
{
return Err(Error::invalid(0, "invalid DGN tag text size or rotation"));
}
let uor = self.model.uor_per_master;
let p = coordinate(anchor, self.model)?;
let origin = coordinate(first_vertex(owner).unwrap_or(anchor), self.model)?;
point(b, 0xa0, origin, true)?;
point(
b,
0xb8,
[p[0] - origin[0], p[1] - origin[1], p[2] - origin[2]],
true,
)?;
if !a.invisible {
u32_at(b, 0xd4, 0x0200_0000)?;
}
f64_at(b, 0xf0, display.width * uor / 0.006)?;
f64_at(b, 0xf8, display.height * uor / 0.006)?;
let q = if !self.model.is_3d {
[display.rotation, 0.0, 0.0, 0.0]
} else if display.rotation == 0.0 {
[-1.0, 0.0, 0.0, 0.0]
} else {
let half = display.rotation / 2.0;
[half.cos(), 0.0, 0.0, (-half).sin()]
};
for (i, v) in q.into_iter().enumerate() {
f64_at(b, 0x100 + 8 * i, v)?;
}
u32_at(
b,
0x12c,
self.tables.tag_font(&a.props, display.style.as_deref())?,
)?;
let (code, fx, fy) = text::justification_code(&a.props, display.halign, display.valign)?;
u32_at(b, 0x130, u32::from(code))?;
if a.invisible {
return put_range(b, [0; 3], [0; 3]);
}
let length = match a.props.get("dgn.text_length") {
Some(Value::Float(v)) if v.is_finite() && *v > 0.0 => *v,
_ => display.width * value_chars(&a.value) as f64,
} * uor;
let height = display.height * uor;
let (sin, cos) = display.rotation.sin_cos();
let corners: Vec<[f64; 3]> = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)]
.into_iter()
.map(|(u, v)| {
let dx = (u - fx) * length;
let dy = (v * 2.0 - fy * 2.0) * height;
[p[0] + dx * cos - dy * sin, p[1] + dx * sin + dy * cos, p[2]]
})
.collect();
range(b, &corners)
}
}
fn copy_symbology(parent: &Entity, child: &mut Entity) {
child.layer = parent.layer.clone();
child.color = parent.color;
child.linetype = parent.linetype.clone();
child.lineweight = parent.lineweight;
child.visible = parent.visible;
for key in ["dgn.color_index", "dgn.style", "dgn.weight"] {
if let Some(value) = parent.props.get(key) {
child.props.insert(key.into(), value.clone());
}
}
}
fn first_vertex(e: &Entity) -> Option<Point3> {
match &e.kind {
EntityKind::Polyline { vertices, .. } => vertices.first().map(|v| v.position),
EntityKind::Polygon { exterior, .. } => exterior.first().copied(),
EntityKind::Face { points, .. } => points.first().copied(),
EntityKind::Line { start, .. } => Some(*start),
EntityKind::Point { position } | EntityKind::Text { position, .. } => Some(*position),
EntityKind::Circle { center, .. }
| EntityKind::Arc { center, .. }
| EntityKind::Ellipse { center, .. } => Some(*center),
EntityKind::Spline {
control_points,
fit_points,
..
} => control_points
.first()
.or_else(|| fit_points.first())
.copied(),
_ => None,
}
}
fn value_chars(v: &Value) -> usize {
match v {
Value::Text(s) => s.chars().count(),
Value::Int(n) => n.to_string().len(),
Value::Float(f) => format!("{f}").len(),
_ => 0,
}
.max(1)
}
fn attribute_symbology(owner: &Entity, a: &Attribute) -> Entity {
let mut s = Entity::new(EntityKind::Point {
position: Point3::default(),
});
s.layer = a.layer.clone().or_else(|| owner.layer.clone());
s.color = a.color.unwrap_or(owner.color);
s.linetype = owner.linetype.clone();
s.lineweight = a.lineweight.unwrap_or(owner.lineweight);
s.visible = true;
for (key, typed) in [
("dgn.color_index", a.color.is_some()),
("dgn.weight", a.lineweight.is_some()),
("dgn.style", false),
] {
let inherited = if typed { None } else { owner.props.get(key) };
if let Some(v) = a.props.get(key).or(inherited) {
s.props.insert(key.into(), v.clone());
}
}
for key in ["dgn.graphic_group", "dgn.properties", "dgn.type_flags"] {
if let Some(v) = a.props.get(key) {
s.props.insert(key.into(), v.clone());
}
}
s
}