tweak the fit of the parts

This commit is contained in:
Nick Estes
2026-08-04 12:27:31 -07:00
parent 45a77885f9
commit 69d9b956e6
41 changed files with 5378 additions and 324 deletions
+25
View File
@@ -0,0 +1,25 @@
# Attitude w/battery
Generated by the Feather Case Wizard.
- Top profile: `generic`
- FeatherWings: 1
- Battery compartment: yes
- 1/4-20 insert: yes
- Approximate exterior: 88.6 × 59.1 × 33.2 mm
- Formats: 3mf
- Parts: `body`, `lid`
- Custom cutouts: 0
Run `ruby build.rb` in this directory to regenerate exports and previews.
OpenSCAD, Blender, and Python 3 must be installed. Set `OPENSCAD`,
`BLENDER`, or `PYTHON` to override their executable paths.
To open the saved Customizer values manually:
```bash
openscad -p parameters.json -P attitude-w-battery source/feather_case.scad
```
The 3MF files contain portable geometry only. Choose printer, filament,
plate, and slicing settings in Bambu Studio.
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
require "fileutils"
require "json"
require "open3"
require "pathname"
require "tmpdir"
require "yaml"
ROOT = Pathname(__dir__).expand_path
def executable(env_name, command)
override = ENV[env_name]
return File.expand_path(override) if override && File.executable?(override)
ENV.fetch("PATH", "").split(File::PATH_SEPARATOR).each do |directory|
candidate = File.join(directory, command)
return candidate if File.file?(candidate) && File.executable?(candidate)
end
nil
end
def literal(value)
case value
when String then JSON.generate(value)
when TrueClass then "true"
when FalseClass then "false"
when Numeric then value.to_s
when Array then "[#{value.map { |item| literal(item) }.join(",")}]"
else raise "Cannot convert #{value.inspect} to OpenSCAD"
end
end
def run!(*command, env: {})
stdout, stderr, status = Open3.capture3(env, *command)
return if status.success?
warn [stdout, stderr].reject(&:empty?).join("\n")
raise "Command failed (#{status.exitstatus}): #{command.first}"
end
config = YAML.safe_load_file(ROOT.join("case.yml"), permitted_classes: [],
permitted_symbols: [], aliases: false)
openscad = executable("OPENSCAD", "openscad")
blender = executable("BLENDER", "blender")
python = executable("PYTHON", "python3")
abort "OpenSCAD not found; install it or set OPENSCAD" unless openscad
abort "Blender not found; install it or set BLENDER" unless blender
parameters = config.fetch("parameters").merge(
"extra_cutouts" => config.fetch("resolved").fetch("extra_cutouts")
)
artwork = !parameters.fetch("lid_label", "").empty? ||
parameters.fetch("lid_logo_enabled", false)
abort "Python 3 not found; install it or set PYTHON" if artwork && !python
parts = %w[body lid] + config.fetch("outputs").fetch("coupons")
parts.concat(%w[lid_base lid_accent]) if artwork
buttons = %w[button_a button_b button_c button_reset]
if parameters["top_profile"] == "oled128x64" &&
buttons.any? { |name| parameters[name] }
parts << "buttons"
end
stage = Pathname(Dir.mktmpdir(".rebuild-", ROOT.to_s))
begin
exports = stage.join("exports")
previews = stage.join("previews")
scratch = stage.join("meshes")
FileUtils.mkdir_p([exports, previews, scratch])
model = ROOT.join("source/feather_case.scad")
renderer = ROOT.join("source/render_stl_previews.py")
export = lambda do |output, part, overrides = {}|
values = parameters.merge(overrides).merge("part" => part)
command = [openscad, "-o", output.to_s]
values.each { |name, value| command.concat(["-D", "#{name}=#{literal(value)}"]) }
run!(*command, model.to_s)
end
config.fetch("outputs").fetch("formats").each do |format|
directory = exports.join(format)
FileUtils.mkdir_p(directory)
parts.each do |part|
puts "Exporting #{part}.#{format}…"
export.call(directory.join("#{part}.#{format}"), part)
end
if artwork && format == "3mf"
puts "Packaging lid_multicolor.3mf…"
run!(
python, ROOT.join("tools/package_multimaterial_3mf.py").to_s,
directory.join("lid_base.3mf").to_s,
directory.join("lid_accent.3mf").to_s,
directory.join("lid_multicolor.3mf").to_s,
"--title", "#{config.fetch("name")} Lid"
)
end
end
assembly = scratch.join("assembly.stl")
puts "Preparing assembly preview…"
export.call(assembly, "assembly",
"exploded_view" => config.fetch("outputs").fetch("assembly_exploded_view"),
"show_references" => false)
render_env = {"DISPLAY" => nil, "WAYLAND_DISPLAY" => nil}
run!(blender, "--background", "-noaudio", "--python", renderer.to_s, "--",
assembly.to_s, previews.to_s, "assembly", env: render_env)
parts.each do |part|
puts "Rendering #{part} preview…"
mesh = scratch.join("#{part}.stl")
export.call(mesh, part) unless mesh.file?
run!(blender, "--background", "-noaudio", "--python", renderer.to_s, "--",
mesh.to_s, previews.to_s, part, "iso", env: render_env)
end
if artwork
puts "Rendering multicolor lid preview…"
run!(
blender, "--background", "-noaudio", "--python",
ROOT.join("source/render_multicolor_lid.py").to_s, "--",
scratch.join("lid_base.stl").to_s,
scratch.join("lid_accent.stl").to_s,
previews.to_s, "lid_multicolor", parameters["lid_art_orientation"], env: render_env
)
end
backup = ROOT.join(".build-old-#{Process.pid}")
FileUtils.mkdir_p(backup)
%w[exports previews].each do |name|
current = ROOT.join(name)
FileUtils.mv(current, backup.join(name)) if current.exist?
end
begin
FileUtils.mv(exports, ROOT.join("exports"))
FileUtils.mv(previews, ROOT.join("previews"))
FileUtils.rm_rf(backup)
rescue StandardError
FileUtils.rm_rf(ROOT.join("exports"))
FileUtils.rm_rf(ROOT.join("previews"))
%w[exports previews].each do |name|
saved = backup.join(name)
FileUtils.mv(saved, ROOT.join(name)) if saved.exist?
end
raise
end
puts "Rebuilt #{ROOT}"
ensure
FileUtils.rm_rf(stage)
end
+94
View File
@@ -0,0 +1,94 @@
---
schema_version: 1
name: Attitude w/battery
slug: attitude-w-battery
generator:
sha256: daeb9015a2bd04a16a75b77b32ee84bca2a9e2a4f4fe16605f3d5dc7e6d53036
created_with: feather-case-wizard
parameters:
top_profile: generic
wing_count: 1
wing_pitch: 11.0
stack_height_override: 0.0
generic_component_height: 3.0
generic_top_gap: 2.0
gps_antenna_height: 4.0
gps_top_gap: 5.0
oled_component_height: 2.4
oled_face_gap: 0.8
button_a: true
button_b: true
button_c: true
button_reset: false
button_projection: 1.5
button_cap_size:
- 5.0
- 3.2
button_flange_size:
- 6.6
- 3.6
button_flange_thickness: 0.9
button_travel: 0.5
button_contact_extension: 0.7
battery_enabled: true
battery_length: 69.0
battery_diameter: 18.0
battery_radial_clearance: 0.6
battery_end_clearance: 1.0
battery_partition_thickness: 1.8
rocker_cutout_size:
- 12.9
- 19.4
rocker_corner_radius: 0.8
rocker_body_size:
- 15.0
- 21.0
- 21.0
rocker_artwork_gap: 2.0
tripod_insert_enabled: true
tripod_insert_length: 5.0
tripod_insert_hole_diameter: 7.2
tripod_insert_outer_diameter: 8.0
tripod_thread_clearance_diameter: 6.8
tripod_boss_diameter: 14.0
m25_insert_length: 4.0
m25_insert_hole_diameter: 3.1
m25_insert_outer_diameter: 3.5
m25_screw_clearance: 2.8
m25_boss_diameter: 7.0
insert_entry_chamfer: 0.6
insert_melt_relief: 0.8
wall_thickness: 2.4
floor_thickness: 2.4
lid_thickness: 3.2
corner_radius: 4.0
board_bottom_clearance: 5.4
board_side_clearance: 7.0
board_rear_clearance: 4.0
usb_board_wall_gap: 1.2
lid_lip_depth: 2.4
lid_lip_thickness: 1.2
fit_clearance: 0.35
hole_compensation: 0.2
lid_screw_head_diameter: 5.2
lid_screw_head_height: 2.5
lid_label: ''
lid_logo_enabled: false
lid_art_orientation: usb_left
lid_inlay_depth: 0.6
lid_inlay_fit_clearance: 0.08
lid_label_size: 5.0
lid_label_logo_gap: 2.0
lid_art_margin: 8.5
usb_opening_width: 12.5
usb_opening_height: 7.0
usb_opening_radius: 1.5
usb_vertical_offset: 0.0
cutouts: []
outputs:
formats:
- 3mf
coupons: []
assembly_exploded_view: 8
resolved:
extra_cutouts: []
+76
View File
@@ -0,0 +1,76 @@
{
"parameterSets": {
"attitude-w-battery": {
"top_profile": "\"generic\"",
"wing_count": "1",
"wing_pitch": "11.0",
"stack_height_override": "0.0",
"generic_component_height": "3.0",
"generic_top_gap": "2.0",
"gps_antenna_height": "4.0",
"gps_top_gap": "5.0",
"oled_component_height": "2.4",
"oled_face_gap": "0.8",
"button_a": "true",
"button_b": "true",
"button_c": "true",
"button_reset": "false",
"button_projection": "1.5",
"button_cap_size": "[5.0,3.2]",
"button_flange_size": "[6.6,3.6]",
"button_flange_thickness": "0.9",
"button_travel": "0.5",
"button_contact_extension": "0.7",
"battery_enabled": "true",
"battery_length": "69.0",
"battery_diameter": "18.0",
"battery_radial_clearance": "0.6",
"battery_end_clearance": "1.0",
"battery_partition_thickness": "1.8",
"rocker_cutout_size": "[12.9,19.4]",
"rocker_corner_radius": "0.8",
"rocker_body_size": "[15.0,21.0,21.0]",
"rocker_artwork_gap": "2.0",
"tripod_insert_enabled": "true",
"tripod_insert_length": "5.0",
"tripod_insert_hole_diameter": "7.2",
"tripod_insert_outer_diameter": "8.0",
"tripod_thread_clearance_diameter": "6.8",
"tripod_boss_diameter": "14.0",
"m25_insert_length": "4.0",
"m25_insert_hole_diameter": "3.1",
"m25_insert_outer_diameter": "3.5",
"m25_screw_clearance": "2.8",
"m25_boss_diameter": "7.0",
"insert_entry_chamfer": "0.6",
"insert_melt_relief": "0.8",
"wall_thickness": "2.4",
"floor_thickness": "2.4",
"lid_thickness": "3.2",
"corner_radius": "4.0",
"board_bottom_clearance": "5.4",
"board_side_clearance": "7.0",
"board_rear_clearance": "4.0",
"usb_board_wall_gap": "1.2",
"lid_lip_depth": "2.4",
"lid_lip_thickness": "1.2",
"fit_clearance": "0.35",
"hole_compensation": "0.2",
"lid_screw_head_diameter": "5.2",
"lid_screw_head_height": "2.5",
"lid_label": "\"\"",
"lid_logo_enabled": "false",
"lid_art_orientation": "\"usb_left\"",
"lid_inlay_depth": "0.6",
"lid_inlay_fit_clearance": "0.08",
"lid_label_size": "5.0",
"lid_label_logo_gap": "2.0",
"lid_art_margin": "8.5",
"usb_opening_width": "12.5",
"usb_opening_height": "7.0",
"usb_opening_radius": "1.5",
"usb_vertical_offset": "0.0"
}
},
"fileFormatVersion": "1"
}
@@ -0,0 +1,82 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="210mm"
height="297mm"
viewBox="0 0 210 297"
version="1.1"
id="svg584"
inkscape:version="1.2.2 (b0a8486541, 2022-12-01)"
sodipodi:docname="NME-fixed.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<sodipodi:namedview
id="namedview586"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
inkscape:document-units="mm"
showgrid="false"
inkscape:zoom="0.914906"
inkscape:cx="1166.24"
inkscape:cy="477.6447"
inkscape:window-width="3440"
inkscape:window-height="1390"
inkscape:window-x="0"
inkscape:window-y="1080"
inkscape:window-maximized="1"
inkscape:current-layer="layer1" />
<defs
id="defs581" />
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1">
<g
id="g772">
<path
id="path2"
d="m 97.576583,26.288608 c -0.51788,0.06491 -2.361848,0.291394 -4.044598,0.485422 -15.62735,1.747308 -32.128529,8.73619 -44.81195,18.960393 -9.803341,7.926917 -17.342201,17.309748 -23.360236,29.151792 -2.879725,5.629978 -3.170767,6.632927 -1.941336,6.535912 0.388054,-0.03245 2.556227,-0.06491 4.788604,-0.03245 l 4.0767,0.03245 4.820708,5.662083 c 2.653242,3.106208 4.918075,5.662083 5.01509,5.662083 0.09737,0 0.291394,-1.035402 0.420862,-2.297287 0.09701,-1.261888 0.517525,-3.688291 0.87348,-5.403146 3.106208,-14.559843 9.415285,-26.692928 19.186524,-36.852576 6.276975,-6.568017 12.521494,-11.098035 21.030846,-15.304204 5.597525,-2.749903 9.933164,-4.367742 15.562791,-5.823656 l 3.559172,-0.938388 -2.10291,0.03245 c -1.164868,0.03246 -2.523768,0.09701 -3.073747,0.129117"
style="fill:#100f0d;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0.0352777" />
<path
id="path3"
d="m 169.08146,36.027745 c -26.62837,2.232377 -57.46291,14.33336 -85.90315,33.68181 -5.85611,3.979685 -15.530335,11.130137 -15.530335,11.453635 0,0.16157 1.3589,0.258937 3.008842,0.258937 h 2.976737 l 3.7211,-2.78271 c 4.917723,-3.688644 13.977408,-9.738784 19.574581,-13.071475 5.759445,-3.46216 18.668995,-9.997721 24.751595,-12.55395 21.90467,-9.188802 42.51501,-12.747625 55.16562,-9.576858 5.04754,1.261888 9.35073,4.432654 11.09769,8.120946 0.80891,1.747308 0.87381,2.167818 0.87381,6.406443 0,4.270727 -0.0649,4.691592 -1.06748,7.603419 -2.65325,7.700433 -8.70374,17.439568 -16.8575,27.178351 -1.26188,1.520825 -2.29693,2.814815 -2.29693,2.91183 0,0.09737 4.7886,0.129468 10.67718,0.06491 l 10.67715,-0.09701 V 90.772856 85.91934 l 2.07081,-2.814815 C 196.58332,76.860006 200.59546,69.677098 202.56925,64.11203 208.1015,48.484325 201.79243,38.616074 184.77337,36.286682 181.6996,35.86582 172.7373,35.704247 169.08146,36.027745"
style="fill:#100f0d;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0.0352777" />
<path
id="path4"
d="m 19.11528,111.8358 v 26.20751 h 11.000669 v -35.91419 l 1.552926,1.71486 c 0.841375,0.93839 4.59458,5.27402 8.347782,9.64212 3.753202,4.33564 9.350727,10.80664 12.456583,14.36582 3.106208,3.55882 6.341533,7.31202 7.215362,8.34742 l 1.552929,1.84397 h 5.629979 5.62963 V 111.8358 85.628298 H 66.8066 61.079958 l 0.161573,17.957092 c 0.06491,9.86825 0.06491,17.95709 -0.03246,17.95709 -0.09666,-0.0324 -0.711552,-0.67945 -1.326443,-1.45591 -0.61454,-0.77646 -4.27073,-5.01509 -8.088842,-9.41564 C 40.857677,98.052425 37.978307,94.720085 33.998622,90.060598 l -3.7211,-4.367742 -5.565071,-0.03246 -5.597171,-0.0321 V 111.8358"
style="fill:#100f0d;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0.0352777" />
<path
id="path5"
d="m 77.030804,111.8358 v 26.20751 h 11.001023 v -35.04035 l 6.7945,9.02687 c 3.720748,4.98299 8.023933,10.67753 9.544753,12.68342 l 2.81481,3.65584 9.5123,-12.68307 9.5123,-12.68306 0.0649,13.65391 0.097,13.65355 3.85022,-3.26743 c 2.13571,-1.81186 4.56212,-3.91512 5.43595,-4.69159 l 1.55293,-1.39135 V 103.294 85.628298 h -5.56507 l -5.59753,0.0321 -9.38283,12.456935 c -5.14456,6.826957 -9.4802,12.392027 -9.57721,12.359567 -0.19438,-0.097 -4.4002,-5.56507 -14.33336,-18.798467 L 88.1934,85.628298 H 82.628329 77.030804 V 111.8358"
style="fill:#100f0d;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0.0352777" />
<path
id="path6"
d="m 170.4079,106.88563 -12.58605,0.097 -6.66538,6.56802 c -21.32189,20.93383 -39.11741,34.16723 -59.727393,44.39108 -28.796192,14.30126 -53.936193,18.6369 -68.334112,11.77749 -2.976739,-1.42381 -6.115402,-4.10916 -7.441848,-6.34154 -2.78271,-4.7565 -2.750253,-12.03642 0.06491,-18.41006 1.002946,-2.29729 1.002946,-2.3943 -0.161925,-2.3943 h -0.93839 l -0.09701,-2.84727 -0.09701,-2.81517 -1.553282,2.58869 c -3.8177601,6.40609 -6.9236165,14.00986 -7.8295498,19.18652 -1.3267981,7.50641 0.1615731,13.07183 4.6912397,17.53659 2.6856951,2.65289 5.0150871,4.04459 8.9947751,5.37068 8.088841,2.6857 18.863026,3.0413 30.608055,0.93874 l 4.238273,-0.74436 3.882673,2.39431 c 14.689312,8.96232 30.252104,13.39497 46.947304,13.39497 14.49529,0 26.66083,-2.81482 39.53828,-9.12389 14.59194,-7.18326 27.33992,-18.70146 35.91418,-32.45238 1.97345,-3.17112 5.92103,-10.80664 6.50312,-12.52185 l 0.32385,-1.0675 -0.54999,0.80892 c -8.60672,12.42447 -18.15112,20.90137 -30.5756,27.08133 -18.15112,9.05934 -39.14987,10.90366 -57.980434,5.04719 -3.268133,-1.00294 -10.839098,-4.01178 -10.806642,-4.27072 0,-0.097 3.461809,-1.90888 7.667977,-3.97969 4.206169,-2.0708 9.706679,-4.95053 12.197999,-6.43855 9.93281,-5.824 22.4222,-14.5923 31.70801,-22.26027 l 3.55918,-2.94464 0.097,1.29434 0.097,1.29399 h 23.94302 23.91021 v -5.01509 -5.01473 h -18.44215 -18.44287 v -1.22943 c 0,-1.16488 0.25929,-1.48873 4.49756,-5.50052 l 4.49721,-4.27072 h 10.54806 l 10.54769,-0.0325 v -5.17701 c 0,-2.81482 -0.0324,-5.11175 -0.0646,-5.07965 -0.0649,0.0646 -5.75944,0.12947 -12.68341,0.16193"
style="fill:#100f0d;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0.0352777" />
<path
id="path7"
d="m 34.484042,128.23997 v 14.17144 l -6.018035,0.16192 -6.01839,0.16157 1.326798,2.91218 c 3.559175,7.79745 8.703382,15.82173 13.912496,21.67785 l 1.423812,1.58538 4.691592,-0.38806 c 5.079645,-0.42086 9.609312,-1.19732 15.497879,-2.6857 3.429706,-0.84102 11.518548,-3.39725 11.906604,-3.75285 0.06491,-0.0649 -0.582438,-0.74471 -1.455915,-1.48872 -9.544756,-7.95937 -17.083264,-18.15112 -21.80731,-29.44318 -1.455914,-3.39725 -1.649941,-3.68829 -7.312379,-10.25631 -3.202869,-3.7211 -5.888564,-6.7624 -5.985579,-6.7624 -0.09701,-0.0324 -0.161573,6.34154 -0.161573,14.10688"
style="fill:#100f0d;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0.0352777" />
<g
id="g475"
transform="matrix(0.14274222,0,0,0.14274222,123.03997,38.158339)">
<path
d="m 134.23594,367.14576 v 34.66667 h 69.06667 c 37.86666,0 71.06666,-0.4 73.86666,-0.8 4.4,-0.8 7.2,-3.73333 31.33333,-32.8 14.53334,-17.46667 26.53334,-32.4 26.8,-32.93333 0.26667,-0.66667 -0.93333,-1.46667 -2.66666,-2 -1.73334,-0.4 -47.06667,-0.8 -100.66667,-0.8 h -97.73333 z"
id="path251"
style="fill:#000000;stroke:none;stroke-width:0.133333" />
<path
d="m 134.90261,432.74576 c -0.4,0.93334 -0.53333,27.2 -0.4,58.4 l 0.4,56.53333 38.4,-37.06666 38.26666,-37.06667 -0.26666,-20.93333 -0.4,-20.8 -37.73334,-0.4 c -29.46666,-0.26667 -37.86666,0 -38.26666,1.33333 z"
id="path253"
style="fill:#000000;stroke:none;stroke-width:0.133333" />
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 7.8 KiB

