or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

addons.mdcolors.mddocument-operations.mdentities.mdindex.mdlayouts.mdmath.mdpath-processing.mdrendering.mdtools.md

math.mddocs/

0

# Math

1

2

Comprehensive mathematical utilities for 2D/3D geometry, transformations, curve calculations, and geometric constructions. The math package provides the mathematical foundation for all geometric operations in ezdxf.

3

4

## Capabilities

5

6

### Vector Mathematics

7

8

2D and 3D vector classes with full arithmetic operations, geometric calculations, and utility functions.

9

10

```python { .api }

11

class Vec2:

12

"""2D vector class"""

13

14

def __init__(self, x: float = 0, y: float = 0): ...

15

16

@property

17

def x(self) -> float: ...

18

@property

19

def y(self) -> float: ...

20

21

def __add__(self, other: 'Vec2') -> 'Vec2': ...

22

def __sub__(self, other: 'Vec2') -> 'Vec2': ...

23

def __mul__(self, scalar: float) -> 'Vec2': ...

24

def __truediv__(self, scalar: float) -> 'Vec2': ...

25

26

def dot(self, other: 'Vec2') -> float: ...

27

def cross(self, other: 'Vec2') -> float: ...

28

def magnitude(self) -> float: ...

29

def normalize(self) -> 'Vec2': ...

30

def angle(self) -> float: ...

31

def rotate(self, angle: float) -> 'Vec2': ...

32

33

class Vec3:

34

"""3D vector class"""

35

36

def __init__(self, x: float = 0, y: float = 0, z: float = 0): ...

37

38

@property

39

def x(self) -> float: ...

40

@property

41

def y(self) -> float: ...

42

@property

43

def z(self) -> float: ...

44

@property

45

def xy(self) -> Vec2: ...

46

47

def __add__(self, other: 'Vec3') -> 'Vec3': ...

48

def __sub__(self, other: 'Vec3') -> 'Vec3': ...

49

def __mul__(self, scalar: float) -> 'Vec3': ...

50

def __truediv__(self, scalar: float) -> 'Vec3': ...

51

52

def dot(self, other: 'Vec3') -> float: ...

53

def cross(self, other: 'Vec3') -> 'Vec3': ...

54

def magnitude(self) -> float: ...

55

def normalize(self) -> 'Vec3': ...

56

def distance(self, other: 'Vec3') -> float: ...

57

def angle_between(self, other: 'Vec3') -> float: ...

58

def project(self, other: 'Vec3') -> 'Vec3': ...

59

def rotate_axis(self, axis: 'Vec3', angle: float) -> 'Vec3': ...

60

```

61

62

Usage examples:

63

```python

64

from ezdxf.math import Vec2, Vec3

65

66

# 2D vector operations

67

v1 = Vec2(3, 4)

68

v2 = Vec2(1, 2)

69

v3 = v1 + v2 # Vec2(4, 6)

70

length = v1.magnitude() # 5.0

71

unit_v1 = v1.normalize() # Vec2(0.6, 0.8)

72

73

# 3D vector operations

74

a = Vec3(1, 0, 0)

75

b = Vec3(0, 1, 0)

76

c = a.cross(b) # Vec3(0, 0, 1) - Z axis

77

dot_product = a.dot(b) # 0.0

78

distance = a.distance(b) # ~1.414

79

```

80

81

### Matrix Transformations

82

83

4x4 transformation matrices for 3D geometric operations including translation, rotation, scaling, and projection.

84

85

