or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

data-access.mdfile-operations.mdindex.mdmesh-analysis.mdmesh-processing.mdtransformations.md

index.mddocs/

0

# NumPy STL

1

2

A high-performance Python library for reading, writing, and manipulating STL (STereoLithography) files. NumPy STL leverages NumPy for fast operations on 3D mesh data, enabling efficient processing of both binary and ASCII STL file formats with comprehensive mesh manipulation capabilities.

3

4

## Package Information

5

6

- **Package Name**: numpy-stl

7

- **Language**: Python

8

- **Installation**: `pip install numpy-stl`

9

- **Dependencies**: `numpy`, `python-utils>=3.4.5`

10

11

## Core Imports

12

13

```python

14

from stl import mesh

15

```

16

17

Access to enums and constants:

18

19

```python

20

from stl import Mesh, Mode, Dimension, RemoveDuplicates

21

```

22

23

## Basic Usage

24

25

```python

26

import numpy as np

27

from stl import mesh

28

29

# Load an existing STL file

30

your_mesh = mesh.Mesh.from_file('model.stl')

31

32

# Create a new mesh from scratch

33

TRIANGLE_COUNT = 100

34

data = np.zeros(TRIANGLE_COUNT, dtype=mesh.Mesh.dtype)

35

your_mesh = mesh.Mesh(data, remove_empty_areas=False)

36

37

# Access mesh properties

38

print(f"Triangle count: {len(your_mesh)}")

39

print(f"Volume: {your_mesh.get_mass_properties()[0]}")

40

41

# Access mesh data

42

normals = your_mesh.normals # Triangle normal vectors (Nx3)

43

vertices = your_mesh.vectors # Triangle vertices (Nx3x3)

44

v0, v1, v2 = your_mesh.v0, your_mesh.v1, your_mesh.v2 # Individual vertex arrays

45

46

# Transform the mesh

47

your_mesh.translate([1.0, 2.0, 3.0]) # Move by offset

48

your_mesh.rotate([0, 0, 1], np.pi/4) # Rotate 45° around Z-axis

49

50

# Save the mesh

51

your_mesh.save('output.stl')

52

```

53

54

## Architecture

55

56

NumPy STL is built around NumPy structured arrays for efficient mesh data storage and manipulation:

57

58

- **Mesh**: Primary interface inheriting from BaseStl for file I/O operations

59

- **BaseMesh**: Core mesh data structure and geometric operations

60

- **BaseStl**: STL file format reading/writing with automatic format detection

61

- **Structured Data Type**: NumPy dtype with normals, vectors, and attributes for efficient memory layout

62

63

The library supports both Cython extensions for performance-critical operations and pure Python fallbacks, with automatic format detection for STL files and comprehensive geometric calculations including volume, center of gravity, and inertia tensors.

64

65

## Capabilities

66

67

### File Operations

68

69

Load, save, and convert STL files with support for both ASCII and binary formats, automatic format detection, and multi-file operations.

70

71

```python { .api }

72

def Mesh.from_file(filename, calculate_normals=True, fh=None, mode=Mode.AUTOMATIC, speedups=True, **kwargs): ...

73

def save(self, filename, fh=None, mode=Mode.AUTOMATIC, update_normals=True): ...

74

def Mesh.from_multi_file(filename, calculate_normals=True, fh=None, mode=Mode.AUTOMATIC, speedups=True, **kwargs): ...

75

def Mesh.from_files(filenames, calculate_normals=True, mode=Mode.AUTOMATIC, speedups=True, **kwargs): ...

76

def Mesh.from_3mf_file(filename, calculate_normals=True, **kwargs): ...

77

```

78

79

[File Operations](./file-operations.md)

80

81

### Mesh Properties and Analysis

82

83

Calculate geometric properties including volume, surface area, center of gravity, inertia tensors, and mesh validation.

84

85

```python { .api }

86

def get_mass_properties(self): ...

87

def get_mass_properties_with_density(self, density): ...

88

def update_areas(self, normals=None): ...

89

def update_centroids(self): ...

90

def is_closed(self, exact=False): ...

91

def check(self, exact=False): ...

92

```

93

94

[Mesh Analysis](./mesh-analysis.md)

95

96

### Geometric Transformations

97

98

Transform meshes through rotation, translation, and general 4x4 transformation matrices with support for rotation around arbitrary axes and points.

99

100