File diff suppressed because it is too large Load Diff
@@ -0,0 +1,101 @@
"""Render aligned lid-base and accent STLs with distinct materials."""
import os
import sys
import math
import bpy
from mathutils import Matrix, Vector
def import_mesh(path, name, color):
bpy.ops.wm.stl_import(filepath=os.path.abspath(path))
model = bpy.context.selected_objects[0]
model.name = name
material = bpy.data.materials.new(f"{name} material")
material.diffuse_color = color
material.metallic = 0.0
material.roughness = 0.45
model.data.materials.append(material)
return model
def look_at(camera, target):
direction = Vector(target) - camera.location
camera.rotation_euler = direction.to_track_quat("-Z", "Y").to_euler()
def main():
args = sys.argv[sys.argv.index("--") + 1 :]
if len(args) not in (4, 5):
raise SystemExit(
"expected: lid-base.stl lid-accent.stl output-directory basename [orientation]"
)
base_path, accent_path, output_dir, basename = args[:4]
orientation = args[4] if len(args) == 5 else "usb_left"
angles = {"usb_left": 0, "usb_front": 90, "usb_right": 180, "usb_rear": 270}
if orientation not in angles:
raise SystemExit(f"unknown lid orientation: {orientation}")
os.makedirs(output_dir, exist_ok=True)
bpy.ops.wm.read_factory_settings(use_empty=True)
models = [
import_mesh(base_path, "Lid base", (0.16, 0.42, 0.72, 1.0)),
import_mesh(accent_path, "Accent inlays", (0.95, 0.42, 0.08, 1.0)),
]
# Lid exports are print-oriented with the decorated exterior face down.
# Turn both aligned parts over and present the configured USB edge in its
# named position so previews inspect the finished face as the user will.
for model in models:
model.matrix_world = (
Matrix.Rotation(math.radians(angles[orientation]), 4, "Z")
@ Matrix.Rotation(math.pi, 4, "X")
)
bpy.context.view_layer.update()
corners = [obj.matrix_world @ Vector(corner) for obj in models for corner in obj.bound_box]
mins = Vector([min(v[i] for v in corners) for i in range(3)])
maxs = Vector([max(v[i] for v in corners) for i in range(3)])
center = (mins + maxs) / 2
span = max(maxs - mins)
world = bpy.data.worlds.new("Inspection world")
world.use_nodes = True
world.node_tree.nodes["Background"].inputs["Color"].default_value = (0.035, 0.04, 0.05, 1)
world.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.5
bpy.context.scene.world = world
camera_data = bpy.data.cameras.new("Camera")
camera = bpy.data.objects.new("Camera", camera_data)
bpy.context.collection.objects.link(camera)
bpy.context.scene.camera = camera
camera.data.type = "ORTHO"
camera.data.ortho_scale = span * 1.35
key_data = bpy.data.lights.new("Key", type="AREA")
key_data.energy = 900
key_data.size = span
key = bpy.data.objects.new("Key", key_data)
key.location = center + Vector((span, -span, span * 1.5))
bpy.context.collection.objects.link(key)
scene = bpy.context.scene
scene.render.engine = "BLENDER_WORKBENCH"
scene.render.resolution_x = 800
scene.render.resolution_y = 600
scene.render.resolution_percentage = 100
scene.render.image_settings.file_format = "PNG"
scene.display.shading.light = "STUDIO"
scene.display.shading.color_type = "MATERIAL"
scene.display.shading.show_shadows = True
scene.display.shading.show_cavity = True
scene.display.shading.cavity_type = "BOTH"
for view, direction in {"iso": (1, -1, 0.8), "top": (0, 0, 1)}.items():
camera.location = center + Vector(direction).normalized() * span * 2.2
look_at(camera, center)
scene.render.filepath = os.path.join(output_dir, f"{basename}_{view}.png")
bpy.ops.render.render(write_still=True)
if __name__ == "__main__":
main()
@@ -0,0 +1,127 @@
"""Render six inspection views of an STL using Blender.
Usage:
blender --background --python tools/render_stl_previews.py -- \
input.stl output-directory basename [comma-separated-views]
"""
import os
import sys
import bpy
from mathutils import Vector
def arguments():
args = sys.argv[sys.argv.index("--") + 1 :]
if len(args) not in (3, 4):
raise SystemExit(
"expected: input.stl output-directory basename [comma-separated-views]"
)
requested_views = args[3].split(",") if len(args) == 4 else None
return args[0], args[1], args[2], requested_views
def look_at(camera, target):
direction = Vector(target) - camera.location
camera.rotation_euler = direction.to_track_quat("-Z", "Y").to_euler()
def render_view(camera, center, span, name, direction, output_dir, basename):
distance = span * 2.2
camera.location = Vector(center) + Vector(direction).normalized() * distance
look_at(camera, center)
camera.data.type = "ORTHO"
camera.data.ortho_scale = span * 1.35
bpy.context.scene.render.filepath = os.path.join(
output_dir, f"{basename}_{name}.png"
)
bpy.ops.render.render(write_still=True)
def main():
input_path, output_dir, basename, requested_views = arguments()
os.makedirs(output_dir, exist_ok=True)
bpy.ops.wm.read_factory_settings(use_empty=True)
bpy.ops.wm.stl_import(filepath=os.path.abspath(input_path))
model = bpy.context.selected_objects[0]
model.name = "Feather case"
material = bpy.data.materials.new("Case material")
material.diffuse_color = (0.16, 0.42, 0.72, 1.0)
material.metallic = 0.0
material.roughness = 0.45
model.data.materials.append(material)
corners = [model.matrix_world @ Vector(corner) for corner in model.bound_box]
mins = Vector([min(v[i] for v in corners) for i in range(3)])
maxs = Vector([max(v[i] for v in corners) for i in range(3)])
center = (mins + maxs) / 2
span = max(maxs - mins)
world = bpy.data.worlds.new("Inspection world")
world.use_nodes = True
world.node_tree.nodes["Background"].inputs["Color"].default_value = (
0.035,
0.04,
0.05,
1,
)
world.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.5
bpy.context.scene.world = world
camera_data = bpy.data.cameras.new("Camera")
camera = bpy.data.objects.new("Camera", camera_data)
bpy.context.collection.objects.link(camera)
bpy.context.scene.camera = camera
key_data = bpy.data.lights.new("Key", type="AREA")
key_data.energy = 900
key_data.shape = "DISK"
key_data.size = span
key = bpy.data.objects.new("Key", key_data)
key.location = center + Vector((span, -span, span * 1.5))
bpy.context.collection.objects.link(key)
fill_data = bpy.data.lights.new("Fill", type="AREA")
fill_data.energy = 500
fill_data.size = span
fill = bpy.data.objects.new("Fill", fill_data)
fill.location = center + Vector((-span, span, span))
bpy.context.collection.objects.link(fill)
scene = bpy.context.scene
scene.render.engine = "BLENDER_WORKBENCH"
scene.render.resolution_x = 800
scene.render.resolution_y = 600
scene.render.resolution_percentage = 100
scene.render.image_settings.file_format = "PNG"
scene.render.film_transparent = False
scene.display.shading.light = "STUDIO"
scene.display.shading.color_type = "MATERIAL"
scene.display.shading.show_shadows = True
scene.display.shading.show_cavity = True
scene.display.shading.cavity_type = "BOTH"
scene.display.shading.curvature_ridge_factor = 1.5
scene.display.shading.curvature_valley_factor = 1.2
views = {
"iso": (1, -1, 0.8),
"front": (-1, 0, 0),
"back": (1, 0, 0),
"left": (0, -1, 0),
"right": (0, 1, 0),
"top": (0, 0, 1),
}
selected = requested_views or list(views)
unknown = sorted(set(selected) - set(views))
if unknown:
raise SystemExit(f"unknown views: {', '.join(unknown)}")
for name in selected:
direction = views[name]
render_view(camera, center, span, name, direction, output_dir, basename)
if __name__ == "__main__":
main()
@@ -0,0 +1,138 @@
#!/usr/bin/env python3
"""Combine aligned lid meshes into one slicer-friendly multipart 3MF."""
from __future__ import annotations
import argparse
import copy
import zipfile
from pathlib import Path
from xml.etree import ElementTree as ET
CORE = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02"
ET.register_namespace("", CORE)
CONTENT_TYPES_XML = b'''<?xml version="1.0" encoding="UTF-8"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml"/>
</Types>
'''
RELATIONSHIPS_XML = b'''<?xml version="1.0" encoding="UTF-8"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Target="/3D/3dmodel.model" Id="rel0" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/>
</Relationships>
'''
def load_mesh(path: Path) -> ET.Element:
with zipfile.ZipFile(path) as archive:
root = ET.fromstring(archive.read("3D/3dmodel.model"))
mesh = root.find(f".//{{{CORE}}}mesh")
if mesh is None:
raise ValueError(f"{path} does not contain a 3MF mesh")
return copy.deepcopy(mesh)
def model_xml(base: Path, accent: Path, title: str) -> bytes:
root = ET.Element(
f"{{{CORE}}}model",
{
"unit": "millimeter",
"{http://www.w3.org/XML/1998/namespace}lang": "en-US",
},
)
ET.SubElement(root, f"{{{CORE}}}metadata", {"name": "Title"}).text = title
ET.SubElement(root, f"{{{CORE}}}metadata", {"name": "Generator"}).text = (
"feather-case-wizard"
)
resources = ET.SubElement(root, f"{{{CORE}}}resources")
materials = ET.SubElement(resources, f"{{{CORE}}}basematerials", {"id": "1"})
ET.SubElement(
materials, f"{{{CORE}}}base", {"name": "Lid base", "displaycolor": "#D1D5DB"}
)
ET.SubElement(
materials,
f"{{{CORE}}}base",
{"name": "Accent inlays", "displaycolor": "#F97316"},
)
for object_id, name, source in (
(2, "Lid base — Filament 1", base),
(3, "Accent inlays — Filament 2", accent),
):
obj = ET.SubElement(
resources,
f"{{{CORE}}}object",
{
"id": str(object_id),
"name": name,
"type": "model",
"pid": "1",
"pindex": str(object_id - 2),
},
)
obj.append(load_mesh(source))
assembly = ET.SubElement(
resources, f"{{{CORE}}}object", {"id": "4", "name": title, "type": "model"}
)
components = ET.SubElement(assembly, f"{{{CORE}}}components")
ET.SubElement(components, f"{{{CORE}}}component", {"objectid": "2"})
ET.SubElement(components, f"{{{CORE}}}component", {"objectid": "3"})
build = ET.SubElement(root, f"{{{CORE}}}build")
ET.SubElement(build, f"{{{CORE}}}item", {"objectid": "4"})
return ET.tostring(root, encoding="utf-8", xml_declaration=True)
def bambu_model_settings_xml(title: str) -> bytes:
root = ET.Element("config")
obj = ET.SubElement(root, "object", {"id": "4"})
ET.SubElement(obj, "metadata", {"key": "name", "value": title})
for part_id, name, extruder in (
(2, "Lid base — Filament 1", 1),
(3, "Accent inlays — Filament 2", 2),
):
part = ET.SubElement(obj, "part", {"id": str(part_id), "subtype": "normal_part"})
ET.SubElement(part, "metadata", {"key": "name", "value": name})
ET.SubElement(part, "metadata", {"key": "extruder", "value": str(extruder)})
ET.SubElement(root, "assemble")
return ET.tostring(root, encoding="utf-8", xml_declaration=True)
def write_entry(archive: zipfile.ZipFile, name: str, data: bytes) -> None:
info = zipfile.ZipInfo(name)
info.create_system = 3
info.external_attr = 0o100644 << 16
info.compress_type = zipfile.ZIP_DEFLATED
archive.writestr(info, data)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("base", type=Path)
parser.add_argument("accent", type=Path)
parser.add_argument("output", type=Path)
parser.add_argument("--title", required=True)
args = parser.parse_args()
args.output.parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(args.output, "w", zipfile.ZIP_DEFLATED) as archive:
write_entry(archive, "[Content_Types].xml", CONTENT_TYPES_XML)
write_entry(archive, "_rels/.rels", RELATIONSHIPS_XML)
write_entry(
archive,
"3D/3dmodel.model",
model_xml(args.base, args.accent, args.title),
)
write_entry(
archive,
"Metadata/model_settings.config",
bambu_model_settings_xml(args.title),
)
if __name__ == "__main__":
main()