```python { .api }

86

class Matrix44:

87

"""4x4 transformation matrix"""

88

89

def __init__(self, values = None): ...

90

91

@classmethod

92

def identity(cls) -> 'Matrix44':

93

"""Create identity matrix"""

94

95

@classmethod

96

def translate(cls, dx: float, dy: float, dz: float) -> 'Matrix44':

97

"""Create translation matrix"""

98

99

@classmethod

100

def scale(cls, sx: float, sy: float = None, sz: float = None) -> 'Matrix44':

101

"""Create scaling matrix"""

102

103

@classmethod

104

def x_rotate(cls, angle: float) -> 'Matrix44':

105

"""Create X-axis rotation matrix (angle in radians)"""

106

107

@classmethod

108

def y_rotate(cls, angle: float) -> 'Matrix44':

109

"""Create Y-axis rotation matrix (angle in radians)"""

110

111

@classmethod

112

def z_rotate(cls, angle: float) -> 'Matrix44':

113

"""Create Z-axis rotation matrix (angle in radians)"""

114

115

@classmethod

116

def axis_rotate(cls, axis: Vec3, angle: float) -> 'Matrix44':

117

"""Create rotation matrix around arbitrary axis"""

118

119

def __mul__(self, other) -> 'Matrix44':

120

"""Matrix multiplication"""

121

122

def transform(self, vector: Vec3) -> Vec3:

123

"""Transform vector by matrix"""

124

125

def transform_vertices(self, vertices) -> List[Vec3]:

126

"""Transform multiple vertices"""

127

128

def inverse(self) -> 'Matrix44':

129

"""Calculate matrix inverse"""

130

131

def transpose(self) -> 'Matrix44':

132

"""Calculate matrix transpose"""

133

```

134

135

Usage examples:

136

```python

137

from ezdxf.math import Matrix44, Vec3

138

import math

139

140

# Create transformation matrices

141

translate = Matrix44.translate(10, 20, 5)

142

scale = Matrix44.scale(2, 2, 1) # Scale by 2 in X and Y

143

rotate = Matrix44.z_rotate(math.radians(45)) # Rotate 45° around Z

144

145

# Combine transformations

146

combined = translate @ rotate @ scale # Matrix multiplication

147

148

# Transform points

149

point = Vec3(1, 1, 0)

150

transformed = combined.transform(point)

151

152

# Transform multiple points

153

points = [Vec3(0, 0, 0), Vec3(1, 0, 0), Vec3(1, 1, 0)]

154

transformed_points = combined.transform_vertices(points)

155

```

156

157

### Curve Mathematics

158

159

Advanced curve mathematics including Bézier curves, B-splines, and specialized curve types.

160

161

```python { .api }

162

class Bezier:

163

"""General Bézier curve class"""

164

165

def __init__(self, control_points): ...

166

167

@property

168

def control_points(self) -> List[Vec3]:

169

"""Control points defining the curve"""

170

171

def point(self, t: float) -> Vec3:

172

"""Evaluate curve at parameter t (0-1)"""

173

174

def tangent(self, t: float) -> Vec3:

175

"""Tangent vector at parameter t"""

176

177

def approximate(self, segments: int) -> List[Vec3]:

178

"""Approximate curve with line segments"""

179

180

class Bezier3P:

181

"""3-point Bézier curve (quadratic)"""

182

183

def __init__(self, start: Vec3, control: Vec3, end: Vec3): ...

184

185

class Bezier4P:

186

"""4-point Bézier curve (cubic)"""

187

188

def __init__(self, start: Vec3, ctrl1: Vec3, ctrl2: Vec3, end: Vec3): ...

189

190

class BSpline:

191

"""B-spline curve representation"""

192

193

def __init__(self, control_points, order: int = 4, knots = None, weights = None): ...

194

195

@property

196

def control_points(self) -> List[Vec3]:

197

"""Control points"""

198

199

@property

200

def order(self) -> int:

201

"""Curve order (degree + 1)"""

202

203

@property

204

def knots(self) -> List[float]:

205

"""Knot vector"""

206

207

@property

208

def weights(self) -> List[float]:

209

"""Control point weights (for NURBS)"""

210

211

def point(self, t: float) -> Vec3:

212

"""Evaluate curve at parameter t"""

213

214

def insert_knot(self, u: float) -> 'BSpline':

215

"""Insert knot at parameter u"""

216

217

def approximate(self, segments: int) -> List[Vec3]:

218

"""Approximate curve with line segments"""

219

220

class EulerSpiral:

221

"""Euler spiral (clothoid) curve"""

222

223

def __init__(self, radius: float = 1000, curvature: float = 1, length: float = 100): ...

224

225

def point(self, t: float) -> Vec3:

226

"""Point at parameter t along the spiral"""

227

228

def approximate(self, segments: int) -> List[Vec3]:

229

"""Approximate spiral with line segments"""

230

```