```python { .api }

101

def rotate(self, axis, theta=0, point=None): ...

102

def rotate_using_matrix(self, rotation_matrix, point=None): ...

103

def translate(self, translation): ...

104

def transform(self, matrix): ...

105

def rotation_matrix(cls, axis, theta): ...

106

```

107

108

[Transformations](./transformations.md)

109

110

### Mesh Data Access

111

112

Access and modify mesh data through convenient properties and array interfaces with support for both vertex-based and coordinate-based operations.

113

114

```python { .api }

115

@property

116

def vectors(self): ...

117

@property

118

def normals(self): ...

119

@property

120

def v0(self): ...

121

@property

122

def v1(self): ...

123

@property

124

def v2(self): ...

125

@property

126

def x(self): ...

127

@property

128

def y(self): ...

129

@property

130

def z(self): ...

131

```

132

133

[Data Access](./data-access.md)

134

135

### Mesh Processing

136

137

Clean and process mesh data including duplicate removal, empty area elimination, and normal vector calculations.

138

139

```python { .api }

140

def update_normals(self, update_areas=True, update_centroids=True): ...

141

def get_unit_normals(self): ...

142

def remove_duplicate_polygons(cls, data, value=RemoveDuplicates.SINGLE): ...

143

def remove_empty_areas(cls, data): ...

144

```

145

146

[Mesh Processing](./mesh-processing.md)

147

148

## Types

149

150

```python { .api }

151

class Mesh(BaseStl):

152

"""

153

Primary mesh class for STL file manipulation.

154

155

Attributes:

156

data: numpy.array - Structured array containing mesh data

157

name: str - Mesh name

158

speedups: bool - Whether to use Cython optimizations

159

"""

160

161

class Mode(enum.IntEnum):

162

"""STL file read/write modes."""

163

AUTOMATIC = 0 # Auto-detect based on TTY

164

ASCII = 1 # Force ASCII format

165

BINARY = 2 # Force binary format

166

167

class Dimension(enum.IntEnum):

168

"""Axis indices for vector access."""

169

X = 0 # X-axis index

170

Y = 1 # Y-axis index

171

Z = 2 # Z-axis index

172

173

class RemoveDuplicates(enum.Enum):

174

"""Duplicate triangle handling options."""

175

NONE = 0 # Keep all duplicates

176

SINGLE = 1 # Keep only one copy

177

ALL = 2 # Remove all including originals

178

179

# NumPy data type for mesh storage

180

dtype = np.dtype([

181

('normals', np.float32, (3,)), # Triangle normal vectors

182

('vectors', np.float32, (3, 3)), # Triangle vertices

183

('attr', np.uint16, (1,)), # Triangle attributes

184

])

185

```

186

187

## Constants

188

189

```python { .api }

190

BUFFER_SIZE: int = 4096 # Buffer size for file reading

191

HEADER_SIZE: int = 80 # STL header field size in bytes

192

COUNT_SIZE: int = 4 # Triangle count field size in bytes

193

MAX_COUNT: float = 1e8 # Maximum number of triangles

194

HEADER_FORMAT: str = '{package_name} ({version}) {now} {name}' # STL header format template

195

196

# Backward compatibility constants

197

AUTOMATIC: int = 0 # Alias for Mode.AUTOMATIC

198

ASCII: int = 1 # Alias for Mode.ASCII

199

BINARY: int = 2 # Alias for Mode.BINARY

200

X: int = 0 # Alias for Dimension.X

201

Y: int = 1 # Alias for Dimension.Y

202

Z: int = 2 # Alias for Dimension.Z

203

```

204

205

## Command Line Tools

206

207

NumPy STL provides console commands for STL file format conversion:

208

209

- **stl**: Convert between ASCII and binary STL formats with automatic detection

210

- **stl2ascii**: Convert STL files to ASCII (text) format

211

- **stl2bin**: Convert STL files to binary format

212

213

```bash

214

# Convert STL files (auto-detects format)

215

stl input.stl output.stl

216

217

# Force ASCII output

218

stl2ascii binary_model.stl ascii_model.stl

219

220

# Force binary output

221

stl2bin ascii_model.stl binary_model.stl

222

223

# Common options for all commands

224

stl --help # Show help

225

stl input.stl output.stl --name "MyMesh" # Set mesh name

226

stl input.stl output.stl -r # Remove empty areas

227

stl input.stl output.stl -s # Disable speedups

228

```