1use sim_core::{Config, ConfigError};
5use toml::{Table, Value};
6
7type Result<T> = std::result::Result<T, ConfigError>;
8
9pub const VERSION: i64 = 1;
12
13#[derive(Debug, Clone, Copy, PartialEq)]
15pub enum Kind {
16 Id,
18 Key,
20 Number,
23 Bool,
24 Table,
26 Ref(&'static str),
28 Refs(&'static str),
30 Coefficients(&'static str),
32 Position,
34 Point,
36 Route(&'static [&'static str]),
38 Choice(&'static [&'static str]),
40}
41
42pub struct Field {
43 pub name: &'static str,
44 pub kind: Kind,
45 pub required: bool,
46 pub doc: &'static str,
47}
48
49const fn field(name: &'static str, kind: Kind, required: bool, doc: &'static str) -> Field {
50 Field { name, kind, required, doc }
51}
52
53const ID: Field = field("id", Kind::Id, true, "Stable id of the node; signals and other nodes refer to it.");
54const POS: Field =
55 field("pos", Kind::Position, false, "Where a node editor draws the node, [x, y]. Not read by the simulation.");
56const CLOCKWISE: Field = field(
57 "clockwise",
58 Kind::Bool,
59 false,
60 "The belt runs round it clockwise, followed along the routes in their order, seen in its belt's plane (its section's `plane`): from the front (x to the right, z up) in x-z, from above (x to the right, y away) in x-y, from +x (y to the right, z up) in y-z. Its spin in the frame momentum takes this sense, and effects.belt_wrap the wrap. Default false (anticlockwise).",
61);
62
63pub const NODES: &[(&str, &str, &[Field])] = &[
65 (
66 "axis",
67 "A tool axis: a straight coordinate of the tool, from 0 to its stroke. Its limits are in [axis.<id>].",
68 &[
69 ID,
70 field("key", Kind::Key, false, "Translation key of its name; default axis-<id>."),
71 field("stroke_m", Kind::Number, false, "Stroke, m; every axis but a rotary one has it."),
72 field(
73 "stroke_rad",
74 Kind::Number,
75 false,
76 "Range of a rotary axis (one a rotary node turns), from 0, rad; in place of stroke_m.",
77 ),
78 field(
79 "incline_deg",
80 Kind::Number,
81 false,
82 "Angle of the axis above the horizontal, deg; 90 is vertical, rising towards +. Default 0. On a rotary axis the tilt of the axis it turns about, from the vertical (0, a C axis) towards x (90, an A axis).",
83 ),
84 field(
85 "cable_chain",
86 Kind::Bool,
87 false,
88 "The axis drags a cable chain fixed at its 0 end (effects.cable_chain, values in [cable_chain]). Default false.",
89 ),
90 POS,
91 ],
92 ),
93 (
94 "motor",
95 "A servo motor with its drive; its data is in [motor] and [drive], shared by all motors; [motor.<id>], [drive.<id>], [gearbox.<id>], [ratings.<id>] and [parts.<id>] give one motor its own.",
96 &[ID, field("key", Kind::Key, false, "Translation key of its name; default motor-<id>."), POS],
97 ),
98 (
99 "gearbox",
100 "The gearbox on a motor's shaft; its data is in [gearbox], shared by all gearboxes. A ratio of 1 is a coupling.",
101 &[ID, field("motor", Kind::Ref("motor"), true, "The motor that drives it."), POS],
102 ),
103 (
104 "pulley",
105 "The toothed pulley on a gearbox's output, which feeds belt into the sections it ends.",
106 &[
107 ID,
108 field("gearbox", Kind::Ref("gearbox"), true, "The gearbox that turns it."),
109 field("radius_m", Kind::Number, true, "Pitch radius, m."),
110 field("inertia_kgm2", Kind::Number, true, "Inertia without the belt, kg m^2."),
111 field(
112 "at_m",
113 Kind::Point,
114 false,
115 "Where the 3D view draws it, [x, y, z], m (from its body where it has one); default at an end of the first axis. Its place in its belt's plane (its section's `plane`) is what the wrap (effects.belt_wrap) and the places of the belt's runs in the frame momentum are worked out from.",
116 ),
117 field(
118 "body",
119 Kind::Ref("body"),
120 false,
121 "A body it rides on (a motor on a moving axis): at_m is then from that body.",
122 ),
123 CLOCKWISE,
124 POS,
125 ],
126 ),
127 (
128 "section",
129 "A belt section: the belt between two driven pulleys, or between a driven pulley and a clamp. Its tension is the same all along; idlers it runs over count as belt.",
130 &[
131 ID,
132 field("key", Kind::Key, false, "Translation key of its name; default belt-section-<id>."),
133 field("length_m", Kind::Number, true, "Length with every axis at 0, m."),
134 field("axes", Kind::Coefficients("axis"), true, "How much longer the section gets per metre of each axis."),
135 field(
136 "pulleys",
137 Kind::Coefficients("pulley"),
138 true,
139 "+1 for a pulley whose forward turn feeds belt into the section, -1 for one that takes belt out of it.",
140 ),
141 field(
142 "route",
143 Kind::Route(&["pulley", "idler", "body"]),
144 false,
145 "The pulleys, idlers and bodies (a clamp on it) the section runs past, in order, for the 3D view; default its pulleys and the body it is clamped to.",
146 ),
147 field(
148 "plane",
149 Kind::Choice(&["x-z", "x-y", "y-z"]),
150 false,
151 "The plane its belt runs in, whose normal its wheels turn about: x-z standing along x (about y), x-y flat (about z), y-z standing along y (about x). The places of its route's wheels in it give the belt's runs their places in the frame momentum, and the wrap. Sections that share a pulley or an idler lie in one plane. Default x-z, or x-y for every section where one section's length changes with axes along x and along y and none along z (an H-bot's, a CoreXY's).",
152 ),
153 POS,
154 ],
155 ),
156 (
157 "body",
158 "A rigid body the axes move: a carriage, a vertical axis.",
159 &[
160 ID,
161 field("mass_kg", Kind::Number, true, "Mass, kg."),
162 field(
163 "payload_kg",
164 Kind::Number,
165 false,
166 "Payload it carries while effects.payload is on and the payload is attached, kg.",
167 ),
168 field(
169 "axes",
170 Kind::Refs("axis"),
171 true,
172 "The axes it moves along: it moves with each of them. Rotary axes among them carry it round, the first outermost.",
173 ),
174 field(
175 "offset_m",
176 Kind::Point,
177 false,
178 "Its centre of mass from where its axes put it, [x, y, z], m: on rotary axes from the point their axes meet at angle 0 (it turns with them); on straight axes alone a constant offset, which only its place in the frame momentum has (its angular momentum and first moment). Default [0, 0, 0].",
179 ),
180 POS,
181 ],
182 ),
183 (
184 "guide",
185 "The linear guide of an axis, with its friction (LuGre with Stribeck, see mech::Lugre). Its id names its loss power, power.<id>, and its warmth.",
186 &[
187 ID,
188 field("axis", Kind::Ref("axis"), true, "The axis it guides; one guide per axis at most."),
189 field(
190 "friction",
191 Kind::Table,
192 true,
193 "The table of its friction values, laid out as [friction_x] of the shipped files.",
194 ),
195 field("carries", Kind::Refs("body"), false, "Bodies whose weight across the axis it carries."),
196 field(
197 "overhang",
198 Kind::Ref("body"),
199 false,
200 "A body that overhangs the guide: accelerated along overhang_axis it tilts the guide's carriages.",
201 ),
202 field(
203 "overhang_axis",
204 Kind::Ref("axis"),
205 false,
206 "The axis along which the overhang's acceleration tilts the guide.",
207 ),
208 field(
209 "lever_m",
210 Kind::Number,
211 false,
212 "Distance of the overhang's centre of mass from the guide with lever_axis at 0, m.",
213 ),
214 field(
215 "lever_axis",
216 Kind::Ref("axis"),
217 false,
218 "An axis whose travel shortens the lever (the overhang rises towards the guide).",
219 ),
220 field(
221 "spacing_m",
222 Kind::Number,
223 false,
224 "Spacing of the guide's two carriages, m; the tilt puts 2 m a lever / spacing on them.",
225 ),
226 field(
227 "side_load",
228 Kind::Bool,
229 false,
230 "The guide also carries the overhang's inertia force m a sideways. Default false.",
231 ),
232 POS,
233 ],
234 ),
235 (
236 "idler",
237 "A free pulley the belt runs over (effects.idlers): its inertia and bearing friction, at the belt speed past it.",
238 &[
239 ID,
240 field(
241 "speed",
242 Kind::Coefficients("axis"),
243 true,
244 "Belt speed past it per speed of each axis (m/s per m/s), positive the way a positive turn of the first pulley that feeds its section moves the belt (the sense its spin in the frame momentum takes).",
245 ),
246 field("radius_m", Kind::Number, true, "Radius, m."),
247 field("inertia_kgm2", Kind::Number, true, "Inertia, kg m^2."),
248 field("friction_nm", Kind::Number, true, "Bearing friction torque, N m."),
249 field(
250 "body",
251 Kind::Ref("body"),
252 false,
253 "A body it rides on, for the 3D view: at_m is then from that body.",
254 ),
255 field(
256 "at_m",
257 Kind::Point,
258 false,
259 "Where the 3D view draws it, [x, y, z], m (from its body where it has one); its place in its belt's plane (the plane of the section whose route has it), as for a pulley.",
260 ),
261 CLOCKWISE,
262 POS,
263 ],
264 ),
265 (
266 "frame",
267 "The machine frame swaying along a horizontal axis on its own spring (effects.frame_compliance, elastic model only). At most one.",
268 &[
269 ID,
270 field("axis", Kind::Ref("axis"), true, "The axis the frame sways along; it has to be horizontal."),
271 field(
272 "mass_kg",
273 Kind::Number,
274 true,
275 "The frame's mass in its sway, kg; bodies that do not move along the axis ride on it too.",
276 ),
277 field("stiffness_n_m", Kind::Number, true, "Its stiffness, N/m."),
278 field("damping_n_s_m", Kind::Number, true, "Its damping, N s/m."),
279 POS,
280 ],
281 ),
282 (
283 "span",
284 "A free belt span between two points that hold it (pulley, idler, clamp), for its sideways mode (effects.belt_span_vibration), and with its speed over ground for the belt's mass run by run.",
285 &[
286 ID,
287 field("section", Kind::Ref("section"), true, "The section it is part of: its tension."),
288 field("length_m", Kind::Number, true, "Length with every axis at 0, m."),
289 field("axes", Kind::Coefficients("axis"), false, "How much longer it gets per metre of each axis."),
290 field(
291 "velocity_x",
292 Kind::Coefficients("axis"),
293 false,
294 "Its belt's speed over ground along x of the 3D view per unit speed of each axis. Given on every span (with velocity_y and velocity_z, 0 where left out), the spans together the whole belt, the belt's kinetic energy is summed run by run (effects.belt_mass) beyond the half of it on each pulley.",
295 ),
296 field("velocity_y", Kind::Coefficients("axis"), false, "As velocity_x, along y."),
297 field("velocity_z", Kind::Coefficients("axis"), false, "As velocity_x, along z."),
298 field(
299 "yaw_lever_m",
300 Kind::Number,
301 false,
302 "With effects.gantry_yaw and machine.gantry: where the span lies across the yawing bridge from its centre, m, so that the yaw moves its belt along the bridge's axis by that times the yaw angle (as a body's lever): its speed over ground gets the lever times the yaw rate along that axis, and the belt's kinetic energy the yaw with it. Default 0 (a span the yaw does not move, or whose lever is not known).",
303 ),
304 field(
305 "yaw_lever_axes",
306 Kind::Coefficients("axis"),
307 false,
308 "How much its lever grows per metre of each axis (a run that ends on the head moving across the bridge); with yaw_lever_m. Default 0.",
309 ),
310 POS,
311 ],
312 ),
313 (
314 "screw",
315 "A ball screw on a gearbox's output (a gearbox of ratio 1 is the coupling) that drives an axis through its nut (transmission::BallScrew; checks screw-speed, screw-dn, screw-buckling, screw-static, screw-life). Its signals and checks are named by its motor: screw.<motor>.speed, joint.<motor>.force.",
316 &[
317 ID,
318 field("gearbox", Kind::Ref("gearbox"), true, "The gearbox that turns it."),
319 field(
320 "axis",
321 Kind::Ref("axis"),
322 true,
323 "The axis its nut drives; one screw, rack, linear motor or rotary per axis.",
324 ),
325 field(
326 "values",
327 Kind::Table,
328 true,
329 "The table of its values, laid out as [screw] of the registered screw axis (lead, diameters, length, mounting, efficiency, nut and bearing stiffness, preload, load ratings).",
330 ),
331 POS,
332 ],
333 ),
334 (
335 "rack",
336 "A pinion on a gearbox's output that drives an axis along a rack (transmission::RackPinion; check rack-feed-force on rack.<motor>.feed_force).",
337 &[
338 ID,
339 field("gearbox", Kind::Ref("gearbox"), true, "The gearbox that turns the pinion."),
340 field(
341 "axis",
342 Kind::Ref("axis"),
343 true,
344 "The axis it drives; one screw, rack, linear motor or rotary per axis.",
345 ),
346 field(
347 "values",
348 Kind::Table,
349 true,
350 "The table of its values, laid out as [rack] of the registered rack axis (module, teeth, helix angle, efficiency, stiffness, backlash, pinion inertia, rated feed force).",
351 ),
352 POS,
353 ],
354 ),
355 (
356 "linear_motor",
357 "An ironcore linear motor that drives an axis with no transmission (transmission::LinearMotor). Its motor's values read in N for N m and m for rad ([motor.<id>]: force constant in N/A, the forcer's mass as rotor_inertia_kgm2); its gearbox values ([gearbox.<id>], ratio 1) are the forcer's mounting.",
358 &[
359 ID,
360 field("motor", Kind::Ref("motor"), true, "The motor it is; that motor has no gearbox node."),
361 field(
362 "axis",
363 Kind::Ref("axis"),
364 true,
365 "The axis it drives; one screw, rack, linear motor or rotary per axis.",
366 ),
367 field(
368 "values",
369 Kind::Table,
370 true,
371 "The table of its values, laid out as [linear_motor] of the registered linear motor axis (attraction force, pole pitch, guide friction coefficient).",
372 ),
373 POS,
374 ],
375 ),
376 (
377 "rotary",
378 "A rotary table or joint on a gearbox's output: its axis turns, in rad. With strain_wave the gearbox is a strain wave gear (check strain-wave-life on strain_wave.<motor>.damage_rate).",
379 &[
380 ID,
381 field("gearbox", Kind::Ref("gearbox"), true, "The gearbox that turns it."),
382 field(
383 "axis",
384 Kind::Ref("axis"),
385 true,
386 "The axis it turns, which has stroke_rad; bodies that move with it ride round on it (offset_m).",
387 ),
388 field("inertia_kgm2", Kind::Number, true, "Inertia it turns, kg m^2."),
389 field(
390 "payload_inertia_kgm2",
391 Kind::Number,
392 false,
393 "Inertia of its payload while effects.payload is on and the payload is attached, kg m^2.",
394 ),
395 field(
396 "friction_coulomb_nm",
397 Kind::Number,
398 false,
399 "Its bearing's Coulomb friction at the axis, N m, while effects.guide_friction is on. Default 0.",
400 ),
401 field(
402 "friction_viscous_nm_s_rad",
403 Kind::Number,
404 false,
405 "Its bearing's viscous friction at the axis, N m s/rad, while effects.guide_friction is on. Default 0.",
406 ),
407 field(
408 "strain_wave",
409 Kind::Table,
410 false,
411 "The table of the strain wave gear's life values, laid out as [strain_wave] of the registered rotary table.",
412 ),
413 POS,
414 ],
415 ),
416 (
417 "linkage",
418 "A parallel linkage of driven arms, each with a pair of forearms (a parallelogram) down to a plate that keeps its orientation. Two arms (crate sim-netlist, linkage.rs): in the vertical x-z plane, one at each side of the base (the planar delta); the tool is the plate's centre, x and z. Three arms (spatial.rs): at 0, 120 and 240 degrees round the base (the spatial delta); the tool is x, y and z. A file with a linkage has as many axes as arms (no stroke: the working range below sets their range), one motor per arm, a gearbox on each and the linkage; nothing else, and no belt effect on. The arms' joints read [joint] (bearing friction, stops), each motor its drive train as everywhere.",
419 &[
420 ID,
421 field(
422 "arms",
423 Kind::Refs("gearbox"),
424 true,
425 "The gearboxes that turn the arms: two (the first the arm at +x, the second the one at -x) or three (at 0, 120 and 240 degrees from +x).",
426 ),
427 field(
428 "axes",
429 Kind::Refs("axis"),
430 true,
431 "The tool's axes, as many as the arms: across (x), with three arms y, then up (z), from the shoulders' plane.",
432 ),
433 field("base_radius_m", Kind::Number, true, "Shoulder axis from the centre, m."),
434 field("platform_radius_m", Kind::Number, true, "Forearms' joints on the plate from its centre, m."),
435 field("upper_arm_m", Kind::Number, true, "Upper arm, shoulder to elbow, m."),
436 field("forearm_m", Kind::Number, true, "Forearm, elbow to plate, m; longer than the upper arm."),
437 field(
438 "forearm_spacing_m",
439 Kind::Number,
440 false,
441 "Distance between the two rods of a forearm pair, m; the 3D view only. Default 0.",
442 ),
443 field("upper_arm_kg", Kind::Number, true, "Upper arm's tube, kg."),
444 field("upper_arm_cg_m", Kind::Number, true, "Its centre of mass from the shoulder axis, m."),
445 field("upper_arm_inertia_kgm2", Kind::Number, true, "Its inertia about the shoulder axis, kg m^2."),
446 field("elbow_kg", Kind::Number, true, "Elbow block at the arm's end, kg."),
447 field("forearm_pair_kg", Kind::Number, true, "One forearm pair, kg."),
448 field(
449 "forearm_elbow_share",
450 Kind::Number,
451 true,
452 "Share of a forearm pair's mass counted at the elbow, the rest at the plate, 0 to 1.",
453 ),
454 field("platform_kg", Kind::Number, true, "Plate, kg."),
455 field(
456 "payload_kg",
457 Kind::Number,
458 false,
459 "Payload at the plate while effects.payload is on and the payload is attached, kg. Default 0.",
460 ),
461 field("half_width_m", Kind::Number, false, "Two arms: the working range's half width, m. Required there."),
462 field(
463 "radius_m",
464 Kind::Number,
465 false,
466 "Three arms: the working range's radius (a cylinder about z), m. Required there.",
467 ),
468 field(
469 "forearm_rod_spin_inertia_kgm2",
470 Kind::Number,
471 false,
472 "Three arms, effects.forearm_inertia: each rod's inertia about its own axis, kg m^2. Default 0.",
473 ),
474 field(
475 "bending_stiffness_nm_rad",
476 Kind::Number,
477 false,
478 "Three arms, effects.link_elasticity: an upper arm's bending in the plane it turns in, as a turn of the elbow, N m/rad. Required with three arms.",
479 ),
480 field("bending_damping_nm_s_rad", Kind::Number, false, "Its damping, N m s/rad. Default 0."),
481 field(
482 "lateral_stiffness_n_m",
483 Kind::Number,
484 false,
485 "Three arms, effects.link_elasticity: the elbow's move along its axis, out of the arm's plane, N/m. Required with three arms.",
486 ),
487 field("lateral_damping_n_s_m", Kind::Number, false, "Its damping, N s/m. Default 0."),
488 field("top_z_m", Kind::Number, true, "Working range: its top, z, m (below 0: under the shoulders)."),
489 field("height_edge_m", Kind::Number, true, "Working range: its height at the edges, m."),
490 field(
491 "height_centre_m",
492 Kind::Number,
493 true,
494 "Working range: its height at the centre, m; the bottom is an arc (two arms) or a sphere's cap (three) through the edges and the centre.",
495 ),
496 field(
497 "max_condition_number",
498 Kind::Number,
499 true,
500 "Targets where the Jacobian's condition number is above this are refused (near a singularity).",
501 ),
502 POS,
503 ],
504 ),
505 (
506 "scissor",
507 "A scissor lift (crate sim-netlist, scissor.rs): stages of crossed arm pairs on the base, a screw turned by the gearbox's output pulling the sliding foot of the lowest stage towards the fixed one; the tool is the platform's height. A file with a scissor lift has one axis (no stroke: min_height_m and max_height_m set its range), one motor, its gearbox and the scissor; nothing else, and no belt effect on.",
508 &[
509 ID,
510 field("gearbox", Kind::Ref("gearbox"), true, "The gearbox that turns the screw."),
511 field("axis", Kind::Ref("axis"), true, "The platform's height."),
512 field("stages", Kind::Number, true, "Stages of crossed arms, a whole number."),
513 field("arm_m", Kind::Number, true, "An arm from pin to pin, m."),
514 field("lead_m", Kind::Number, true, "The screw's lead: the foot moves this far per turn, m."),
515 field("min_height_m", Kind::Number, true, "The platform's lowest height, above 0, m."),
516 field("max_height_m", Kind::Number, true, "Its highest, below stages times arm_m, m."),
517 field("arms_kg", Kind::Number, true, "All the arms together, kg."),
518 field("platform_kg", Kind::Number, true, "The platform, kg."),
519 field(
520 "payload_kg",
521 Kind::Number,
522 false,
523 "Payload on the platform while effects.payload is on and the payload is attached, kg. Default 0.",
524 ),
525 field(
526 "screw_efficiency",
527 Kind::Number,
528 false,
529 "The screw's efficiency, with effects.gearbox_efficiency; above 0, at most 1. Default 1.",
530 ),
531 field("screw_inertia_kgm2", Kind::Number, false, "The screw's inertia about its axis, kg m^2. Default 0."),
532 POS,
533 ],
534 ),
535 (
536 "lean",
537 "A body leaning on its carriage along a horizontal axis (effects.tool_flex, elastic model only): its centre of mass moves sideways by u against the guide, which gives way sideways and in tilt, and the tool tip below it moves with it. At most one.",
538 &[
539 ID,
540 field("body", Kind::Ref("body"), true, "The body that leans; it moves with axis."),
541 field("axis", Kind::Ref("axis"), true, "The horizontal axis it leans along."),
542 field("com_drop_m", Kind::Number, true, "Its centre of mass below the guide with lever_axis at 0, m."),
543 field("tool_drop_m", Kind::Number, true, "The tool tip below the guide with lever_axis at 0, m."),
544 field(
545 "lever_axis",
546 Kind::Ref("axis"),
547 false,
548 "An axis whose travel raises both towards the guide (shortens the lever).",
549 ),
550 field("lateral_stiffness_n_m", Kind::Number, true, "The guide's stiffness sideways, N/m."),
551 field("tilt_stiffness_nm_rad", Kind::Number, true, "The guide's stiffness in tilt, N m/rad."),
552 field("damping_n_s_m", Kind::Number, true, "The damping of the lean at the centre of mass, N s/m."),
553 field(
554 "belt_offset_m",
555 Kind::Number,
556 false,
557 "With effects.belt_run_offset: how far the belt's runs that reach the body from above meet it to either side of its line (the side their other wheel is on), m; as the guide tilts the body they get longer and shorter by it times the tilt. Default 0.",
558 ),
559 POS,
560 ],
561 ),
562 (
563 "worm",
564 "A worm gear: the gearbox it names is a worm stage of this ratio, which loses by its forward efficiency while the motor drives and by its back efficiency while the load drives it back; with a back efficiency of 0 or less it locks itself. The efficiencies count with effects.gearbox_efficiency on.",
565 &[
566 ID,
567 field("gearbox", Kind::Ref("gearbox"), true, "The gearbox that is the worm stage; one worm per gearbox."),
568 field("ratio", Kind::Number, true, "Its ratio (wheel teeth per worm start), in place of the gearbox's."),
569 field("efficiency", Kind::Number, true, "Driven by the worm, above 0 and at most 1."),
570 field(
571 "back_efficiency",
572 Kind::Number,
573 true,
574 "Driven back by the wheel, at most 1; 0 or less locks itself.",
575 ),
576 POS,
577 ],
578 ),
579 (
580 "gantry",
581 "A gantry's bridge that yaws (racks) about a vertical axis while it travels along a horizontal axis (effects.gantry_yaw): its two sides run apart by width times the yaw angle, which its joints and guides hold with a spring. Bodies that move with its axis and along the bridge (across) weigh on the side they are nearer; screws, racks and linear motors at its sides (drives) and belt sections that pull its ends (sections) turn it. Two drives on its axis make a dual-drive gantry, one motor more than axes; each follows the axis's setpoint. Signals gantry.<id>.yaw, .sync_error, .moment; check gantry-sync. At most one.",
582 &[
583 ID,
584 field("axis", Kind::Ref("axis"), true, "The horizontal straight axis the bridge travels along."),
585 field(
586 "across",
587 Kind::Ref("axis"),
588 false,
589 "The straight axis along the bridge, whose bodies' lever about the bridge's centre changes with it.",
590 ),
591 field("width_m", Kind::Number, true, "Distance between the bridge's two sides (its guides), m."),
592 field(
593 "across_start_m",
594 Kind::Number,
595 false,
596 "Where across is at 0, from the bridge's first side, m; default with across's stroke in the middle.",
597 ),
598 field(
599 "inertia_kgm2",
600 Kind::Number,
601 true,
602 "The bridge's own inertia about a vertical axis through its centre, without the bodies that move across, kg m^2.",
603 ),
604 field(
605 "stiffness_nm_rad",
606 Kind::Number,
607 true,
608 "What holds the yaw beside the drives and belts: the joints of the bridge on its carriages and their guides, N m/rad.",
609 ),
610 field("damping_nm_s_rad", Kind::Number, true, "Damping of the yaw, N m s/rad."),
611 field(
612 "drives",
613 Kind::Coefficients("motor"),
614 false,
615 "Per motor whose screw, rack or linear motor drives axis: where it acts across the bridge, from its centre, m (negative towards the first side).",
616 ),
617 field(
618 "sections",
619 Kind::Coefficients("section"),
620 false,
621 "Per belt section that pulls the bridge's ends along axis: how much longer it gets per rad of yaw, m (its pull along axis times the end's place across, from the centre).",
622 ),
623 field(
624 "tolerance_m",
625 Kind::Number,
626 false,
627 "The largest synchronisation error (width times yaw) the check gantry-sync allows, m; no check without it.",
628 ),
629 POS,
630 ],
631 ),
632 (
633 "tcp",
634 "The tool centre point of a tool carried by rotary axes (a head), of a workpiece on a rotary table, or both (table/table, head/table): the tool's coordinates of the three straight axes are where its tip is on the workpiece, not where the axes stand, so the tip follows the path while the rotaries turn and the straight axes make up for them. At most one.",
635 &[
636 ID,
637 field(
638 "axes",
639 Kind::Refs("axis"),
640 true,
641 "The three straight axes along x (the first axis of the file), y (horizontal) and z (vertical), in that order.",
642 ),
643 field(
644 "rotaries",
645 Kind::Refs("axis"),
646 false,
647 "The rotary axes that carry the tool (a head), outermost first; none for a table/table machine.",
648 ),
649 field(
650 "table",
651 Kind::Refs("axis"),
652 false,
653 "The rotary axes that carry the workpiece (a rotary or tilting table), outermost first: the tool's x, y and z are the tip's on the workpiece, which they turn. None for a head alone.",
654 ),
655 field(
656 "table_pivot_m",
657 Kind::Point,
658 false,
659 "With table: where the table's rotary axes meet, in the straight axes' coordinates (where they stand at 0), m; [0, 0, 0] if left out.",
660 ),
661 field(
662 "tool_m",
663 Kind::Point,
664 true,
665 "The tool's tip from the point the rotaries' axes meet, [x, y, z] at angle 0, m.",
666 ),
667 POS,
668 ],
669 ),
670 (
671 "cylinder",
672 "A double-acting pneumatic cylinder at the tool, moved by its directional valve and not by a drive (sim_components::pneumatic; checks cushion-energy, load-factor). It is no tool axis: the cycle commands its valve (a segment's valves = { <id> = \"extend\" }) and waits for its end-position sensors (wait = [\"<id>.extended\"]). Its signals are cylinder.<id>.*; its weight belongs in the body of the axis that carries it.",
673 &[
674 ID,
675 field("key", Kind::Key, false, "Translation key of its name; default cylinder."),
676 field(
677 "values",
678 Kind::Table,
679 true,
680 "The table of its values (bore, stroke, valve, throttles, cushions, seals; see docs/config-reference.md).",
681 ),
682 POS,
683 ],
684 ),
685];
686
687pub fn cylinders(cfg: &Config) -> Result<Vec<sim_components::pneumatic::CylinderNode>> {
689 let Ok(Value::Array(nodes)) = cfg.get("machine.cylinder") else { return Ok(Vec::new()) };
690 nodes
691 .iter()
692 .map(|node| {
693 let field = |name: &str| node.get(name).and_then(Value::as_str);
694 let id = field("id").ok_or_else(|| ConfigError::Missing("machine.cylinder.id".into()))?;
695 let values =
696 field("values").ok_or_else(|| ConfigError::Missing(format!("machine.cylinder[{id}].values")))?;
697 if !cfg.get(values).is_ok_and(Value::is_table) {
698 return Err(ConfigError::Missing(format!("machine.cylinder[{id}].values = \"{values}\"")));
699 }
700 Ok(sim_components::pneumatic::CylinderNode {
701 id: id.into(),
702 key: field("key").unwrap_or("cylinder").into(),
703 values: values.into(),
704 })
705 })
706 .collect()
707}
708
709pub struct AxisNode {
710 pub id: String,
711 pub key: String,
712 pub stroke: f64,
713 pub incline_deg: f64,
714 pub cable_chain: bool,
715 pub rotary: bool,
717}
718
719pub enum Transmission {
722 Belt,
723 Screw {
724 values: String,
725 },
726 Rack {
727 values: String,
728 },
729 LinearMotor {
730 values: String,
731 },
732 Rotary {
734 inertia: f64,
735 payload: f64,
736 strain_wave: Option<String>,
737 bearing: [f64; 2],
738 },
739}
740
741pub struct MotorNode {
742 pub id: String,
743 pub key: String,
744 pub radius: f64,
746 pub inertia: f64,
747 pub pulley: String,
748 pub at: Option<[f64; 3]>,
749 pub body: Option<usize>,
751 pub clockwise: bool,
753 pub transmission: Transmission,
754 pub axis: Option<usize>,
756 pub worm: Option<WormNode>,
758}
759
760#[derive(Debug, Clone, Copy, PartialEq)]
762pub struct WormNode {
763 pub ratio: f64,
764 pub efficiency: f64,
765 pub back_efficiency: f64,
766}
767
768#[derive(Debug, Clone, Copy, PartialEq)]
770pub struct LeanNode {
771 pub body: usize,
772 pub axis: usize,
773 pub com_drop: f64,
774 pub tool_drop: f64,
775 pub lever_axis: Option<usize>,
776 pub lateral: f64,
777 pub tilt: f64,
778 pub damping: f64,
779 pub belt_offset: f64,
782}
783
784pub struct SectionNode {
785 pub id: String,
786 pub key: String,
787 pub length: f64,
788 pub axes: Vec<f64>,
790 pub pulleys: Vec<f64>,
791 pub route: Vec<Waypoint>,
793 pub plane: Option<[usize; 3]>,
796}
797
798#[derive(Debug, Clone, Copy, PartialEq)]
800pub enum Waypoint {
801 Pulley(usize),
803 Idler(usize),
804 Body(usize),
805}
806
807pub struct IdlerNode {
808 pub id: String,
809 pub speed: Vec<f64>,
810 pub radius: f64,
811 pub inertia: f64,
812 pub friction: f64,
813 pub body: Option<usize>,
814 pub at: Option<[f64; 3]>,
815 pub clockwise: bool,
816}
817
818pub struct FrameNode {
819 pub axis: usize,
820 pub mass: f64,
821 pub stiffness: f64,
822 pub damping: f64,
823}
824
825pub struct SpanNode {
826 pub id: String,
827 pub section: usize,
828 pub length: f64,
829 pub axes: Vec<f64>,
830 pub velocity: Option<[Vec<f64>; 3]>,
832 pub yaw_lever: Option<(f64, Vec<f64>)>,
835}
836
837pub struct BodyNode {
838 pub id: String,
839 pub mass: f64,
840 pub payload: f64,
841 pub axes: Vec<bool>,
842 pub rotaries: Vec<usize>,
844 pub offset: [f64; 3],
845}
846
847#[derive(Debug, Clone, PartialEq)]
849pub struct GantryNode {
850 pub id: String,
851 pub axis: usize,
852 pub across: Option<usize>,
853 pub width: f64,
854 pub across_shift: f64,
856 pub inertia: f64,
857 pub stiffness: f64,
858 pub damping: f64,
859 pub drives: Vec<Option<f64>>,
861 pub sections: Vec<f64>,
863 pub tolerance: Option<f64>,
864}
865
866#[derive(Debug, Clone, PartialEq)]
868pub struct TcpNode {
869 pub axes: [usize; 3],
871 pub rotaries: Vec<usize>,
872 pub tool: [f64; 3],
873 pub table: Vec<usize>,
875 pub pivot: [f64; 3],
876}
877
878pub struct Overhang {
879 pub body: usize,
880 pub axis: usize,
881 pub lever: f64,
882 pub lever_axis: Option<usize>,
883 pub spacing: f64,
884 pub side_load: bool,
885}
886
887pub struct GuideNode {
888 pub id: String,
889 pub axis: usize,
890 pub friction: String,
891 pub carries: Vec<usize>,
892 pub overhang: Option<Overhang>,
893}
894
895pub struct Netlist {
897 pub axes: Vec<AxisNode>,
898 pub motors: Vec<MotorNode>,
899 pub sections: Vec<SectionNode>,
900 pub bodies: Vec<BodyNode>,
901 pub guides: Vec<GuideNode>,
902 pub idlers: Vec<IdlerNode>,
903 pub frame: Option<FrameNode>,
904 pub spans: Vec<SpanNode>,
905 pub lean: Option<LeanNode>,
906 pub gantry: Option<GantryNode>,
907 pub tcp: Option<TcpNode>,
908 pub refs: Vec<String>,
910 pub values: Vec<(&'static str, String)>,
913 pub linkage: Option<crate::linkage::LinkageNode>,
916 pub scissor: Option<crate::scissor::ScissorNode>,
918}
919
920pub(crate) struct Node<'a> {
923 pub(crate) table: &'a Table,
924 pub(crate) path: String,
925}
926
927impl Node<'_> {
928 pub(crate) fn at(&self, name: &str) -> String {
929 format!("{}.{name}", self.path)
930 }
931 pub(crate) fn get(&self, name: &str) -> Option<&Value> {
932 self.table.get(name)
933 }
934 fn required(&self, name: &str) -> Result<&Value> {
935 self.get(name).ok_or_else(|| ConfigError::Missing(self.at(name)))
936 }
937 pub(crate) fn text(&self, name: &str) -> Result<Option<&str>> {
938 self.get(name).map(|v| v.as_str().ok_or_else(|| ConfigError::Type(self.at(name)))).transpose()
939 }
940 fn bool(&self, name: &str) -> Result<bool> {
941 self.get(name).map_or(Ok(false), |v| v.as_bool().ok_or_else(|| ConfigError::Type(self.at(name))))
942 }
943 fn point(&self, cfg: &Config, name: &str, refs: &mut Vec<String>) -> Result<Option<[f64; 3]>> {
945 let Some(value) = self.get(name) else { return Ok(None) };
946 let Some([x, y, z]) = value.as_array().map(Vec::as_slice) else {
947 return Err(ConfigError::Type(self.at(name)));
948 };
949 let mut at = |v: &Value| number(cfg, v, &self.at(name), refs);
950 Ok(Some([at(x)?, at(y)?, at(z)?]))
951 }
952 pub(crate) fn id_list(&self, name: &str) -> Result<Vec<&str>> {
953 let Some(value) = self.get(name) else { return Ok(Vec::new()) };
954 let err = || ConfigError::Type(self.at(name));
955 value.as_array().ok_or_else(err)?.iter().map(|v| v.as_str().ok_or_else(err)).collect()
956 }
957}
958
959pub(crate) fn number(cfg: &Config, value: &Value, at: &str, refs: &mut Vec<String>) -> Result<f64> {
961 match value {
962 Value::Float(f) => sim_core::config::number(*f, at),
963 Value::Integer(i) => sim_core::config::number(*i as f64, at),
964 Value::String(path) => {
965 let v = cfg.f64(path).map_err(|e| match e {
966 ConfigError::Missing(_) => ConfigError::Missing(format!("{at} = \"{path}\"")),
967 other => other,
968 })?;
969 refs.push(path.clone());
970 Ok(v)
971 }
972 _ => Err(ConfigError::Type(at.into())),
973 }
974}
975
976fn valid_id(id: &str) -> bool {
977 !id.is_empty() && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
978}
979
980impl Netlist {
981 pub fn parse(cfg: &Config) -> Result<Self> {
982 let machine = cfg.get("machine")?.as_table().ok_or_else(|| ConfigError::Type("machine".into()))?;
983 match machine.get("version").map(Value::as_integer) {
984 Some(Some(VERSION)) => {}
985 Some(_) => return Err(ConfigError::Version("machine.version".into())),
986 None => return Err(ConfigError::Missing("machine.version".into())),
987 }
988 for (key, _) in machine {
989 if !["version", "id", "name"].contains(&key.as_str()) && !NODES.iter().any(|(list, ..)| list == key) {
990 return Err(ConfigError::Unknown(format!("machine.{key}")));
991 }
992 }
993 let mut lists: Vec<Vec<Node>> = Vec::new();
995 let mut ids: Vec<String> = Vec::new();
996 let none = Vec::new();
997 for (list, _, fields) in NODES {
998 let mut nodes = Vec::new();
999 let items = match machine.get(*list) {
1000 None => &none,
1001 Some(v) => v.as_array().ok_or_else(|| ConfigError::Type(format!("machine.{list}")))?,
1002 };
1003 for (n, item) in items.iter().enumerate() {
1004 let table = item.as_table().ok_or_else(|| ConfigError::Type(format!("machine.{list}[#{}]", n + 1)))?;
1005 let mut node = Node { table, path: format!("machine.{list}[#{}]", n + 1) };
1006 let id = node.required("id")?.as_str().ok_or_else(|| ConfigError::Type(node.at("id")))?;
1007 if !valid_id(id) {
1008 return Err(ConfigError::Invalid(format!(
1009 "{} = \"{id}\" (letters, digits, _ and - only)",
1010 node.at("id")
1011 )));
1012 }
1013 if ids.iter().any(|known| known == id) {
1014 return Err(ConfigError::Invalid(format!(
1015 "{} = \"{id}\" (another node has this id)",
1016 node.at("id")
1017 )));
1018 }
1019 ids.push(id.into());
1020 node.path = format!("machine.{list}[{id}]");
1021 for key in table.keys() {
1022 if !fields.iter().any(|f| f.name == key) {
1023 return Err(ConfigError::Unknown(node.at(key)));
1024 }
1025 }
1026 for f in fields.iter().filter(|f| f.required) {
1027 node.required(f.name)?;
1028 }
1029 if let Some(pos) = node.get("pos") {
1030 let ok = pos
1031 .as_array()
1032 .is_some_and(|p| p.len() == 2 && p.iter().all(|v| v.is_float() || v.is_integer()));
1033 if !ok {
1034 return Err(ConfigError::Type(node.at("pos")));
1035 }
1036 }
1037 for f in fields.iter() {
1039 let Some(value) = node.get(f.name) else { continue };
1040 let ok = match f.kind {
1041 Kind::Id | Kind::Key | Kind::Table | Kind::Ref(_) => value.is_str(),
1042 Kind::Choice(words) => value.as_str().is_some_and(|w| words.contains(&w)),
1043 Kind::Bool => value.is_bool(),
1044 Kind::Refs(_) | Kind::Route(_) => value.is_array(),
1045 _ => true,
1046 };
1047 if !ok {
1048 return Err(ConfigError::Type(node.at(f.name)));
1049 }
1050 }
1051 nodes.push(node);
1052 }
1053 lists.push(nodes);
1054 }
1055 let mut take = |list: &str| {
1057 let at = NODES.iter().position(|(name, ..)| *name == list).expect("a list of NODES");
1058 std::mem::take(&mut lists[at])
1059 };
1060 let (axes, motors, gearboxes, pulleys, sections) =
1061 (take("axis"), take("motor"), take("gearbox"), take("pulley"), take("section"));
1062 let (bodies, guides, idlers, frames, spans) =
1063 (take("body"), take("guide"), take("idler"), take("frame"), take("span"));
1064 let (screws, racks, linears, rotaries) = (take("screw"), take("rack"), take("linear_motor"), take("rotary"));
1065 let (leans, worms, linkages, scissors) = (take("lean"), take("worm"), take("linkage"), take("scissor"));
1066 let (gantries, tcps) = (take("gantry"), take("tcp"));
1067 for (list, nodes) in [("axis", &axes), ("motor", &motors)] {
1069 if nodes.is_empty() {
1070 return Err(ConfigError::Missing(format!("machine.{list}")));
1071 }
1072 }
1073 for (key, check) in [("id", true), ("name", false)] {
1074 match machine.get(key) {
1075 None => {}
1076 Some(Value::String(text)) if !check || valid_id(text) => {}
1077 Some(Value::String(_)) => {
1078 return Err(ConfigError::Invalid(format!("machine.{key} (letters, digits, _ and - only)")));
1079 }
1080 Some(_) => return Err(ConfigError::Type(format!("machine.{key}"))),
1081 }
1082 }
1083 if !scissors.is_empty() {
1084 let others = [
1085 &pulleys, §ions, &bodies, &guides, &idlers, &frames, &spans, &screws, &racks, &linears, &rotaries,
1086 &leans, &worms, &linkages,
1087 ];
1088 return crate::scissor::read(cfg, &axes, &motors, &gearboxes, &scissors, &others.map(|n| &n[..]));
1089 }
1090 if !linkages.is_empty() {
1091 let others = [
1092 &pulleys, §ions, &bodies, &guides, &idlers, &frames, &spans, &screws, &racks, &linears, &rotaries,
1093 &leans, &worms, &gantries, &tcps,
1094 ];
1095 return crate::linkage::read(cfg, &axes, &motors, &gearboxes, &linkages, &others.map(|n| &n[..]));
1096 }
1097 let id_of = |node: &Node| node.table["id"].as_str().unwrap_or_default().to_string();
1098 let find = |nodes: &[Node], node: &Node, name: &str, id: &str| -> Result<usize> {
1100 nodes
1101 .iter()
1102 .position(|n| n.table["id"].as_str() == Some(id))
1103 .ok_or_else(|| ConfigError::Invalid(format!("{}.{name} = \"{id}\"", node.path)))
1104 };
1105 let mut refs = Vec::new();
1106
1107 let turned: Vec<&str> = rotaries.iter().filter_map(|r| r.table.get("axis").and_then(Value::as_str)).collect();
1109 let mut axis_nodes = Vec::new();
1110 for node in &axes {
1111 let id = id_of(node);
1112 let rotary = turned.contains(&id.as_str());
1113 let incline = node
1114 .get("incline_deg")
1115 .map(|v| number(cfg, v, &node.at("incline_deg"), &mut refs))
1116 .transpose()?
1117 .unwrap_or(0.0);
1118 let (stroke_field, other) = if rotary { ("stroke_rad", "stroke_m") } else { ("stroke_m", "stroke_rad") };
1119 if node.get(other).is_some() {
1120 return Err(ConfigError::Invalid(format!(
1121 "{} (a rotary axis has stroke_rad, any other stroke_m)",
1122 node.at(other)
1123 )));
1124 }
1125 let stroke = number(cfg, node.required(stroke_field)?, &node.at(stroke_field), &mut refs)?;
1126 if stroke <= 0.0 {
1127 return Err(ConfigError::Invalid(node.at(stroke_field)));
1128 }
1129 if rotary && node.bool("cable_chain")? {
1131 return Err(ConfigError::Invalid(format!("{} (not on a rotary axis)", node.at("cable_chain"))));
1132 }
1133 let key = node.text("key")?.map_or_else(|| format!("axis-{id}"), str::to_string);
1134 axis_nodes.push(AxisNode {
1135 id,
1136 key,
1137 stroke,
1138 incline_deg: incline,
1139 cable_chain: node.bool("cable_chain")?,
1140 rotary,
1141 });
1142 }
1143
1144 let refers = |nodes: &[Node], field: &str, to: &str| -> Vec<usize> {
1147 (0..nodes.len()).filter(|&i| nodes[i].table.get(field).and_then(Value::as_str) == Some(to)).collect()
1148 };
1149 let table_path = |node: &Node, name: &str| -> Result<String> {
1151 let path = node.required(name)?.as_str().ok_or_else(|| ConfigError::Type(node.at(name)))?;
1152 if !cfg.get(path).is_ok_and(Value::is_table) {
1153 return Err(ConfigError::Missing(format!("{} = \"{path}\"", node.at(name))));
1154 }
1155 Ok(path.to_string())
1156 };
1157 let mut motor_nodes = Vec::new();
1158 let mut values = Vec::new();
1159 let mut driven: Vec<Option<(String, String)>> = vec![None; axis_nodes.len()];
1161 let sides: Vec<String> = gantries
1163 .first()
1164 .and_then(|g| g.get("drives"))
1165 .and_then(Value::as_table)
1166 .map_or_else(Vec::new, |t| t.keys().cloned().collect());
1167 for motor in &motors {
1168 let id = id_of(motor);
1169 let key = motor.text("key")?.map_or_else(|| format!("motor-{id}"), str::to_string);
1170 let mut worm = None;
1171 let (node, transmission) =
1172 match (&refers(&gearboxes, "motor", &id)[..], &refers(&linears, "motor", &id)[..]) {
1173 ([], [l]) => {
1174 (&linears[*l], Transmission::LinearMotor { values: table_path(&linears[*l], "values")? })
1175 }
1176 ([g], []) => {
1177 let gearbox = &gearboxes[*g];
1178 let gearbox_id = id_of(gearbox);
1179 worm = worm_node(cfg, &worms, &gearbox_id, &mut refs)?;
1180 let outputs: Vec<(usize, usize)> = [&pulleys, &screws, &racks, &rotaries]
1181 .into_iter()
1182 .enumerate()
1183 .flat_map(|(list, nodes)| {
1184 refers(nodes, "gearbox", &gearbox_id).into_iter().map(move |i| (list, i))
1185 })
1186 .collect();
1187 let [(list, i)] = outputs[..] else {
1188 return Err(ConfigError::Invalid(format!(
1189 "{} (one pulley, screw, rack or rotary per gearbox)",
1190 gearbox.path
1191 )));
1192 };
1193 match list {
1194 0 => {
1195 let pulley = &pulleys[i];
1196 let radius =
1197 number(cfg, pulley.required("radius_m")?, &pulley.at("radius_m"), &mut refs)?;
1198 let inertia = number(
1199 cfg,
1200 pulley.required("inertia_kgm2")?,
1201 &pulley.at("inertia_kgm2"),
1202 &mut refs,
1203 )?;
1204 if radius <= 0.0 || inertia <= 0.0 {
1205 return Err(ConfigError::Invalid(pulley.at(if radius <= 0.0 {
1206 "radius_m"
1207 } else {
1208 "inertia_kgm2"
1209 })));
1210 }
1211 motor_nodes.push(MotorNode {
1212 id,
1213 key,
1214 radius,
1215 inertia,
1216 pulley: id_of(pulley),
1217 at: pulley.point(cfg, "at_m", &mut refs)?,
1218 body: pulley
1219 .text("body")?
1220 .map(|id| find(&bodies, pulley, "body", id))
1221 .transpose()?,
1222 clockwise: pulley.bool("clockwise")?,
1223 transmission: Transmission::Belt,
1224 axis: None,
1225 worm,
1226 });
1227 continue;
1228 }
1229 1 => (&screws[i], Transmission::Screw { values: table_path(&screws[i], "values")? }),
1230 2 => (&racks[i], Transmission::Rack { values: table_path(&racks[i], "values")? }),
1231 _ => {
1232 let node = &rotaries[i];
1233 let inertia =
1234 number(cfg, node.required("inertia_kgm2")?, &node.at("inertia_kgm2"), &mut refs)?;
1235 let mut optional = |name: &str| -> Result<f64> {
1236 let v = node
1237 .get(name)
1238 .map(|v| number(cfg, v, &node.at(name), &mut refs))
1239 .transpose()?
1240 .unwrap_or(0.0);
1241 if v < 0.0 { Err(ConfigError::Invalid(node.at(name))) } else { Ok(v) }
1242 };
1243 let payload = optional("payload_inertia_kgm2")?;
1244 let bearing =
1245 [optional("friction_coulomb_nm")?, optional("friction_viscous_nm_s_rad")?];
1246 if inertia <= 0.0 {
1247 return Err(ConfigError::Invalid(node.at("inertia_kgm2")));
1248 }
1249 let strain_wave =
1250 node.get("strain_wave").map(|_| table_path(node, "strain_wave")).transpose()?;
1251 (node, Transmission::Rotary { inertia, payload, strain_wave, bearing })
1252 }
1253 }
1254 }
1255 _ => {
1256 return Err(ConfigError::Invalid(format!(
1257 "{} (one gearbox per motor, or one linear motor)",
1258 motor.path
1259 )));
1260 }
1261 };
1262 let axis = find(&axes, node, "axis", node.text("axis")?.unwrap_or_default())?;
1263 if let Some((other, motor)) = &driven[axis]
1264 && !(sides.contains(motor) && sides.contains(&id))
1265 {
1266 return Err(ConfigError::Invalid(format!(
1267 "{} (one screw, rack, linear motor or rotary per axis, but at a gantry's sides; {other} drives it too)",
1268 node.at("axis")
1269 )));
1270 }
1271 driven[axis] = Some((id_of(node), id.clone()));
1272 match &transmission {
1273 Transmission::Screw { values: v } => values.push(("screw", v.clone())),
1274 Transmission::Rack { values: v } => values.push(("rack", v.clone())),
1275 Transmission::LinearMotor { values: v } => values.push(("linear_motor", v.clone())),
1276 Transmission::Rotary { strain_wave: Some(v), .. } => values.push(("strain_wave", v.clone())),
1277 _ => {}
1278 }
1279 motor_nodes.push(MotorNode {
1280 id,
1281 key,
1282 radius: 1.0,
1283 inertia: 0.0,
1284 pulley: String::new(),
1285 at: None,
1286 body: None,
1287 clockwise: false,
1288 transmission,
1289 axis: Some(axis),
1290 worm,
1291 });
1292 }
1293 for gearbox in &gearboxes {
1294 find(&motors, gearbox, "motor", gearbox.text("motor")?.unwrap_or_default())?;
1295 }
1296 for (nodes, field, targets) in [
1297 (&pulleys, "gearbox", &gearboxes),
1298 (&screws, "gearbox", &gearboxes),
1299 (&racks, "gearbox", &gearboxes),
1300 (&rotaries, "gearbox", &gearboxes),
1301 (&linears, "motor", &motors),
1302 (&worms, "gearbox", &gearboxes),
1303 ] {
1304 for node in nodes {
1305 find(targets, node, field, node.text(field)?.unwrap_or_default())?;
1306 }
1307 }
1308
1309 let mut section_nodes = Vec::new();
1310 for node in §ions {
1311 let id = id_of(node);
1312 let length = number(cfg, node.required("length_m")?, &node.at("length_m"), &mut refs)?;
1313 if length <= 0.0 {
1314 return Err(ConfigError::Invalid(node.at("length_m")));
1315 }
1316 let mut along = vec![0.0; axis_nodes.len()];
1317 let mut fed = vec![0.0; motor_nodes.len()];
1318 for (name, out) in [("axes", &mut along), ("pulleys", &mut fed)] {
1319 let table = node.required(name)?.as_table().ok_or_else(|| ConfigError::Type(node.at(name)))?;
1320 for (target, value) in table {
1321 let at = format!("{}.{target}", node.at(name));
1322 let i = if name == "axes" {
1323 axis_nodes.iter().position(|a| &a.id == target)
1324 } else {
1325 motor_nodes.iter().position(|m| &m.pulley == target)
1326 };
1327 let i = i.ok_or_else(|| ConfigError::Invalid(at.clone()))?;
1328 out[i] = number(cfg, value, &at, &mut refs)?;
1329 if name == "pulleys" && out[i].abs() != 1.0 {
1331 return Err(ConfigError::Invalid(at));
1332 }
1333 }
1334 }
1335 let key = node.text("key")?.map_or_else(|| format!("belt-section-{id}"), str::to_string);
1336 let mut route = Vec::new();
1337 for target in node.id_list("route")? {
1338 let found = motor_nodes.iter().position(|m| m.pulley == target).map(Waypoint::Pulley);
1339 let found = found.or_else(|| {
1340 idlers.iter().position(|n| n.table["id"].as_str() == Some(target)).map(Waypoint::Idler)
1341 });
1342 let found = found
1343 .or_else(|| bodies.iter().position(|n| n.table["id"].as_str() == Some(target)).map(Waypoint::Body));
1344 route.push(found.ok_or_else(|| ConfigError::Invalid(format!("{} = \"{target}\"", node.at("route"))))?);
1345 }
1346 let plane = match node.text("plane")? {
1347 None => None,
1348 Some("x-z") => Some([0, 2, 1]),
1349 Some("x-y") => Some([0, 1, 2]),
1350 Some("y-z") => Some([1, 2, 0]),
1351 Some(_) => return Err(ConfigError::Invalid(node.at("plane"))),
1352 };
1353 let wheels = |pulleys: &[f64], route: &[Waypoint]| -> Vec<Waypoint> {
1355 let fed = (0..pulleys.len()).filter(|&kk| pulleys[kk] != 0.0).map(Waypoint::Pulley);
1356 fed.chain(route.iter().copied().filter(|w| !matches!(w, Waypoint::Body(_)))).collect()
1357 };
1358 let mine = wheels(&fed, &route);
1359 if let Some(other) = section_nodes.iter().find(|o: &&SectionNode| {
1360 o.plane != plane && wheels(&o.pulleys, &o.route).iter().any(|w| mine.contains(w))
1361 }) {
1362 return Err(ConfigError::Invalid(format!(
1363 "{} (a wheel it shares with section {} turns in one plane)",
1364 node.at("plane"),
1365 other.id
1366 )));
1367 }
1368 section_nodes.push(SectionNode { id, key, length, axes: along, pulleys: fed, route, plane });
1369 }
1370 let coefficients = |node: &Node, name: &str, refs: &mut Vec<String>| -> Result<Vec<f64>> {
1372 let mut out = vec![0.0; axis_nodes.len()];
1373 let Some(value) = node.get(name) else { return Ok(out) };
1374 for (target, value) in value.as_table().ok_or_else(|| ConfigError::Type(node.at(name)))? {
1375 let at = format!("{}.{target}", node.at(name));
1376 let i =
1377 axis_nodes.iter().position(|a| &a.id == target).ok_or_else(|| ConfigError::Invalid(at.clone()))?;
1378 out[i] = number(cfg, value, &at, refs)?;
1379 }
1380 Ok(out)
1381 };
1382
1383 let mut body_nodes = Vec::new();
1384 for node in &bodies {
1385 let mass = number(cfg, node.required("mass_kg")?, &node.at("mass_kg"), &mut refs)?;
1386 let payload = node
1387 .get("payload_kg")
1388 .map(|v| number(cfg, v, &node.at("payload_kg"), &mut refs))
1389 .transpose()?
1390 .unwrap_or(0.0);
1391 if mass <= 0.0 || payload < 0.0 {
1392 return Err(ConfigError::Invalid(node.at(if mass <= 0.0 { "mass_kg" } else { "payload_kg" })));
1393 }
1394 let mut moves = vec![false; axis_nodes.len()];
1395 let mut rotaries = Vec::new();
1396 for id in node.id_list("axes")? {
1397 let i = find(&axes, node, "axes", id)?;
1398 if axis_nodes[i].rotary {
1400 rotaries.push(i);
1401 }
1402 moves[i] = true;
1403 }
1404 if !moves.contains(&true) {
1405 return Err(ConfigError::Missing(node.at("axes")));
1406 }
1407 let offset = node.point(cfg, "offset_m", &mut refs)?.unwrap_or_default();
1408 body_nodes.push(BodyNode { id: id_of(node), mass, payload, axes: moves, rotaries, offset });
1409 }
1410
1411 let mut guide_nodes: Vec<GuideNode> = Vec::new();
1412 for node in &guides {
1413 let axis = find(&axes, node, "axis", node.text("axis")?.unwrap_or_default())?;
1414 if guide_nodes.iter().any(|g| g.axis == axis) {
1415 return Err(ConfigError::Invalid(node.at("axis")));
1416 }
1417 if axis_nodes[axis].rotary {
1419 return Err(ConfigError::Invalid(format!("{} (a rotary axis has no guide)", node.at("axis"))));
1420 }
1421 let friction = node.text("friction")?.unwrap_or_default().to_string();
1422 if !cfg.get(&friction).is_ok_and(Value::is_table) {
1423 return Err(ConfigError::Missing(format!("{} = \"{friction}\"", node.at("friction"))));
1424 }
1425 let carries = node
1426 .id_list("carries")?
1427 .into_iter()
1428 .map(|id| find(&bodies, node, "carries", id))
1429 .collect::<Result<Vec<_>>>()?;
1430 let overhang = match node.text("overhang")? {
1431 None => {
1432 if let Some(extra) = ["overhang_axis", "lever_m", "lever_axis", "spacing_m", "side_load"]
1433 .into_iter()
1434 .find(|f| node.get(f).is_some())
1435 {
1436 return Err(ConfigError::Missing(format!("{} (with {extra})", node.at("overhang"))));
1437 }
1438 None
1439 }
1440 Some(body) => {
1441 let body = find(&bodies, node, "overhang", body)?;
1442 let axis_id = node
1443 .required("overhang_axis")?
1444 .as_str()
1445 .ok_or_else(|| ConfigError::Type(node.at("overhang_axis")))?;
1446 let lever_axis =
1447 node.text("lever_axis")?.map(|id| find(&axes, node, "lever_axis", id)).transpose()?;
1448 let spacing = number(cfg, node.required("spacing_m")?, &node.at("spacing_m"), &mut refs)?;
1449 if spacing <= 0.0 {
1450 return Err(ConfigError::Invalid(node.at("spacing_m")));
1451 }
1452 Some(Overhang {
1453 body,
1454 axis: find(&axes, node, "overhang_axis", axis_id)?,
1455 lever: number(cfg, node.required("lever_m")?, &node.at("lever_m"), &mut refs)?,
1456 lever_axis,
1457 spacing,
1458 side_load: node.bool("side_load")?,
1459 })
1460 }
1461 };
1462 guide_nodes.push(GuideNode { id: id_of(node), axis, friction, carries, overhang });
1463 }
1464
1465 let mut idler_nodes = Vec::new();
1466 for node in &idlers {
1467 let value = |name: &str, refs: &mut Vec<String>| number(cfg, node.required(name)?, &node.at(name), refs);
1468 let (radius, inertia, friction) =
1469 (value("radius_m", &mut refs)?, value("inertia_kgm2", &mut refs)?, value("friction_nm", &mut refs)?);
1470 if radius <= 0.0 || inertia < 0.0 || friction < 0.0 {
1471 return Err(ConfigError::Invalid(node.at(if radius <= 0.0 {
1472 "radius_m"
1473 } else if inertia < 0.0 {
1474 "inertia_kgm2"
1475 } else {
1476 "friction_nm"
1477 })));
1478 }
1479 let speed = coefficients(node, "speed", &mut refs)?;
1480 let body = node.text("body")?.map(|id| find(&bodies, node, "body", id)).transpose()?;
1481 idler_nodes.push(IdlerNode {
1482 id: id_of(node),
1483 speed,
1484 radius,
1485 inertia,
1486 friction,
1487 body,
1488 at: node.point(cfg, "at_m", &mut refs)?,
1489 clockwise: node.bool("clockwise")?,
1490 });
1491 }
1492
1493 let frame = match &frames[..] {
1494 [] => None,
1495 [node] => {
1496 let axis = find(&axes, node, "axis", node.text("axis")?.unwrap_or_default())?;
1497 if axis_nodes[axis].incline_deg != 0.0 || axis_nodes[axis].rotary {
1499 return Err(ConfigError::Invalid(format!(
1500 "{} (the frame sways along a horizontal axis)",
1501 node.at("axis")
1502 )));
1503 }
1504 let value =
1505 |name: &str, refs: &mut Vec<String>| number(cfg, node.required(name)?, &node.at(name), refs);
1506 let (mass, stiffness, damping) = (
1507 value("mass_kg", &mut refs)?,
1508 value("stiffness_n_m", &mut refs)?,
1509 value("damping_n_s_m", &mut refs)?,
1510 );
1511 if mass <= 0.0 || stiffness <= 0.0 || damping < 0.0 {
1512 return Err(ConfigError::Invalid(node.at(if mass <= 0.0 {
1513 "mass_kg"
1514 } else if stiffness <= 0.0 {
1515 "stiffness_n_m"
1516 } else {
1517 "damping_n_s_m"
1518 })));
1519 }
1520 Some(FrameNode { axis, mass, stiffness, damping })
1521 }
1522 [_, second, ..] => return Err(ConfigError::Invalid(format!("{} (one frame at most)", second.path))),
1523 };
1524
1525 let mut span_nodes = Vec::new();
1526 for node in &spans {
1527 let section = find(§ions, node, "section", node.text("section")?.unwrap_or_default())?;
1528 let length = number(cfg, node.required("length_m")?, &node.at("length_m"), &mut refs)?;
1529 if length <= 0.0 {
1530 return Err(ConfigError::Invalid(node.at("length_m")));
1531 }
1532 let named = ["velocity_x", "velocity_y", "velocity_z"];
1533 let velocity = if named.iter().any(|name| node.get(name).is_some()) {
1534 let [x, y, z] = named.map(|name| coefficients(node, name, &mut refs));
1535 Some([x?, y?, z?])
1536 } else {
1537 None
1538 };
1539 let yaw_lever = if node.get("yaw_lever_m").is_some() || node.get("yaw_lever_axes").is_some() {
1540 let constant = match node.get("yaw_lever_m") {
1541 Some(v) => number(cfg, v, &node.at("yaw_lever_m"), &mut refs)?,
1542 None => 0.0,
1543 };
1544 Some((constant, coefficients(node, "yaw_lever_axes", &mut refs)?))
1545 } else {
1546 None
1547 };
1548 span_nodes.push(SpanNode {
1549 id: id_of(node),
1550 section,
1551 length,
1552 axes: coefficients(node, "axes", &mut refs)?,
1553 velocity,
1554 yaw_lever,
1555 });
1556 }
1557 let lean = lean_node(cfg, &leans, &axes, &bodies, &axis_nodes, &body_nodes, &mut refs)?;
1558 if let Some(i) = (0..axis_nodes.len()).find(|&i| !axis_nodes[i].rotary && !body_nodes.iter().any(|b| b.axes[i]))
1559 {
1560 return Err(ConfigError::Invalid(format!("machine.axis[{}] (no body moves with it)", axis_nodes[i].id)));
1561 }
1562 let gantry = gantry_node(cfg, &gantries, &axes, &axis_nodes, &motor_nodes, §ion_nodes, &mut refs)?;
1563 let tcp = tcp_node(cfg, &tcps, &axes, &axis_nodes, &mut refs)?;
1564 let extra = gantry.as_ref().map_or(0, |g| g.drives.iter().flatten().count().saturating_sub(1));
1566 if motor_nodes.len() != axis_nodes.len() + extra {
1567 return Err(ConfigError::Invalid(
1568 "machine.motor (as many motors as axes, and one more per gantry drive beyond the first)".into(),
1569 ));
1570 }
1571 Ok(Self {
1572 axes: axis_nodes,
1573 motors: motor_nodes,
1574 sections: section_nodes,
1575 bodies: body_nodes,
1576 guides: guide_nodes,
1577 idlers: idler_nodes,
1578 frame,
1579 spans: span_nodes,
1580 lean,
1581 gantry,
1582 tcp,
1583 refs,
1584 values,
1585 linkage: None,
1586 scissor: None,
1587 })
1588 }
1589}
1590
1591fn worm_node(cfg: &Config, worms: &[Node], gearbox: &str, refs: &mut Vec<String>) -> Result<Option<WormNode>> {
1594 let mine: Vec<&Node> =
1595 worms.iter().filter(|w| w.table.get("gearbox").and_then(Value::as_str) == Some(gearbox)).collect();
1596 let node = match mine[..] {
1597 [] => return Ok(None),
1598 [node] => node,
1599 [_, second, ..] => {
1600 return Err(ConfigError::Invalid(format!("{} (one worm per gearbox)", second.at("gearbox"))));
1601 }
1602 };
1603 let value = |name: &str, refs: &mut Vec<String>| number(cfg, node.required(name)?, &node.at(name), refs);
1604 let worm = WormNode {
1605 ratio: value("ratio", refs)?,
1606 efficiency: value("efficiency", refs)?,
1607 back_efficiency: value("back_efficiency", refs)?,
1608 };
1609 if worm.ratio <= 0.0 {
1610 return Err(ConfigError::Invalid(node.at("ratio")));
1611 }
1612 if worm.efficiency <= 0.0 || worm.efficiency > 1.0 {
1613 return Err(ConfigError::Invalid(format!("{} (above 0, at most 1)", node.at("efficiency"))));
1614 }
1615 if worm.back_efficiency > 1.0 {
1616 return Err(ConfigError::Invalid(format!("{} (at most 1)", node.at("back_efficiency"))));
1617 }
1618 if worm.back_efficiency <= 0.0 && worm.efficiency >= 0.5 {
1620 let why = "a self-locking worm has an efficiency below 0.5";
1621 return Err(ConfigError::Invalid(format!("{} ({why})", node.at("efficiency"))));
1622 }
1623 Ok(Some(worm))
1624}
1625
1626fn lean_node(
1629 cfg: &Config,
1630 leans: &[Node],
1631 axes: &[Node],
1632 bodies: &[Node],
1633 axis_nodes: &[AxisNode],
1634 body_nodes: &[BodyNode],
1635 refs: &mut Vec<String>,
1636) -> Result<Option<LeanNode>> {
1637 let node = match leans {
1638 [] => return Ok(None),
1639 [node] => node,
1640 [_, second, ..] => return Err(ConfigError::Invalid(format!("{} (one lean at most)", second.path))),
1641 };
1642 let find = |nodes: &[Node], name: &str, id: &str| {
1643 nodes
1644 .iter()
1645 .position(|n| n.table["id"].as_str() == Some(id))
1646 .ok_or_else(|| ConfigError::Invalid(format!("{}.{name} = \"{id}\"", node.path)))
1647 };
1648 let body = find(bodies, "body", node.text("body")?.unwrap_or_default())?;
1649 let axis = find(axes, "axis", node.text("axis")?.unwrap_or_default())?;
1650 let lever_axis = node.text("lever_axis")?.map(|id| find(axes, "lever_axis", id)).transpose()?;
1651 if axis_nodes[axis].incline_deg != 0.0 || axis_nodes[axis].rotary {
1653 return Err(ConfigError::Invalid(format!("{} (a body leans along a horizontal axis)", node.at("axis"))));
1654 }
1655 if !body_nodes[body].axes[axis] {
1656 return Err(ConfigError::Invalid(format!("{} (the body does not move with axis)", node.at("body"))));
1657 }
1658 let value = |name: &str, refs: &mut Vec<String>| number(cfg, node.required(name)?, &node.at(name), refs);
1659 let lean = LeanNode {
1660 body,
1661 axis,
1662 com_drop: value("com_drop_m", refs)?,
1663 tool_drop: value("tool_drop_m", refs)?,
1664 lever_axis,
1665 lateral: value("lateral_stiffness_n_m", refs)?,
1666 tilt: value("tilt_stiffness_nm_rad", refs)?,
1667 damping: value("damping_n_s_m", refs)?,
1668 belt_offset: 0.0,
1669 };
1670 let offset = match node.get("belt_offset_m") {
1672 Some(item) => number(cfg, item, &node.at("belt_offset_m"), refs)?,
1673 None => 0.0,
1674 };
1675 let lean = LeanNode {
1676 belt_offset: match cfg.bool("effects.belt_run_offset") {
1677 Ok(true) => offset,
1678 Ok(false) | Err(ConfigError::Missing(_)) => 0.0,
1679 Err(e) => return Err(e),
1680 },
1681 ..lean
1682 };
1683 for (name, bad) in [
1684 ("lateral_stiffness_n_m", lean.lateral <= 0.0),
1685 ("tilt_stiffness_nm_rad", lean.tilt <= 0.0),
1686 ("damping_n_s_m", lean.damping < 0.0),
1687 ("belt_offset_m", offset < 0.0),
1688 ] {
1689 if bad {
1690 return Err(ConfigError::Invalid(node.at(name)));
1691 }
1692 }
1693 Ok(Some(lean))
1694}
1695
1696#[allow(clippy::too_many_arguments)]
1699fn gantry_node(
1700 cfg: &Config,
1701 gantries: &[Node],
1702 axes: &[Node],
1703 axis_nodes: &[AxisNode],
1704 motors: &[MotorNode],
1705 sections: &[SectionNode],
1706 refs: &mut Vec<String>,
1707) -> Result<Option<GantryNode>> {
1708 let node = match gantries {
1709 [] => return Ok(None),
1710 [node] => node,
1711 [_, second, ..] => return Err(ConfigError::Invalid(format!("{} (one gantry at most)", second.path))),
1712 };
1713 let find = |name: &str, id: &str| {
1714 axes.iter()
1715 .position(|n| n.table["id"].as_str() == Some(id))
1716 .ok_or_else(|| ConfigError::Invalid(format!("{}.{name} = \"{id}\"", node.path)))
1717 };
1718 let axis = find("axis", node.text("axis")?.unwrap_or_default())?;
1719 if axis_nodes[axis].incline_deg != 0.0 || axis_nodes[axis].rotary {
1720 return Err(ConfigError::Invalid(format!("{} (a horizontal straight axis)", node.at("axis"))));
1721 }
1722 let across = node.text("across")?.map(|id| find("across", id)).transpose()?;
1723 if across.is_some_and(|a| a == axis || axis_nodes[a].rotary) {
1724 return Err(ConfigError::Invalid(format!("{} (a straight axis other than axis)", node.at("across"))));
1725 }
1726 let value = |name: &str, refs: &mut Vec<String>| number(cfg, node.required(name)?, &node.at(name), refs);
1727 let (width, inertia, stiffness, damping) = (
1728 value("width_m", refs)?,
1729 value("inertia_kgm2", refs)?,
1730 value("stiffness_nm_rad", refs)?,
1731 value("damping_nm_s_rad", refs)?,
1732 );
1733 for (name, bad) in [
1734 ("width_m", width <= 0.0),
1735 ("inertia_kgm2", inertia <= 0.0),
1736 ("stiffness_nm_rad", stiffness <= 0.0),
1737 ("damping_nm_s_rad", damping < 0.0),
1738 ] {
1739 if bad {
1740 return Err(ConfigError::Invalid(node.at(name)));
1741 }
1742 }
1743 let across_shift = match node.get("across_start_m") {
1744 Some(v) => number(cfg, v, &node.at("across_start_m"), refs)? - 0.5 * width,
1745 None => -0.5 * across.map_or(0.0, |a| axis_nodes[a].stroke),
1746 };
1747 let per = |name: &str, ids: &[&str], refs: &mut Vec<String>| -> Result<Vec<Option<f64>>> {
1749 let mut out = vec![None; ids.len()];
1750 let Some(table) = node.get(name) else { return Ok(out) };
1751 for (id, v) in table.as_table().ok_or_else(|| ConfigError::Type(node.at(name)))? {
1752 let at = format!("{}.{id}", node.at(name));
1753 let i = ids.iter().position(|known| known == id).ok_or_else(|| ConfigError::Invalid(at.clone()))?;
1754 out[i] = Some(number(cfg, v, &at, refs)?);
1755 }
1756 Ok(out)
1757 };
1758 let motor_ids: Vec<&str> = motors.iter().map(|m| m.id.as_str()).collect();
1759 let drives = per("drives", &motor_ids, refs)?;
1760 for (m, _) in motors.iter().zip(&drives).filter(|(_, d)| d.is_some()) {
1761 let side = matches!(
1762 m.transmission,
1763 Transmission::Screw { .. } | Transmission::Rack { .. } | Transmission::LinearMotor { .. }
1764 );
1765 if !side || m.axis != Some(axis) {
1766 return Err(ConfigError::Invalid(format!(
1767 "{}.{} (a motor whose screw, rack or linear motor drives the gantry's axis)",
1768 node.at("drives"),
1769 m.id
1770 )));
1771 }
1772 }
1773 let section_ids: Vec<&str> = sections.iter().map(|s| s.id.as_str()).collect();
1774 let lengths = per("sections", §ion_ids, refs)?.into_iter().map(|l| l.unwrap_or(0.0)).collect();
1775 let tolerance = node.get("tolerance_m").map(|v| number(cfg, v, &node.at("tolerance_m"), refs)).transpose()?;
1776 if tolerance.is_some_and(|t| t <= 0.0) {
1777 return Err(ConfigError::Invalid(node.at("tolerance_m")));
1778 }
1779 Ok(Some(GantryNode {
1780 id: node.table["id"].as_str().unwrap_or_default().to_string(),
1781 axis,
1782 across,
1783 width,
1784 across_shift,
1785 inertia,
1786 stiffness,
1787 damping,
1788 drives,
1789 sections: lengths,
1790 tolerance,
1791 }))
1792}
1793
1794fn tcp_node(
1797 cfg: &Config,
1798 tcps: &[Node],
1799 axes: &[Node],
1800 axis_nodes: &[AxisNode],
1801 refs: &mut Vec<String>,
1802) -> Result<Option<TcpNode>> {
1803 let node = match tcps {
1804 [] => return Ok(None),
1805 [node] => node,
1806 [_, second, ..] => return Err(ConfigError::Invalid(format!("{} (one tcp at most)", second.path))),
1807 };
1808 let find = |name: &str| -> Result<Vec<usize>> {
1809 node.id_list(name)?
1810 .into_iter()
1811 .map(|id| {
1812 axes.iter()
1813 .position(|n| n.table["id"].as_str() == Some(id))
1814 .ok_or_else(|| ConfigError::Invalid(format!("{} = \"{id}\"", node.at(name))))
1815 })
1816 .collect()
1817 };
1818 let (straight, rotaries, table) = (find("axes")?, find("rotaries")?, find("table")?);
1819 let incline = |i: usize| (!axis_nodes[i].rotary).then_some(axis_nodes[i].incline_deg);
1820 let axes = match straight[..] {
1821 [x, y, z]
1822 if x == 0
1823 && y != 0
1824 && z != 0
1825 && y != z
1826 && incline(x) == Some(0.0)
1827 && incline(y) == Some(0.0)
1828 && incline(z) == Some(90.0) =>
1829 {
1830 [x, y, z]
1831 }
1832 _ => {
1833 return Err(ConfigError::Invalid(format!(
1834 "{} (three straight axes: the file's first, a horizontal and a vertical one)",
1835 node.at("axes")
1836 )));
1837 }
1838 };
1839 for (name, list) in [("rotaries", &rotaries), ("table", &table)] {
1840 let twice = |r: &usize| rotaries.iter().chain(&table).filter(|&s| s == r).count() > 1;
1841 if list.iter().any(|&r| !axis_nodes[r].rotary || twice(&r)) {
1842 return Err(ConfigError::Invalid(format!("{} (rotary axes, each once)", node.at(name))));
1843 }
1844 }
1845 if rotaries.is_empty() && table.is_empty() {
1846 return Err(ConfigError::Missing(format!("{} (or table)", node.at("rotaries"))));
1847 }
1848 let tool = node.point(cfg, "tool_m", refs)?.ok_or_else(|| ConfigError::Missing(node.at("tool_m")))?;
1849 let pivot = node.point(cfg, "table_pivot_m", refs)?.unwrap_or_default();
1850 Ok(Some(TcpNode { axes, rotaries, tool, table, pivot }))
1851}
1852
1853pub fn json_schema() -> Value {
1857 fn obj<const N: usize>(pairs: [(&str, Value); N]) -> Value {
1858 Value::Table(pairs.into_iter().map(|(k, v)| (k.to_string(), v)).collect())
1859 }
1860 let text = |t: &str| Value::String(t.into());
1861 let number = obj([(
1862 "oneOf",
1863 Value::Array(vec![
1864 obj([("type", text("number"))]),
1865 obj([
1866 ("type", text("string")),
1867 ("pattern", text(r"^[A-Za-z0-9_]+(\.[A-Za-z0-9_]+)+$")),
1868 ("description", text("Dotted path of a number in the file.")),
1869 ]),
1870 ]),
1871 )]);
1872 let id = obj([("type", text("string")), ("pattern", text("^[A-Za-z0-9_-]+$"))]);
1873 let mut lists = Table::new();
1874 for (list, doc, fields) in NODES {
1875 let mut properties = Table::new();
1876 for f in *fields {
1877 let (schema, about) = match f.kind {
1878 Kind::Id => (id.clone(), None),
1879 Kind::Key | Kind::Table => (obj([("type", text("string"))]), None),
1880 Kind::Ref(target) => (obj([("type", text("string"))]), Some(format!("Id of a machine.{target} node."))),
1881 Kind::Refs(target) => (
1882 obj([("type", text("array")), ("items", obj([("type", text("string"))]))]),
1883 Some(format!("Ids of machine.{target} nodes.")),
1884 ),
1885 Kind::Coefficients(target) => (
1886 obj([("type", text("object")), ("additionalProperties", number.clone())]),
1887 Some(format!("Keys: ids of machine.{target} nodes.")),
1888 ),
1889 Kind::Number => (number.clone(), None),
1890 Kind::Bool => (obj([("type", text("boolean"))]), None),
1891 Kind::Position => (
1892 obj([
1893 ("type", text("array")),
1894 ("items", obj([("type", text("number"))])),
1895 ("minItems", Value::Integer(2)),
1896 ("maxItems", Value::Integer(2)),
1897 ]),
1898 None,
1899 ),
1900 Kind::Point => (
1901 obj([
1902 ("type", text("array")),
1903 ("items", number.clone()),
1904 ("minItems", Value::Integer(3)),
1905 ("maxItems", Value::Integer(3)),
1906 ]),
1907 None,
1908 ),
1909 Kind::Choice(words) => (obj([("enum", Value::Array(words.iter().map(|w| text(w)).collect()))]), None),
1910 Kind::Route(targets) => (
1911 obj([("type", text("array")), ("items", obj([("type", text("string"))]))]),
1912 Some(format!(
1913 "Ids of {} nodes.",
1914 targets.iter().map(|t| format!("machine.{t}")).collect::<Vec<_>>().join(", ")
1915 )),
1916 ),
1917 };
1918 let mut schema = schema.as_table().cloned().unwrap_or_default();
1919 schema.insert(
1920 "description".into(),
1921 text(&about.map_or_else(|| f.doc.to_string(), |a| format!("{} {a}", f.doc))),
1922 );
1923 properties.insert(f.name.into(), Value::Table(schema));
1924 }
1925 let required = fields.iter().filter(|f| f.required).map(|f| text(f.name)).collect();
1926 let items = obj([
1927 ("type", text("object")),
1928 ("properties", Value::Table(properties)),
1929 ("required", Value::Array(required)),
1930 ("additionalProperties", Value::Boolean(false)),
1931 ]);
1932 lists.insert((*list).into(), obj([("type", text("array")), ("description", text(doc)), ("items", items)]));
1933 }
1934 lists.insert(
1935 "version".into(),
1936 obj([("const", Value::Integer(VERSION)), ("description", text("Version of the [machine] part."))]),
1937 );
1938 lists.insert(
1939 "id".into(),
1940 obj([
1941 ("type", text("string")),
1942 ("pattern", text("^[A-Za-z0-9_-]+$")),
1943 (
1944 "description",
1945 text("Id of the machine, as the front ends list it; default the file name without its extension."),
1946 ),
1947 ]),
1948 );
1949 lists.insert(
1950 "name".into(),
1951 obj([
1952 ("type", text("string")),
1953 ("description", text("Translation key or plain text of the machine's name; default its id.")),
1954 ]),
1955 );
1956 let required = ["version", "axis", "motor"].map(text).to_vec();
1957 obj([
1958 ("$schema", text("https://json-schema.org/draft/2020-12/schema")),
1959 ("$id", text("https://github.com/kinematics-simulation/machine-file.schema.json")),
1960 ("title", text("Machine file")),
1961 (
1962 "description",
1963 text(
1964 "A machine as a netlist of simulation components: [machine] says what is connected to what, the other tables hold the values (see docs/machine-files.md). Generated by sim_netlist::json_schema; do not edit.",
1965 ),
1966 ),
1967 ("type", text("object")),
1968 ("required", Value::Array(vec![text("format_version"), text("machine")])),
1969 (
1970 "properties",
1971 obj([
1972 ("format_version", obj([("const", Value::Integer(sim_core::config::FORMAT_VERSION))])),
1973 (
1974 "machine",
1975 obj([
1976 ("type", text("object")),
1977 ("required", Value::Array(required)),
1978 ("properties", Value::Table(lists)),
1979 ("additionalProperties", Value::Boolean(false)),
1980 ]),
1981 ),
1982 ]),
1983 ),
1984 ("additionalProperties", obj([("type", Value::Array(vec![text("object"), text("array")]))])),
1985 ])
1986}