231

232

### Geometric Construction

233

234

2D and 3D geometric construction utilities for lines, circles, ellipses, and other geometric primitives.

235

236

```python { .api }

237

class ConstructionLine:

238

"""2D construction line utilities"""

239

240

def __init__(self, start: Vec2, end: Vec2): ...

241

242

@classmethod

243

def from_angle(cls, start: Vec2, angle: float, length: float = 1): ...

244

245

def intersect(self, other: 'ConstructionLine') -> Vec2:

246

"""Find intersection point with another line"""

247

248

def distance_to_point(self, point: Vec2) -> float:

249

"""Distance from point to line"""

250

251

def is_parallel(self, other: 'ConstructionLine') -> bool:

252

"""Check if lines are parallel"""

253

254

class ConstructionRay:

255

"""2D construction ray (semi-infinite line)"""

256

257

def __init__(self, start: Vec2, direction: Vec2): ...

258

259

class ConstructionBox:

260

"""2D rectangle construction utilities"""

261

262

def __init__(self, center: Vec2, width: float, height: float, angle: float = 0): ...

263

264

@property

265

def corners(self) -> List[Vec2]:

266

"""Rectangle corner points"""

267

268

def contains_point(self, point: Vec2) -> bool:

269

"""Check if point is inside rectangle"""

270

271

class ConstructionEllipse:

272

"""3D ellipse construction and manipulation"""

273

274

def __init__(self, center: Vec3, major_axis: Vec3, minor_axis: Vec3,

275

start_param: float = 0, end_param: float = 2*pi): ...

276

277

@property

278

def center(self) -> Vec3: ...

279

@property

280

def major_axis(self) -> Vec3: ...

281

@property

282

def minor_axis(self) -> Vec3: ...

283

284

def point(self, param: float) -> Vec3:

285

"""Point at parameter value"""

286

287

def tangent(self, param: float) -> Vec3:

288

"""Tangent vector at parameter"""

289

290

def approximate(self, segments: int) -> List[Vec3]:

291

"""Approximate ellipse with line segments"""

292

```

293

294

### Geometric Utility Functions

295

296

Collection of utility functions for common geometric calculations and operations.

297

298

```python { .api }

299

def distance(p1, p2) -> float:

300

"""Calculate distance between two points"""

301

302

def lerp(p1, p2, factor: float):

303

"""Linear interpolation between points"""

304

305

def has_clockwise_orientation(vertices) -> bool:

306

"""Check if 2D vertices have clockwise orientation"""

307

308

def is_point_in_polygon_2d(point, polygon) -> bool:

309

"""Test if point is inside 2D polygon"""

310

311

def intersection_line_line_2d(line1, line2):

312

"""Calculate 2D line-line intersection"""

313

314

def intersection_ray_ray_3d(ray1, ray2):

315

"""Calculate 3D ray-ray intersection"""

316

317

def world_mercator_to_gps(x: float, y: float) -> tuple:

318

"""Convert Web Mercator coordinates to GPS (lat, lon)"""

319

320

def gps_to_world_mercator(lat: float, lon: float) -> tuple:

321

"""Convert GPS coordinates to Web Mercator (x, y)"""

322

323

def close_vectors(a, b, abs_tol: float = 1e-12) -> bool:

324

"""Compare vector sequences for equality within tolerance"""

325

```

326

327

### B-Spline Functions

328

329

Specialized functions for B-spline curve fitting, interpolation, and conversion.

330

331

```python { .api }

332

def fit_points_to_cad_cv(points, *, method: str = 'chord', tangents = None) -> BSpline:

333

"""

334

Fit points to B-spline control vertices.

335

336

Parameters:

337

- points: data points to fit

338

- method: parameterization method ('chord', 'centripetal', 'uniform')

339

- tangents: optional start/end tangent vectors

340

341

Returns:

342

BSpline: Fitted B-spline curve

343

"""

344

345

def global_bspline_interpolation(points, *, degree: int = 3, method: str = 'chord',

346

tangents = None) -> BSpline:

347

"""

348

Global B-spline interpolation through points.

349

350

Parameters:

351

- points: points to interpolate

352

- degree: spline degree (1-3)

353

- method: parameterization method

354

- tangents: optional tangent constraints

355

356

Returns:

357

BSpline: Interpolating B-spline

358

"""

359

360

def local_cubic_bspline_interpolation(points, *, method: str = 'chord',

361

tangents = None) -> BSpline:

362

"""Local cubic B-spline interpolation"""

363

364

def rational_bspline_from_arc(arc, *, segments: int = 1) -> BSpline:

365

"""Create rational B-spline from circular arc"""

366

367

def rational_bspline_from_ellipse(ellipse, *, segments: int = 1) -> BSpline:

368

"""Create rational B-spline from ellipse"""

369

```

370

371

### Specialized Mathematics

372

373

Advanced mathematical utilities for specific applications and specialized calculations.

374

375

```python { .api }

376

class BarycentricCoordinates:

377

"""Barycentric coordinate system for triangular interpolation"""

378

379

def __init__(self, triangle): ...

380

381

def from_cartesian(self, point) -> tuple:

382

"""Convert Cartesian coordinates to barycentric"""

383

384

def to_cartesian(self, u: float, v: float, w: float):

385

"""Convert barycentric coordinates to Cartesian"""

386

387

class Plane:

388

"""3D plane representation and operations"""

389

390

def __init__(self, normal: Vec3, distance: float): ...

391

392

@classmethod

393

def from_3_points(cls, p1: Vec3, p2: Vec3, p3: Vec3) -> 'Plane': ...

394

395

def distance_to_point(self, point: Vec3) -> float:

396

"""Signed distance from point to plane"""

397

398

def intersect_line(self, start: Vec3, end: Vec3) -> Vec3:

399

"""Find line-plane intersection"""

400

401

def mapbox_earcut_2d(exterior, holes = None) -> List[int]:

402

"""

403

2D polygon triangulation using earcut algorithm.

404

405

Parameters:

406

- exterior: exterior polygon vertices

407

- holes: list of hole polygon vertices

408

409

Returns:

410

List[int]: Triangle indices (3 indices per triangle)

411

"""

412

413

def mapbox_earcut_3d(points, holes = None) -> List[int]:

414

"""3D polygon triangulation projected to best-fit plane"""

415

```

416

417

## Types

418

419

```python { .api }

420

# Type aliases for flexibility

421

AnyVec = Union[Vec2, Vec3, Sequence[float]]

422

UVec = Union[Vec2, Vec3, Vertex]

423

424

# Constants

425

X_AXIS: Vec3 # (1, 0, 0)

426

Y_AXIS: Vec3 # (0, 1, 0)

427

Z_AXIS: Vec3 # (0, 0, 1)

428

NULLVEC: Vec3 # (0, 0, 0)

429

430

# Geometric primitives

431

Vertex = Tuple[float, float, float]

432

```

433

434

Usage examples:

435

```python

436

from ezdxf.math import *

437

import math

438

439

# Vector operations

440

v1 = Vec3(1, 2, 3)

441

v2 = Vec3(4, 5, 6)

442

v3 = v1 + v2 # Vec3(5, 7, 9)

443

v4 = v1.cross(v2) # Cross product

444

445

# Matrix transformations

446

m1 = Matrix44.translate(10, 20, 0)

447

m2 = Matrix44.z_rotate(math.radians(45))

448

combined = m1 @ m2 # Translate then rotate

449

450

# Curve operations

451

points = [Vec3(0, 0, 0), Vec3(1, 1, 0), Vec3(2, 0, 0), Vec3(3, 1, 0)]

452

spline = global_bspline_interpolation(points, degree=3)

453

curve_points = spline.approximate(20) # 20 line segments

454

455

# Geometric utilities

456

poly = [Vec2(0, 0), Vec2(4, 0), Vec2(4, 3), Vec2(0, 3)]

457

test_point = Vec2(2, 1.5)

458

inside = is_point_in_polygon_2d(test_point, poly) # True

459

```