From 74c0d73784fde2a9b79386edf2ecdf9e5b4b3eb8 Mon Sep 17 00:00:00 2001 From: David Date: Tue, 1 Dec 2026 13:51:01 +0100 Subject: [PATCH 1/7] vismach: unify static and Hal* transform and primitive classes Consolidate separate static and HAL-animated transform and geometry classes into single unified implementations while maintaining full backwards compatibility: - Merge Translate, Scale, Rotate, RotateEuler, and Show to accept both static values and an optional hal.component with HAL pin names. - Merge Line, Grid, Plane, and Coords primitives to support origin, normal, and normal+direction modes with optional HAL component arguments. - Consolidate CylinderX, CylinderY, and CylinderZ using a shared _CylinderAxis base class. - Retain all legacy Hal* class names as aliases for backwards compatibility. - Update vismach.adoc to document the unified classes and legacy aliases. - Also fixed along the way is a double import hal --- docs/src/gui/vismach.adoc | 171 ++++--- lib/python/vismach.py | 972 ++++++++++++++++---------------------- 2 files changed, 526 insertions(+), 617 deletions(-) diff --git a/docs/src/gui/vismach.adoc b/docs/src/gui/vismach.adoc index f67066b08a7..a8bcae3adfa 100644 --- a/docs/src/gui/vismach.adoc +++ b/docs/src/gui/vismach.adoc @@ -83,31 +83,70 @@ or raw data: possible to assemble the model in the CAD package. Alternatively parts can be created inside the model script from a range -of *shape primitives*. Many shapes are created at the origin and need to -be moved to the required location after creation: - -* `cylinder = CylinderX(x1, r1, x2, r2) + - cylinder = CylinderY(y1, r1, y2, r2) + - cylinder = CylinderZ(z1, r1, z2, r2)` + +of *shape primitives*. All primitives accept static numbers or an +optional leading HAL component (`[comp,]`) followed by HAL pin names. +Many shapes are created at the origin and need to be moved to the +required location after creation: + +* `cylinder = CylinderX([comp,] x1, r1, x2, r2)` + + `cylinder = CylinderY([comp,] y1, r1, y2, r2)` + + `cylinder = CylinderZ([comp,] z1, r1, z2, r2)` + Creates a (optionally tapered) cylinder on the given axis with the given radii at the given points on the axis. -* `sphere = Sphere(x, y, z, r)` + - Creates a sphere of radius r at (x,y,z) -* `triangle = TriangleXY(x1, y1, x2, y2, x3, y3, z1, z2) + - triangle = TriangleXZ(x1, z1, x2, z2, x3, z3, y1, y2) + - triangle = TriangleYZ(y1, z1, y2, z2, y3, z3, x1, x2)` + +* `sphere = Sphere([comp,] x, y, z, r)` + + Creates a sphere of radius `r` at `(x, y, z)`. +* `triangle = TriangleXY([comp,] x1, y1, x2, y2, x3, y3, z1, z2)` + + `triangle = TriangleXZ([comp,] x1, z1, x2, z2, x3, z3, y1, y2)` + + `triangle = TriangleYZ([comp,] y1, z1, y2, z2, y3, z3, x1, x2)` + Creates a triangular plate between planes defined by the last two values parallel to the specified plane, with vertices given by the three coordinate pairs. -* `arc = ArcX(x1, x2, r1, r2, a1, a2)` + - Create an arc shape. -* `box = Box(x1, y1, z1, x2, y2, z2)` + +* `arc = ArcX([comp,] x1, x2, r1, r2, a1, a2, steps)` + + Creates a curved arc segment along the X-axis between `x1` and `x2`, + with inner radius `r1`, outer radius `r2`, start/end angles `a1` and + `a2` (in degrees), and `steps` subdivisions. +* `box = Box([comp,] x1, y1, z1, x2, y2, z2)` + Creates a rectangular prism with opposite corners at the specified positions and edges parallel to the XYZ axes. -* `box = BoxCentered(xw, yw, zw)` + - Creates an xw by yw by zw box centred on the origin. -* `box = BoxCenteredXY(xw, yw, z)` + - Creates a box of width xw / yw and height z. +* `box = BoxCentered([comp,] xw, yw, zw)` + + Creates an `xw` by `yw` by `zw` box centred on the origin. +* `box = BoxCenteredXY([comp,] xw, yw, zw)` + + Creates a box of width `xw` / `yw` and height `zw`. +* `line = Line([comp,] x1, y1, z1, x2, y2, z2, stretch=1, r=5)` + + (Legacy alias: `HalLine`.) + + Creates a cylindrical line segment starting at `(x1, y1, z1)` along + vector `(x2, y2, z2)` scaled by `stretch` with radius `r`. +* `grid = Grid([comp,] s=500)` + + `grid = Grid([comp,] x, y, z, vx, vy, vz, s=500)` + + `grid = Grid([comp,] ox, oy, oz, xx, xy, xz, zx, zy, zz, s=500)` + + (Legacy aliases: `HalGrid`, `HalGridFromNormal`, `HalGridFromNormalAndDirection`.) + + Creates a reference grid of half-size `s` on the XY plane at the + origin, perpendicular to normal vector `(vx, vy, vz)` at `(x, y, z)`, + or aligned to origin `(ox, oy, oz)`, X-direction `(xx, xy, xz)`, and + Z-normal `(zx, zy, zz)`. +* `plane = Plane([comp,] s=500)` + + `plane = Plane([comp,] x, y, z, vx, vy, vz, s=500)` + + `plane = Plane([comp,] ox, oy, oz, xx, xy, xz, zx, zy, zz, s=500)` + + (Legacy alias: `HalPlaneFromNormal`.) + + Creates a solid reference plane of half-size `s` at the origin, + aligned to a normal vector, or aligned to an origin, X-direction + vector, and Z-normal vector. +* `coords = Coords([comp,] stretch=1, r=5)` + + `coords = Coords([comp,] ox, oy, oz, zx, zy, zz, stretch=1, r=5)` + + `coords = Coords([comp,] ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch=1, r=5)` + + (Legacy alias: `HalCoordsFromNormalAndDirection`.) + + Creates a 3-axis RGB coordinate indicator (X=Red, Y=Green, Z=Blue) of + base length `50 * stretch` and radius `r` at the origin, aligned to a + Z-normal vector, or aligned to an origin, X-direction vector, and + Z-normal vector. + +[NOTE] +==== +Legacy `Hal*` aliases (such as `HalLine`, `HalGrid`, +`HalGridFromNormal`, `HalGridFromNormalAndDirection`, `HalPlaneFromNormal`, +and `HalCoordsFromNormalAndDirection`) remain supported for backwards +compatibility, though they may be deprecated in the future. +==== Composite parts may be created by *assembling* these primitives either at creation time or subsequently using `Collection()`: @@ -131,44 +170,62 @@ rotation axis is created at the origin (but moves with the Part): * `part1 = Rotate([part1], theta, x, y, z)` + Rotate the part by angle theta about an axis between the origin and x, y, z. +* `part1 = Scale([part1], x, y, z)` + + Scale the part by factors `x`, `y`, and `z` along the respective axes. +* `part1 = RotateEuler([part1], th1, th2, th3, order=123)` + + Apply three successive Euler rotations (`th1`, `th2`, `th3` in degrees) + about the axes specified by `order` (default `123` for X-Y-Z). +* `part1 = Show([part1], const, var, scaleby_true=1, scaleby_false=0)` + + Toggle part visibility/scale between `scaleby_true` and `scaleby_false` + depending on whether `const == var`. + +[NOTE] +==== +Legacy `Hal*` aliases (such as `HalTranslate`, `HalVectorTranslate`, +`HalRotate`, `HalVectorRotate`, `HalScale`, `HalRotateEuler`, and +`HalShow`) remain supported for backwards compatibility, though they may +be deprecated in the future. +==== == Animating Parts -To animate the model (controlled by the values of HAL pins) there are -two functions 'HalTranslate' and 'HalRotate'. For parts to move inside -an assembly they need to have their HAL motions defined before being -assembled with the "Collection" command. The rotation axis and -translation vector move with the part as it is moved by the vismach -script during model assembly, or as it moves in response to the HAL pins -as the model is animated: - -* `part = HalTranslate([part], comp, "hal_pin", xs, ys, zs)` + - The function arguments are: -** first a _collection/part_ which can be pre-created earlier in the - script, or could be created at this point if preferred eg - `part1 = HalTranslate([Box(....)], ...)`. -** The _HAL component_ is the next argument, i.e. the object returned by - the `comp = hal.component(...)` command. After that is the name of - the HAL in that will animate the motion, this needs to match an - existing HAL pin that is part of the HAL component created earlier in - the script. -** Then follow the _X, Y, Z scales_. + - For a Cartesian machine created at 1:1 scale this would typically be - 1,0,0 for a motion in the positive X direction. + - However if the STL file happened to be in cm and the machine was in - inches, this could be fixed at this point by using 0.3937 - (1cm /2.54in) as the scale. -* `part = HalRotate([part], comp, "hal_pin", angle_scale, x, y, z)` + - This command is similar in its operation to HalTranslate except that - it is typically necessary to move the part to the origin first to - define the axis. -** The _axis of rotation_ is from the origin point to the point defined - by (x,y,z). + - When the part is moved back away from the origin to its correct - location the axis of rotation can be considered to remain "embedded" - in the part. -** _Rotation angles_ are in degrees, so for a rotary joint with a 0-1 - scaling you would need to use an angle scale of 360. +To animate the model, transform classes accept either static numbers or +a HAL component (`[comp,]`) followed by HAL pin names. All legacy `Hal*` +transform classes are kept as backwards-compatible aliases. For parts to +move inside an assembly they need to have their motions defined before +being assembled with the `Collection()` command. The rotation axis and +translation vector move with the part as it is moved by the Vismach +script during model assembly, or as it moves in response to HAL pins as +the model is animated: + +* `part = Translate([part], [comp,] x, y, z)` + + `part = Translate([part], [comp,] var, x, y, z)` + + (Legacy alias: `HalTranslate`.) + + In the 3-argument form, moves `part` by `(x, y, z)`. In the 4-argument + form, moves `part` along vector `(x, y, z)` scaled by `var`. +* `part = VectorTranslate([part], [comp,] xvar, yvar, zvar, scale=1)` + + (Legacy alias: `HalVectorTranslate`.) + + Moves `part` along `(xvar, yvar, zvar)` scaled by `scale` (which may + be passed either positionally or as a keyword argument). +* `part = Rotate([part], [comp,] th, x, y, z)` + + `part = Rotate([part], [comp,] var, th, x, y, z)` + + (Legacy aliases: `HalRotate`, `HalVectorRotate`.) + + Rotates `part` around the axis `(x, y, z)` by angle `th` (in degrees), + or by `th * var` when a variable multiplier `var` is given. +* `part = RotateEuler([part], [comp,] x, y, z, order=123)` + + (Legacy alias: `HalRotateEuler`.) + + Applies sequential Euler rotations `x`, `y`, `z` (in degrees) around + axes `1` (X), `2` (Y), and `3` (Z) in the specified `order`. +* `part = Scale([part], [comp,] x, y, z)` + + `part = Scale([part], [comp,] x, y, z, var)` + + (Legacy alias: `HalScale`.) + + Scales `part` along `(x, y, z)`, or scales by `(x * var, y * var, + z * var)` when a variable multiplier `var` is given. +* `part = Show([part], [comp,] const, var, scaleby_true=1, scaleby_false=0)` + + (Legacy alias: `HalShow`.) + + Compares `var` against `const`. When `var == const`, `part` is scaled by + `scaleby_true` (default `1`, visible); otherwise it is scaled by + `scaleby_false` (default `0`, hidden). == Assembling the model. @@ -195,21 +252,21 @@ of drive dogs: #Drive dogs dogs = Box(-6,-3,94,6,3,100) dogs = Color([1,1,1,1],[dogs]) -dogs = HalRotate([dogs],c,"spindle",360,0,0,1) +dogs = Rotate([dogs],c,"spindle",360,0,0,1) dogs = Translate([dogs],-1,49,0) #Drawbar draw = CylinderZ(120,3,125,3) draw = Color([1,0,.5,1],[draw]) draw = Translate([draw],-1,49,0) -draw = HalTranslate([draw],c,"drawbar",0,0,1) +draw = Translate([draw],c,"drawbar",0,0,1) # head/spindle head = AsciiSTL(filename="./head.stl") head = Color([0.3,0.3,0.3,1],[head]) head = Translate([head],0,0,4) head = Collection([head, tool, dogs, draw]) -head = HalTranslate([head],c,"Z",0,0,0.1) +head = Translate([head],c,"Z",0,0,0.1) # base base = AsciiSTL(filename="./base.stl") @@ -295,7 +352,7 @@ tooltip = Capture() #Build and assemble the model part1 = Collection([Box(-6,-3,94,6,3,100)]) part1 = Color([1,1,1,1],[part1]) -part1 = HalRotate([part1],comp,"pin_name",360,0,0,1) +part1 = Rotate([part1],comp,"pin_name",360,0,0,1) part1 = Translate([dogs],-1,49,0) ... #create a top-level model diff --git a/lib/python/vismach.py b/lib/python/vismach.py index 95648aefab6..5da36dc3644 100644 --- a/lib/python/vismach.py +++ b/lib/python/vismach.py @@ -22,7 +22,6 @@ from OpenGL.GLU import * from math import * import glnav -import hal class Collection(object): def __init__(self, parts): @@ -56,160 +55,243 @@ def volume(self): def set_volume(self,vol): self.vol = vol; -class Translate(Collection): - def __init__(self, parts, x, y, z): + +def _split_comp(args): + """Detects an optional leading hal.component instance in *args.""" + if args and isinstance(args[0], hal.component): + return args[0], args[1:] + return None, args + + +def _cross3(a, b): + return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] + + +def _polar3(v, stretch=1.0): + length = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]) * stretch + axis = (1, 0, 0) if hypot(v[0], v[1]) < 0.001 else _cross3(v, (0, 0, 1)) + angle = -atan2(hypot(v[0], v[1]), v[2]) * 180.0 / pi + return (length, angle, axis) + + +class ArgsBase(object): + """Resolves static numbers or HAL pin strings against an optional hal.component.""" + def __init__(self, comp, *args): + self.comp = comp + self._args = args + + def coords(self): + return [self.comp[v] if isinstance(v, str) else v for v in self._args] + + def cross(self, a, b): + return _cross3(a, b) + + def polar(self, v, stretch=1.0): + return _polar3(v, stretch) + + +class Translate(Collection, ArgsBase): + """ + Supports: + - Translate(parts, [comp,] x, y, z) + - Translate(parts, [comp,] var, x, y, z) + """ + def __init__(self, parts, *args): self.parts = parts - self.where = x, y, z + comp, rest = _split_comp(args) + if len(rest) == 3: + x, y, z = rest + ArgsBase.__init__(self, comp, 1, x, y, z) + elif len(rest) == 4: + var, x, y, z = rest + ArgsBase.__init__(self, comp, var, x, y, z) + else: + raise TypeError("Translate expects (parts, [comp,] [var,] x, y, z)") def apply(self): + v, x, y, z = self.coords() glPushMatrix() - glTranslatef(*self.where) + glTranslatef(x * v, y * v, z * v) def unapply(self): glPopMatrix() -class Scale(Collection): - def __init__(self, parts, x, y, z): + +class VectorTranslate(Collection, ArgsBase): + """ + Supports: + - VectorTranslate(parts, [comp,] xvar, yvar, zvar, scale=1) + """ + def __init__(self, parts, *args, **kwargs): self.parts = parts - self.scaleby = x, y, z + comp, rest = _split_comp(args) + if len(rest) == 3: + x, y, z = rest + sc = kwargs.get("scale", 1) + elif len(rest) == 4: + x, y, z, sc = rest + else: + raise TypeError("VectorTranslate expects (parts, [comp,] xvar, yvar, zvar[, scale])") + ArgsBase.__init__(self, comp, x, y, z, sc) def apply(self): + x, y, z, sc = self.coords() glPushMatrix() - glScalef(*self.scaleby) + glTranslatef(sc * x, sc * y, sc * z) def unapply(self): glPopMatrix() -class HalTranslate(Collection): - def __init__(self, parts, comp, var, x, y, z): + +HalTranslate = Translate +HalVectorTranslate = VectorTranslate + + +class Scale(Collection, ArgsBase): + """ + Unifies legacy classes: + - Scale(parts, x, y, z) + - HalScale(parts, comp, x, y, z, var) + """ + def __init__(self, parts, *args): self.parts = parts - self.where = x, y, z - self.comp = comp - self.var = var + comp, rest = _split_comp(args) + if len(rest) == 3: + x, y, z = rest + factor = 1 + elif len(rest) == 4: + x, y, z, factor = rest + else: + raise TypeError("Scale expects (parts, [comp,] x, y, z[, var])") + ArgsBase.__init__(self, comp, x, y, z, factor) def apply(self): - x, y, z = self.where - v = self.comp[self.var] - + x, y, z, factor = self.coords() glPushMatrix() - glTranslatef(x*v, y*v, z*v) + glScalef(x * factor, y * factor, z * factor) def unapply(self): glPopMatrix() +HalScale = Scale + -class HalRotate(Collection): - def __init__(self, parts, comp, var, th, x, y, z): +class Rotate(Collection, ArgsBase): + """ + Unifies legacy classes: + - Rotate(parts, th, x, y, z) + - HalRotate(parts, comp, var, th, x, y, z) + - HalVectorRotate(parts, comp, var, th, x, y, z) + """ + def __init__(self, parts, *args): self.parts = parts - self.where = th, x, y, z - self.comp = comp - self.var = var + comp, rest = _split_comp(args) + if comp is not None and len(rest) == 5: + var, th, x, y, z = rest + ArgsBase.__init__(self, comp, var, th, x, y, z) + elif len(rest) == 4: + th, x, y, z = rest + ArgsBase.__init__(self, comp, 1, th, x, y, z) + else: + raise TypeError("Rotate expects (parts, [comp, var,] th, x, y, z)") def apply(self): - th, x, y, z = self.where + if hasattr(self, "get_values"): + # Legacy subclass pattern (e.g. HalRotateNutation) overriding get_values() + c_vals = self.coords() + var = c_vals[0] if isinstance(c_vals, (list, tuple)) else c_vals + th, x, y, z = self.get_values() + else: + var, th, x, y, z = self.coords() glPushMatrix() - glRotatef(th * self.comp[self.var], x, y, z) + glRotatef(th * var, x, y, z) def unapply(self): glPopMatrix() +HalRotate = Rotate +HalVectorRotate = Rotate -class Rotate(Collection): - def __init__(self, parts, th, x, y, z): + +class RotateEuler(Collection, ArgsBase): + """Replaces legacy class HalRotateEuler(parts, [comp,] th1, th2, th3, order=123).""" + def __init__(self, parts, *args, order=123): self.parts = parts - self.where = th, x, y, z + comp, rest = _split_comp(args) + if len(rest) == 4: + th1, th2, th3, order = rest + elif len(rest) == 3: + th1, th2, th3 = rest + else: + raise TypeError("RotateEuler expects (parts, [comp,] th1, th2, th3[, order])") + ArgsBase.__init__(self, comp, order, th1, th2, th3) def apply(self): - th, x, y, z = self.where + order, th1, th2, th3 = self.coords() + order = int(order) glPushMatrix() - glRotatef(th, x, y, z) + axes = { + 131: ((1, 0, 0), (0, 0, 1), (1, 0, 0)), + 121: ((1, 0, 0), (0, 1, 0), (1, 0, 0)), + 212: ((0, 1, 0), (1, 0, 0), (0, 1, 0)), + 232: ((0, 1, 0), (0, 0, 1), (0, 1, 0)), + 323: ((0, 0, 1), (0, 1, 0), (0, 0, 1)), + 313: ((0, 0, 1), (1, 0, 0), (0, 0, 1)), + 123: ((1, 0, 0), (0, 1, 0), (0, 0, 1)), + 132: ((1, 0, 0), (0, 0, 1), (0, 1, 0)), + 213: ((0, 1, 0), (1, 0, 0), (0, 0, 1)), + 231: ((0, 1, 0), (0, 0, 1), (1, 0, 0)), + 321: ((0, 0, 1), (0, 1, 0), (1, 0, 0)), + 312: ((0, 0, 1), (1, 0, 0), (0, 1, 0)), + } + if order in axes: + a1, a2, a3 = axes[order] + glRotatef(th1, *a1) + glRotatef(th2, *a2) + glRotatef(th3, *a3) def unapply(self): glPopMatrix() +HalRotateEuler = RotateEuler -class HalRotateEuler(Collection): - def __init__(self, parts, comp, th1, th2, th3, order=123): - self.parts = parts - self.comp = comp - self.order = order - self.th1 = th1 - self.th2 = th2 - self.th3 = th3 - def apply(self): - # check whether pins or values have been passed - if isinstance(self.order, str): - order = int(self.comp[self.order]) - else: - order = self.order - if isinstance(self.th1, str): - th1 = self.comp[self.th1] - else: - th1 = self.th1 - if isinstance(self.th2, str): - th2 = self.comp[self.th2] - else: - th2 = self.th2 - if isinstance(self.th3, str): - th3 = self.comp[self.th3] +class Show(Collection, ArgsBase): + """ + Replaces legacy class HalShow(parts, [comp,] const, var, scaleby_true=1, scaleby_false=0). + """ + def __init__(self, parts, *args): + self.parts = parts + comp, rest = _split_comp(args) + if len(rest) == 2: + const, var = rest + scaleby_true, scaleby_false = 1, 0 + elif len(rest) == 3: + const, var, scaleby_true = rest + scaleby_false = 0 + elif len(rest) == 4: + const, var, scaleby_true, scaleby_false = rest else: - th3 = self.th3 + raise TypeError( + "Show expects (parts, [prefix,] const, var[, scaleby_true[, scaleby_false]])" + ) + ArgsBase.__init__(self, comp, const, var, scaleby_true, scaleby_false) + def apply(self): + const, var, scaleby_true, scaleby_false = self.coords() glPushMatrix() - if order == 131: - glRotatef(th1, 1, 0, 0) - glRotatef(th2, 0, 0, 1) - glRotatef(th3, 1, 0, 0) - elif order == 121: - glRotatef(th1, 1, 0, 0) - glRotatef(th2, 0, 1, 0) - glRotatef(th3, 1, 0, 0) - elif order == 212: - glRotatef(th1, 0, 1, 0) - glRotatef(th2, 1, 0, 0) - glRotatef(th3, 0, 1, 0) - elif order == 232: - glRotatef(th1, 0, 1, 0) - glRotatef(th2, 0, 0, 1) - glRotatef(th3, 0, 1, 0) - elif order == 323: - glRotatef(th1, 0, 0, 1) - glRotatef(th2, 0, 1, 0) - glRotatef(th3, 0, 0, 1) - elif order == 313: - glRotatef(th1, 0, 0, 1) - glRotatef(th2, 1, 0, 0) - glRotatef(th3, 0, 0, 1) - elif order == 123: - glRotatef(th1, 1, 0, 0) - glRotatef(th2, 0, 1, 0) - glRotatef(th3, 0, 0, 1) - elif order == 132: - glRotatef(th1, 1, 0, 0) - glRotatef(th2, 0, 0, 1) - glRotatef(th3, 0, 1, 0) - elif order == 213: - glRotatef(th1, 0, 1, 0) - glRotatef(th2, 1, 0, 0) - glRotatef(th3, 0, 0, 1) - elif order == 231: - glRotatef(th1, 0, 1, 0) - glRotatef(th2, 0, 0, 1) - glRotatef(th3, 1, 0, 0) - elif order == 321: - glRotatef(th1, 0, 0, 1) - glRotatef(th2, 0, 1, 0) - glRotatef(th3, 1, 0, 0) - elif order == 312: - glRotatef(th1, 0, 0, 1) - glRotatef(th2, 1, 0, 0) - glRotatef(th3, 0, 1, 0) + if const == var: + glScalef(scaleby_true, scaleby_true, scaleby_true) + else: + glScalef(scaleby_false, scaleby_false, scaleby_false) def unapply(self): glPopMatrix() +HalShow = Show + + class Track(Collection): '''move and rotate an object to point from one capture()'d coordinate system to another. @@ -261,520 +343,290 @@ def apply(self): def unapply(self): glPopMatrix() -# scales an object by the value of a halpin -class HalScale(Collection): - def __init__(self, parts, comp, x, y, z, var): - self.parts = parts - self.comp = comp - self.var = var - self.xyz = x, y, z - - def apply(self): - x, y, z = self.xyz - factor = self.comp[self.var] - glPushMatrix() - glScalef(x*factor,y*factor,z*factor) - - def unapply(self): - glPopMatrix() - - -# shows an object if const=var and hides it otherwise, behavior can be changed -# using the optional arguments for scalefactors when true or false -class HalShow(Collection): - def __init__(self, parts, comp, const, var, scaleby_true=1, scaleby_false=0): - self.parts = parts - self.comp = comp - self.const = const - self.var = var - self.scaleby_true = scaleby_true - self.scaleby_false = scaleby_false - def apply(self): - s_t = self.scaleby_true - s_f = self.scaleby_false - glPushMatrix() - if self.const == self.comp[self.var]: - glScalef(s_t,s_t,s_t) +class CoordsBase(ArgsBase): + def __init__(self, *args): + if args and (args[0] is None or isinstance(args[0], hal.component)): + comp, rest = args[0], args[1:] else: - glScalef(s_f,s_f,s_f) - - def unapply(self): - glPopMatrix() + comp, rest = _split_comp(args) + ArgsBase.__init__(self, comp, *rest) + self.q = gluNewQuadric() -# translates an object using a variable translation vector -# use scale=-1 to change direction -class HalVectorTranslate(Collection): - def __init__(self, parts, comp, xvar, yvar, zvar, scale=1): - self.parts = parts - self.comp = comp - self.xvar = xvar - self.yvar = yvar - self.zvar = zvar - self.sc = scale +class Line(CoordsBase): + def __init__(self, *args, **kwargs): + comp, rest = _split_comp(args) + if len(rest) < 6 or len(rest) > 8: + raise TypeError("Line expects ([comp,] x1, y1, z1, x2, y2, z2, stretch=1, r=5)") + x1, y1, z1, x2, y2, z2 = rest[:6] + stretch = rest[6] if len(rest) >= 7 else kwargs.get("stretch", 1) + r = rest[7] if len(rest) == 8 else kwargs.get("r", 5) + CoordsBase.__init__(self, comp, x1, y1, z1, x2, y2, z2, stretch, r) - def apply(self): - # check for zero vector components - xvar = 0 if self.xvar == 0 else self.comp[self.xvar] - yvar = 0 if self.yvar == 0 else self.comp[self.yvar] - zvar = 0 if self.zvar == 0 else self.comp[self.zvar] - sc = self.sc + def draw(self): + x1, y1, z1, x2, y2, z2, stretch, r = self.coords() + length, angle, axis = self.polar([x2, y2, z2], stretch) glPushMatrix() - glTranslatef(sc*xvar, sc*yvar, sc*zvar) + glTranslate(x1, y1, z1) + glRotate(angle, *axis) + gluCylinder(self.q, r, r, length, 32, 1) def unapply(self): glPopMatrix() +HalLine = Line -class HalVectorRotate(Collection): - def __init__(self, parts, comp, var, th, x, y, z): - self.parts = parts - self.comp = comp - self.var = var - self.values = th, x, y, z - - def get_values(self): - return self.values - def apply(self): - th, x, y, z = self.get_values() +def _apply_normal_or_basis(origin, vec_z, vec_x=None): + """Pushes a matrix aligned to an origin + Z-normal (and optional X-direction).""" + ox, oy, oz = origin + if vec_x is None: + _, angle, axis = _polar3(vec_z) glPushMatrix() - glRotatef(th * self.comp[self.var], x, y, z) - - def unapply(self): - glPopMatrix() - + glTranslate(ox, oy, oz) + glRotate(angle, *axis) + else: + xx, xy, xz = vec_x + zx, zy, zz = vec_z + yx, yy, yz = _cross3(vec_z, vec_x) + m_t = [ + [xx, xy, xz, 0], + [yx, yy, yz, 0], + [zx, zy, zz, 0], + [ox, oy, oz, 1], + ] + glPushMatrix() + glMultMatrixf(m_t) -class CoordsBase(object): - def __init__(self, *args): - if args and isinstance(args[0], hal.component): - self.comp = args[0] - args = args[1:] +def _draw_grid_lines(s): + s_int = int(s) + glBegin(GL_LINES) + for i in range(-s_int, s_int + 10, 10): + glVertex3f(-s_int, i, 0) + glVertex3f(s_int, i, 0) + glVertex3f(i, -s_int, 0) + glVertex3f(i, s_int, 0) + glEnd() + + +class Grid(CoordsBase): + """ + Unifies legacy classes: + - HalGrid([comp,] s=500) + - HalGridFromNormal([comp,] x, y, z, vx, vy, vz, s=500) + - HalGridFromNormalAndDirection([comp,] ox, oy, oz, xx, xy, xz, zx, zy, zz, s=500) + """ + def __init__(self, *args, **kwargs): + comp, rest = _split_comp(args) + n = len(rest) + + if n in (0, 1): + self._mode = "origin" + s = rest[0] if n == 1 else kwargs.get("s", 500) + CoordsBase.__init__(self, comp, s) + elif n in (6, 7): + self._mode = "normal" + x, y, z, vx, vy, vz = rest[:6] + s = rest[6] if n == 7 else kwargs.get("s", 500) + CoordsBase.__init__(self, comp, x, y, z, vx, vy, vz, s) + elif n in (9, 10): + self._mode = "normal_dir" + ox, oy, oz, xx, xy, xz, zx, zy, zz = rest[:9] + s = rest[9] if n == 10 else kwargs.get("s", 500) + CoordsBase.__init__(self, comp, ox, oy, oz, xx, xy, xz, zx, zy, zz, s) else: - self.comp = None - self._coords = args - self.q = gluNewQuadric() - - def coords(self): - return list(map(self._coord, self._coords)) - - def _coord(self, v): - if isinstance(v, str): return self.comp[v] - return v - - -# draw an open cylinder from point_1 to point_2, radius is optional (defaults to 5) -class HalLine(): - def __init__(self, comp, x1var, y1var, z1var, x2var, y2var, z2var, stretch, r=5): - self.comp = comp - self.x1var = x1var - self.y1var = y1var - self.z1var = z1var - self.x2var = x2var - self.y2var = y2var - self.z2var = z2var - self.stretch = stretch - self.r = r - self.q = gluNewQuadric() - - def cross(self, a, b): - return [a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]] - - # calculate polar coordinates in degrees - # a rotates around the x-axis; b rotates around the y axis - def polar(self, v): - length = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]) * self.stretch - axis = (1, 0, 0) if hypot(v[0], v[1]) < 0.001 else self.cross(v, (0, 0, 1)) - angle = -atan2(hypot(v[0], v[1]), v[2])*180/pi - return (length, angle, axis) + raise TypeError( + "Grid expects 0-1, 6-7 (origin + normal), or " + "9-10 (origin + X-dir + normal) arguments after optional comp" + ) def draw(self): - x1 = 0 if self.x1var == 0 else self.comp[self.x1var] - y1 = 0 if self.y1var == 0 else self.comp[self.y1var] - z1 = 0 if self.z1var == 0 else self.comp[self.z1var] - x2 = 0 if self.x2var == 0 else self.comp[self.x2var] - y2 = 0 if self.y2var == 0 else self.comp[self.y2var] - z2 = 0 if self.z2var == 0 else self.comp[self.z2var] - r = self.r - v = [x2,y2,z2] - length, angle, axis = self.polar(v) - glPushMatrix() - glTranslate(x1, y1, z1) - glRotate(angle,*axis) - gluCylinder(self.q, r, r, length, 32, 1) - - def unapply(self): - glPopMatrix() + if self._mode == "origin": + (s,) = self.coords() + elif self._mode == "normal": + x, y, z, vx, vy, vz, s = self.coords() + _apply_normal_or_basis((x, y, z), (vx, vy, vz)) + else: + ox, oy, oz, xx, xy, xz, zx, zy, zz, s = self.coords() + _apply_normal_or_basis((ox, oy, oz), (zx, zy, zz), (xx, xy, xz)) -# draw a plane defined by it's normal vector(vx,vy,vz) origin at (x,y,z) -class HalPlaneFromNormal(): - def __init__(self, comp, x, y, z, vx, vy, vz, s=500): - self.comp = comp - self.x = x - self.y = y - self.z = z - self.vx = vx - self.vy = vy - self.vz = vz - self.s = s - self.q = gluNewQuadric() + _draw_grid_lines(s) - def cross(self, a, b): - return [a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]] + def unapply(self): + if self._mode != "origin": + glPopMatrix() + + +HalGrid = Grid +HalGridFromNormal = Grid +HalGridFromNormalAndDirection = Grid + + +class Plane(CoordsBase): + """ + Replaces legacy class: + - HalPlaneFromNormal([comp,] x, y, z, vx, vy, vz, s=500) + and adds: + - Plane([comp,] s=500) + - Plane([comp,] ox, oy, oz, xx, xy, xz, zx, zy, zz, s=500) + """ + def __init__(self, *args, **kwargs): + comp, rest = _split_comp(args) + n = len(rest) + + if n in (0, 1): + self._mode = "origin" + s = rest[0] if n == 1 else kwargs.get("s", 500) + CoordsBase.__init__(self, comp, s) + elif n in (6, 7): + self._mode = "normal" + x, y, z, vx, vy, vz = rest[:6] + s = rest[6] if n == 7 else kwargs.get("s", 500) + CoordsBase.__init__(self, comp, x, y, z, vx, vy, vz, s) + elif n in (9, 10): + self._mode = "normal_dir" + ox, oy, oz, xx, xy, xz, zx, zy, zz = rest[:9] + s = rest[9] if n == 10 else kwargs.get("s", 500) + CoordsBase.__init__(self, comp, ox, oy, oz, xx, xy, xz, zx, zy, zz, s) + else: + raise TypeError("Plane expects 0-1, 6-7, or 9-10 arguments after optional comp") - # calculate polar coordinates in degrees - # a rotates around the x-axis; b rotates around the y axis - def polar(self, v): - length = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]) - axis = (1, 0, 0) if hypot(v[0], v[1]) < 0.001 else self.cross(v, (0, 0, 1)) - angle = -atan2(hypot(v[0], v[1]), v[2])*180/pi - return (length, angle, axis) + def draw(self): + if self._mode == "origin": + (s,) = self.coords() + n = (0, 0, 1) + elif self._mode == "normal": + x, y, z, vx, vy, vz, s = self.coords() + n = (vx, vy, vz) + _apply_normal_or_basis((x, y, z), n) + else: + ox, oy, oz, xx, xy, xz, zx, zy, zz, s = self.coords() + n = (zx, zy, zz) + _apply_normal_or_basis((ox, oy, oz), n, (xx, xy, xz)) - def square(self,n, s): glBegin(GL_QUADS) - glNormal3f(n[0],n[1],n[2]) - glVertex3f( s, s, 0) - glVertex3f(-s, s, 0) + glNormal3f(*n) + glVertex3f(s, s, 0) + glVertex3f(-s, s, 0) glVertex3f(-s, -s, 0) - glVertex3f( s, -s, 0) + glVertex3f(s, -s, 0) glEnd() - def draw(self): - # check for zero values in the arguments - x = 0 if self.x == 0 else self.comp[self.x] - y = 0 if self.y == 0 else self.comp[self.y] - z = 0 if self.z == 0 else self.comp[self.z] - vx = 0 if self.vx == 0 else self.comp[self.vx] - vy = 0 if self.vy == 0 else self.comp[self.vy] - vz = 0 if self.vz == 0 else self.comp[self.vz] - s = self.s - v = [vx, vy, vz] - length, angle, axis = self.polar(v) - glPushMatrix() - glTranslate(x,y,z) - glRotate(angle,*axis) - self.square(v,s) - def unapply(self): - glPopMatrix() - - -# draw a coordinate system defined by it's normal vector(zx,zy,zz) and x-direction vector(xx, xy, xz) -# optional r to define the thickness of the cylinders -class HalCoordsFromNormalAndDirection(): - def __init__(self, comp, ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch, r=5): - self.comp = comp - self.ox = ox - self.oy = oy - self.oz = oz - self.xx = xx - self.xy = xy - self.xz = xz - self.zx = zx - self.zy = zy - self.zz = zz - self.stretch = stretch - self.r = r - self.q = gluNewQuadric() - + if self._mode != "origin": + glPopMatrix() + + +HalPlaneFromNormal = Plane + + +class Coords(CoordsBase): + """ + Replaces legacy class: + - HalCoordsFromNormalAndDirection ([comp,] ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch=1, r=5) + and adds: + - Coords([comp,] stretch=1, r=5) + - Coords([comp,] ox, oy, oz, zx, zy, zz, stretch=1, r=5) + """ + def __init__(self, *args, **kwargs): + comp, rest = _split_comp(args) + n = len(rest) + + if n <= 2: + self._mode = "origin" + stretch = rest[0] if n >= 1 else kwargs.get("stretch", 1) + r = rest[1] if n == 2 else kwargs.get("r", 5) + CoordsBase.__init__(self, comp, stretch, r) + elif n in (6, 7, 8): + self._mode = "normal" + ox, oy, oz, zx, zy, zz = rest[:6] + stretch = rest[6] if n >= 7 else kwargs.get("stretch", 1) + r = rest[7] if n == 8 else kwargs.get("r", 5) + CoordsBase.__init__(self, comp, ox, oy, oz, zx, zy, zz, stretch, r) + elif n in (9, 10, 11): + self._mode = "normal_dir" + ox, oy, oz, xx, xy, xz, zx, zy, zz = rest[:9] + stretch = rest[9] if n >= 10 else kwargs.get("stretch", 1) + r = rest[10] if n == 11 else kwargs.get("r", 5) + CoordsBase.__init__(self, comp, ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch, r) + else: + raise TypeError("Coords expects 0-2, 6-8, or 9-11 arguments after optional comp") - def draw_vector(self, color): - gluCylinder(self.q, self.r, self.r, 50*self.stretch, 32, 1) + def draw_vector(self, r, stretch, color): glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color) - - def cross(self, a, b): - return [a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]] + gluCylinder(self.q, r, r, 50 * stretch, 32, 1) def draw(self): - # check for zero values in the arguments - ox = 0 if self.ox == 0 else self.comp[self.ox] - oy = 0 if self.oy == 0 else self.comp[self.oy] - oz = 0 if self.oz == 0 else self.comp[self.oz] - xx = 0 if self.xx == 0 else self.comp[self.xx] - xy = 0 if self.xy == 0 else self.comp[self.xy] - xz = 0 if self.xz == 0 else self.comp[self.xz] - zx = 0 if self.zx == 0 else self.comp[self.zx] - zy = 0 if self.zy == 0 else self.comp[self.zy] - zz = 0 if self.zz == 0 else self.comp[self.zz] - r = self.r - vo = [ox, oy, oz] - vx = [xx, xy, xz] - vz = [zx, zy, zz] - # calculate the missing y vector - vy = [yx, yy, yz] = self.cross(vz,vx) - # for some reason we need to rotate in the opposite (transpose) sense - m_t=[[ xx, xy, xz, 0], - [ yx, yy, yz, 0], - [ zx, zy, zz, 0], - [ ox, oy, oz, 1]] + if self._mode == "origin": + stretch, r = self.coords() + glPushMatrix() + elif self._mode == "normal": + ox, oy, oz, zx, zy, zz, stretch, r = self.coords() + _apply_normal_or_basis((ox, oy, oz), (zx, zy, zz)) + else: + ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch, r = self.coords() + _apply_normal_or_basis((ox, oy, oz), (zx, zy, zz), (xx, xy, xz)) - glPushMatrix() - glMultMatrixf(m_t) - self.draw_vector([1,0,0,1]) - glRotate(90,0,1,0) - self.draw_vector([0,1,0,1]) - glRotate(-90,1,0,0) - self.draw_vector([0,0,1,1]) + glPushAttrib(GL_LIGHTING_BIT) + self.draw_vector(r, stretch, [0, 0, 1, 1]) + glRotate(90, 0, 1, 0) + self.draw_vector(r, stretch, [1, 0, 0, 1]) + glRotate(-90, 1, 0, 0) + self.draw_vector(r, stretch, [0, 1, 0, 1]) + glPopAttrib() def unapply(self): glPopMatrix() -# draw a grid defined by it's normal vector(zx,zy,zz) and x-direction vector(xx, xy, xz) -# optional s to define the half-width from the origin (ox,oy,oz) -class HalGridFromNormalAndDirection(): - def __init__(self, comp, ox, oy, oz, xx, xy, xz, zx, zy, zz, s=500): - self.comp = comp - self.ox = ox - self.oy = oy - self.oz = oz - self.xx = xx - self.xy = xy - self.xz = xz - self.zx = zx - self.zy = zy - self.zz = zz - self.s = s - self.q = gluNewQuadric() +HalCoordsFromNormalAndDirection = Coords - def square(self, s): - glBegin(GL_LINES); - for i in range (-s,s+10,10): - # line 1 in x direction - glVertex3f(-s, i, 0) - glVertex3f( s, i, 0) - # line 1 in y direction - glVertex3f( i,-s, 0) - glVertex3f( i, s, 0) - glEnd() - def cross(self, a, b): - return [a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]] +class _CylinderAxis(CoordsBase): + """Shared base class for axis-aligned capped cylinders (X, Y, or Z).""" + _axis_rotation = None # (angle_deg, x, y, z) or None for Z-axis def draw(self): - # check for zero values in the arguments - ox = 0 if self.ox == 0 else self.comp[self.ox] - oy = 0 if self.oy == 0 else self.comp[self.oy] - oz = 0 if self.oz == 0 else self.comp[self.oz] - xx = 0 if self.xx == 0 else self.comp[self.xx] - xy = 0 if self.xy == 0 else self.comp[self.xy] - xz = 0 if self.xz == 0 else self.comp[self.xz] - zx = 0 if self.zx == 0 else self.comp[self.zx] - zy = 0 if self.zy == 0 else self.comp[self.zy] - zz = 0 if self.zz == 0 else self.comp[self.zz] - s = self.s - vo = [ox, oy, oz] - vx = [xx, xy, xz] - vz = [zx, zy, zz] - # calculate the missing y vector - vy = [yx, yy, yz] = self.cross(vz,vx) - # for some reason we need to rotate in the opposite (transpose) sense - m_t=[[ xx, xy, xz, 0], - [ yx, yy, yz, 0], - [ zx, zy, zz, 0], - [ ox, oy, oz, 1]] - - glPushMatrix() - glMultMatrixf(m_t) - self.square(s) - - def unapply(self): - glPopMatrix() - -# draw a grid defined by it's normal vector(vx,vy,vz) origin at (x,y,z) -class HalGridFromNormal(): - def __init__(self, comp, x, y, z, vx, vy, vz, s=500): - self.comp = comp - self.x = x - self.y = y - self.z = z - self.vx = vx - self.vy = vy - self.vz = vz - self.s = s - self.q = gluNewQuadric() - - def cross(self, a, b): - return [a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]] - - # calculate polar coordinates in degrees - # a rotates around the x-axis; b rotates around the y axis - def polar(self, v): - length = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]) - axis = (1, 0, 0) if hypot(v[0], v[1]) < 0.001 else self.cross(v, (0, 0, 1)) - angle = -atan2(hypot(v[0], v[1]), v[2])*180/pi - return (length, angle, axis) - - def square(self,n, s): - glBegin(GL_LINES); - for i in range (-s,s+10,10): - # line 1 in x direction - glVertex3f(-s, i, 0) - glVertex3f( s, i, 0) - # line 1 in y direction - glVertex3f( i,-s, 0) - glVertex3f( i, s, 0) - glEnd() + p1, r1, p2, r2 = self.coords() + if p1 > p2: + p1, p2 = p2, p1 + r1, r2 = r2, r1 - def draw(self): - # check for zero values in the arguments - x = 0 if self.x == 0 else self.comp[self.x] - y = 0 if self.y == 0 else self.comp[self.y] - z = 0 if self.z == 0 else self.comp[self.z] - vx = 0 if self.vx == 0 else self.comp[self.vx] - vy = 0 if self.vy == 0 else self.comp[self.vy] - vz = 0 if self.vz == 0 else self.comp[self.vz] - s = self.s - v = [vx, vy, vz] - length, angle, axis = self.polar(v) glPushMatrix() - glTranslate(x,y,z) - glRotate(angle,*axis) - self.square(v,s) - - def unapply(self): - glPopMatrix() - -# draw a grid defined by it's normal vector(vx,vy,vz) origin at (x,y,z) -class HalGrid(): - def __init__(self, comp, s=500): - self.comp = comp - self.s = s - self.q = gluNewQuadric() - - def grid(self, s): - glBegin(GL_LINES); - for i in range (-s,s+10,10): - # line 1 in x direction - glVertex3f(-s, i, 0) - glVertex3f( s, i, 0) - # line 1 in y direction - glVertex3f( i,-s, 0) - glVertex3f( i, s, 0) - glEnd() - - def draw(self): - s = self.s - self.grid(s) + if self._axis_rotation is not None: + glRotatef(*self._axis_rotation) + glTranslatef(0, 0, p1) + gluCylinder(self.q, r1, r2, p2 - p1, 32, 1) - -# give endpoint X values and radii -# resulting cylinder is on the X axis -class CylinderX(CoordsBase): - def draw(self): - x1, r1, x2, r2 = self.coords() - if x1 > x2: - tmp = x1 - x1 = x2 - x2 = tmp - tmp = r1 - r1 = r2 - r2 = tmp - glPushMatrix() - # GL creates cylinders along Z, so need to rotate - z1 = x1 - z2 = x2 - glRotatef(90,0,1,0) - # need to translate the whole thing to z1 - glTranslatef(0,0,z1) - # the cylinder starts out at Z=0 - gluCylinder(self.q, r1, r2, z2-z1, 32, 1) - # bottom cap - glRotatef(180,1,0,0) + # Bottom cap + glRotatef(180, 1, 0, 0) gluDisk(self.q, 0, r1, 32, 1) - glRotatef(180,1,0,0) - # the top cap needs flipped and translated + glRotatef(180, 1, 0, 0) + + # Top cap glPushMatrix() - glTranslatef(0,0,z2-z1) + glTranslatef(0, 0, p2 - p1) gluDisk(self.q, 0, r2, 32, 1) glPopMatrix() glPopMatrix() def volume(self): - x1, r1, x2, r2 = self.coords() - # actually a frustum of a cone - vol = 3.1415927/3.0 * abs(x1-x2)*(r1*r1+r1*r2+r2*r2) - #print "CylinderX.volume", vol - return vol + p1, r1, p2, r2 = self.coords() + return (pi / 3.0) * abs(p1 - p2) * (r1 * r1 + r1 * r2 + r2 * r2) -# give endpoint Y values and radii -# resulting cylinder is on the Y axis -class CylinderY(CoordsBase): - def __init__(self, y1, r1, y2, r2): - self._coords = y1, r1, y2, r2 - self.q = gluNewQuadric() +class CylinderX(_CylinderAxis): + _axis_rotation = (90, 0, 1, 0) - def draw(self): - y1, r1, y2, r2 = self.coords() - if y1 > y2: - tmp = y1 - y1 = y2 - y2 = tmp - tmp = r1 - r1 = r2 - r2 = tmp - glPushMatrix() - # GL creates cylinders along Z, so need to rotate - z1 = y1 - z2 = y2 - glRotatef(-90,1,0,0) - # need to translate the whole thing to z1 - glTranslatef(0,0,z1) - # the cylinder starts out at Z=0 - gluCylinder(self.q, r1, r2, z2-z1, 32, 1) - # bottom cap - glRotatef(180,1,0,0) - gluDisk(self.q, 0, r1, 32, 1) - glRotatef(180,1,0,0) - # the top cap needs flipped and translated - glPushMatrix() - glTranslatef(0,0,z2-z1) - gluDisk(self.q, 0, r2, 32, 1) - glPopMatrix() - glPopMatrix() - def volume(self): - y1, r1, y2, r2 = self.coords() - # actually a frustum of a cone - vol = 3.1415927/3.0 * abs(y1-y2)*(r1*r1+r1*r2+r2*r2) - #print "CylinderY.volume", vol - return vol +class CylinderY(_CylinderAxis): + _axis_rotation = (-90, 1, 0, 0) -class CylinderZ(CoordsBase): - def draw(self): - z1, r1, z2, r2 = self.coords() - if z1 > z2: - tmp = z1 - z1 = z2 - z2 = tmp - tmp = r1 - r1 = r2 - r2 = tmp - # need to translate the whole thing to z1 - glPushMatrix() - glTranslatef(0,0,z1) - # the cylinder starts out at Z=0 - gluCylinder(self.q, r1, r2, z2-z1, 32, 1) - # bottom cap - glRotatef(180,1,0,0) - gluDisk(self.q, 0, r1, 32, 1) - glRotatef(180,1,0,0) - # the top cap needs flipped and translated - glPushMatrix() - glTranslatef(0,0,z2-z1) - gluDisk(self.q, 0, r2, 32, 1) - glPopMatrix() - glPopMatrix() +class CylinderZ(_CylinderAxis): + _axis_rotation = None - def volume(self): - z1, r1, z2, r2 = self.coords() - # actually a frustum of a cone - vol = 3.1415927/3.0 * abs(z1-z2)*(r1*r1+r1*r2+r2*r2) - #print "CylinderZ.volume", vol - return vol # give center and radius class Sphere(CoordsBase): From 62e32aab43166383e6fae290bd54e914a3a3a9b1 Mon Sep 17 00:00:00 2001 From: David Date: Wed, 2 Dec 2026 14:00:56 +0100 Subject: [PATCH 2/7] vismach: add prefix dot-notation, expressions, and stat polling Extend argument resolution across transforms, primitives, Color, and Track to support dynamic dot-notation references and compiled math/conditional expressions without requiring an explicit HAL component argument: - Add "prefix.attr" dot-notation and "{prefix.attr}" math/conditional expression compilation in ArgsBase (with CoordsBase alias) across hal.component, hal module, linuxcnc.stat, and Python dict objects. - Support hyphenated HAL pin names inside "{...}" tokens and evaluate compiled expressions with __builtins__ disabled and pre-allocated math environments. - Register referenced linuxcnc.stat instances automatically and poll them once per update/redraw cycle via poll_all_stats(). - Support coordinate expressions in Track, Capture.world_pos(world), both Color argument orders, and an optional update callback function in main(). - Cache Collection traversal callables and optimize matrix inversion in invert(). - Update vismach.adoc to document prefix syntax, expressions, Track, Capture.world_pos(), and main(..., function=...). --- docs/src/gui/vismach.adoc | 213 ++++++++++---- lib/python/vismach.py | 574 +++++++++++++++++++++++++++++--------- 2 files changed, 594 insertions(+), 193 deletions(-) diff --git a/docs/src/gui/vismach.adoc b/docs/src/gui/vismach.adoc index a8bcae3adfa..39da7aa872f 100644 --- a/docs/src/gui/vismach.adoc +++ b/docs/src/gui/vismach.adoc @@ -83,57 +83,58 @@ or raw data: possible to assemble the model in the CAD package. Alternatively parts can be created inside the model script from a range -of *shape primitives*. All primitives accept static numbers or an -optional leading HAL component (`[comp,]`) followed by HAL pin names. -Many shapes are created at the origin and need to be moved to the -required location after creation: - -* `cylinder = CylinderX([comp,] x1, r1, x2, r2)` + - `cylinder = CylinderY([comp,] y1, r1, y2, r2)` + - `cylinder = CylinderZ([comp,] z1, r1, z2, r2)` + +of *shape primitives*. All primitives accept static numbers, an optional +leading prefix object (`[prefix,]` such as a `hal.component`, +`linuxcnc.stat`, `hal`, or `dict`), `"prefix.attr"` dot-notation strings, +or `"{prefix.attr}"` expressions. Many shapes are created at the origin +and need to be moved to the required location after creation: + +* `cylinder = CylinderX([prefix,] x1, r1, x2, r2)` + + `cylinder = CylinderY([prefix,] y1, r1, y2, r2)` + + `cylinder = CylinderZ([prefix,] z1, r1, z2, r2)` + Creates a (optionally tapered) cylinder on the given axis with the given radii at the given points on the axis. -* `sphere = Sphere([comp,] x, y, z, r)` + +* `sphere = Sphere([prefix,] x, y, z, r)` + Creates a sphere of radius `r` at `(x, y, z)`. -* `triangle = TriangleXY([comp,] x1, y1, x2, y2, x3, y3, z1, z2)` + - `triangle = TriangleXZ([comp,] x1, z1, x2, z2, x3, z3, y1, y2)` + - `triangle = TriangleYZ([comp,] y1, z1, y2, z2, y3, z3, x1, x2)` + +* `triangle = TriangleXY([prefix,] x1, y1, x2, y2, x3, y3, z1, z2)` + + `triangle = TriangleXZ([prefix,] x1, z1, x2, z2, x3, z3, y1, y2)` + + `triangle = TriangleYZ([prefix,] y1, z1, y2, z2, y3, z3, x1, x2)` + Creates a triangular plate between planes defined by the last two values parallel to the specified plane, with vertices given by the three coordinate pairs. -* `arc = ArcX([comp,] x1, x2, r1, r2, a1, a2, steps)` + +* `arc = ArcX([prefix,] x1, x2, r1, r2, a1, a2, steps)` + Creates a curved arc segment along the X-axis between `x1` and `x2`, with inner radius `r1`, outer radius `r2`, start/end angles `a1` and `a2` (in degrees), and `steps` subdivisions. -* `box = Box([comp,] x1, y1, z1, x2, y2, z2)` + +* `box = Box([prefix,] x1, y1, z1, x2, y2, z2)` + Creates a rectangular prism with opposite corners at the specified positions and edges parallel to the XYZ axes. -* `box = BoxCentered([comp,] xw, yw, zw)` + +* `box = BoxCentered([prefix,] xw, yw, zw)` + Creates an `xw` by `yw` by `zw` box centred on the origin. -* `box = BoxCenteredXY([comp,] xw, yw, zw)` + +* `box = BoxCenteredXY([prefix,] xw, yw, zw)` + Creates a box of width `xw` / `yw` and height `zw`. -* `line = Line([comp,] x1, y1, z1, x2, y2, z2, stretch=1, r=5)` + +* `line = Line([prefix,] x1, y1, z1, x2, y2, z2, stretch=1, r=5)` + (Legacy alias: `HalLine`.) + Creates a cylindrical line segment starting at `(x1, y1, z1)` along vector `(x2, y2, z2)` scaled by `stretch` with radius `r`. -* `grid = Grid([comp,] s=500)` + - `grid = Grid([comp,] x, y, z, vx, vy, vz, s=500)` + - `grid = Grid([comp,] ox, oy, oz, xx, xy, xz, zx, zy, zz, s=500)` + +* `grid = Grid([prefix,] s=500)` + + `grid = Grid([prefix,] x, y, z, vx, vy, vz, s=500)` + + `grid = Grid([prefix,] ox, oy, oz, xx, xy, xz, zx, zy, zz, s=500)` + (Legacy aliases: `HalGrid`, `HalGridFromNormal`, `HalGridFromNormalAndDirection`.) + Creates a reference grid of half-size `s` on the XY plane at the origin, perpendicular to normal vector `(vx, vy, vz)` at `(x, y, z)`, or aligned to origin `(ox, oy, oz)`, X-direction `(xx, xy, xz)`, and Z-normal `(zx, zy, zz)`. -* `plane = Plane([comp,] s=500)` + - `plane = Plane([comp,] x, y, z, vx, vy, vz, s=500)` + - `plane = Plane([comp,] ox, oy, oz, xx, xy, xz, zx, zy, zz, s=500)` + +* `plane = Plane([prefix,] s=500)` + + `plane = Plane([prefix,] x, y, z, vx, vy, vz, s=500)` + + `plane = Plane([prefix,] ox, oy, oz, xx, xy, xz, zx, zy, zz, s=500)` + (Legacy alias: `HalPlaneFromNormal`.) + Creates a solid reference plane of half-size `s` at the origin, aligned to a normal vector, or aligned to an origin, X-direction vector, and Z-normal vector. -* `coords = Coords([comp,] stretch=1, r=5)` + - `coords = Coords([comp,] ox, oy, oz, zx, zy, zz, stretch=1, r=5)` + - `coords = Coords([comp,] ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch=1, r=5)` + +* `coords = Coords([prefix,] stretch=1, r=5)` + + `coords = Coords([prefix,] ox, oy, oz, zx, zy, zz, stretch=1, r=5)` + + `coords = Coords([prefix,] ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch=1, r=5)` + (Legacy alias: `HalCoordsFromNormalAndDirection`.) + Creates a 3-axis RGB coordinate indicator (X=Red, Y=Green, Z=Blue) of base length `50 * stretch` and radius `r` at the origin, aligned to a @@ -189,44 +190,69 @@ be deprecated in the future. == Animating Parts -To animate the model, transform classes accept either static numbers or -a HAL component (`[comp,]`) followed by HAL pin names. All legacy `Hal*` -transform classes are kept as backwards-compatible aliases. For parts to -move inside an assembly they need to have their motions defined before -being assembled with the `Collection()` command. The rotation axis and -translation vector move with the part as it is moved by the Vismach -script during model assembly, or as it moves in response to HAL pins as -the model is animated: - -* `part = Translate([part], [comp,] x, y, z)` + - `part = Translate([part], [comp,] var, x, y, z)` + +To animate the model, transforms, primitives, and `Color` accept static +numbers, HAL pin names with an explicit prefix object, `"prefix.attr"` +dot-notation strings, or `"{prefix.attr}"` math and conditional +expressions. For parts to move inside an assembly they need to have their +motions defined before being assembled with the `Collection()` command. +The rotation axis and translation vector move with the part as it is +moved by the Vismach script during model assembly, or as it moves in +response to live values as the model is animated: + +* `part = Translate([part], [prefix,] x, y, z)` + + `part = Translate([part], [prefix,] var, x, y, z)` + (Legacy alias: `HalTranslate`.) + In the 3-argument form, moves `part` by `(x, y, z)`. In the 4-argument form, moves `part` along vector `(x, y, z)` scaled by `var`. -* `part = VectorTranslate([part], [comp,] xvar, yvar, zvar, scale=1)` + +* `part = VectorTranslate([part], [prefix,] xvar, yvar, zvar, scale=1)` + (Legacy alias: `HalVectorTranslate`.) + Moves `part` along `(xvar, yvar, zvar)` scaled by `scale` (which may be passed either positionally or as a keyword argument). -* `part = Rotate([part], [comp,] th, x, y, z)` + - `part = Rotate([part], [comp,] var, th, x, y, z)` + +* `part = Rotate([part], [prefix,] th, x, y, z)` + + `part = Rotate([part], [prefix,] var, th, x, y, z)` + (Legacy aliases: `HalRotate`, `HalVectorRotate`.) + Rotates `part` around the axis `(x, y, z)` by angle `th` (in degrees), or by `th * var` when a variable multiplier `var` is given. -* `part = RotateEuler([part], [comp,] x, y, z, order=123)` + +* `part = RotateEuler([part], [prefix,] x, y, z, order=123)` + (Legacy alias: `HalRotateEuler`.) + Applies sequential Euler rotations `x`, `y`, `z` (in degrees) around axes `1` (X), `2` (Y), and `3` (Z) in the specified `order`. -* `part = Scale([part], [comp,] x, y, z)` + - `part = Scale([part], [comp,] x, y, z, var)` + +* `part = Scale([part], [prefix,] x, y, z)` + + `part = Scale([part], [prefix,] x, y, z, var)` + (Legacy alias: `HalScale`.) + Scales `part` along `(x, y, z)`, or scales by `(x * var, y * var, z * var)` when a variable multiplier `var` is given. -* `part = Show([part], [comp,] const, var, scaleby_true=1, scaleby_false=0)` + +* `part = Show([part], [prefix,] const, var, scaleby_true=1, scaleby_false=0)` + (Legacy alias: `HalShow`.) + Compares `var` against `const`. When `var == const`, `part` is scaled by `scaleby_true` (default `1`, visible); otherwise it is scaled by `scaleby_false` (default `0`, hidden). +=== Prefix and Expression Syntax + +Any numeric parameter on a transform, primitive, or `Color` can be driven +dynamically in three ways: + +* *Explicit prefix object + attribute name:* + + Pass a `hal.component`, `linuxcnc.stat`, `hal` module, or Python `dict` + as the prefix argument followed by pin or attribute names: +** `Translate([part], c, "joint0", 1, 0, 0)` (reads `c["joint0"]`) +** `Translate([part], s, "g5x_offset[0]", 1, 0, 0)` (reads `s.g5x_offset[0]`) +* *Dot-notation strings (`"prefix.attr"`):* + + Omit the leading prefix object and reference any `hal.component`, + `linuxcnc.stat`, `hal`, or `dict` variable in scope directly by name: +** `"c.joint0"` (reads `c["joint0"]`) +** `"hal.spindle.0.speed"` (reads `hal.get_value("spindle.0.speed")`) +** `"s.actual_position[2]"` (reads `s.actual_position[2]`, polled once per redraw) +* *Math and conditional expressions (`"{prefix.attr}"`):* + + Wrap one or more `"prefix.attr"` tokens in curly braces `{...}` inside a + Python math or conditional expression. Hyphenated HAL pin names (such as + `"{c.pivot-z}"`) are supported directly: +** `Translate([part], 0, 0, "{s.actual_position[2] - s.g5x_offset[2]}")` +** `Rotate([part], "{sin(radians(c.angle)) * 45}", 0, 1, 0)` +** `Show([part], 1, "{1 if s.tool_in_spindle > 0 else 0}")` +** `Color([part], ["{1.0 if c.active else 0.2}", 0.2, 0.2, 1.0])` + == Assembling the model. In order for parts to move together they need to be assembled with the @@ -299,27 +325,31 @@ model = Collection([base, saddle, head, carousel]) == Other functions -* `part = Color([colorspec], [part])` + - Sets the display color of the part. Note that unlike the other - functions the part definition comes second in this case. + - The colorspec consists of the three RGB values and an opacity. - For example [1,0,0,0.5] for a 50% opacity red. +* `part = Color([part], [prefix,] [colorspec])` + + (Legacy swapped order `Color([colorspec], [part])` is also supported.) + + Sets the display color of the part. The `colorspec` consists of the + three RGB values and an optional opacity (default `1.0`), for example + `[1, 0, 0, 0.5]` for a 50% opacity red. Each channel may be a static + number, `"prefix.attr"`, or `"{prefix.attr}"` expression. +* `part = Track([part], [prefix,] position, target, world)` + + Aligns `part` along the vector from `position` to `target` in `world` + space. `position` and `target` may each be a `Capture()` object or a + 3-element `[x, y, z]` list containing static numbers, `"prefix.attr"`, + or `"{prefix.attr}"` expressions. * `myhud = Hud()` + Creates a heads-up display in the Vismach GUI to display such items as axis positions. -//// -Need to play around with this to see how it works. -//// * `tooltip = Capture()` + Think of this as an invisible part that needs to be attached to the tooltip to track the position and orientation of the tool coordinate system. It is actually a transformation matrix that is constantly updated as the - model moves. + model moves. Calling `tooltip.world_pos(world)` returns its `[x, y, z]` + coordinates relative to `world` (or in model space if `world` is omitted). * `work = Capture()` + Same as above but attached to the work table to track the work coordinate system. * `main(model, tooltip, work, size=10, hud=0, rotation_vectors=None, - lat=0, lon=0)` + + lat=0, lon=0, function=None)` + This is the command that makes it all happen, creates the display etc. ** _model_ should be a collection that contains all the machine parts. ** _tooltip_ and _work_ need to be created by `Capture()`. Vismach needs @@ -332,6 +362,10 @@ Need to play around with this to see how it works. initial viewpoint is rather unhelpfully from immediately overhead. ** _size_ sets the extent of the volume visualized in the initial view. ** _hud_ refers to a head-up display of axis positions. +** _function_ is an optional zero-argument callback executed on each + periodic update cycle (after `linuxcnc.stat` polling and before + redrawing), useful for computing derived values into a Python `dict` + prefix. == Basic structure of a Vismach script. @@ -361,4 +395,75 @@ model = Collection([base, saddle, head, carousel]) main(model, tooltip, work, 100, lat=-75, lon=215) ---- +== Dynamic Values and Expressions + +=== Custom Prefix Identifiers + +Prefix names are not restricted to `c` or `s`. Any valid Python variable +name bound in the caller's scope to a `hal.component`, `linuxcnc.stat`, +`hal` module, or `dict` can be used as a prefix: + +[source,python] +---- +comp = hal.component("mygui") +status = linuxcnc.stat() +world = Capture() +spindle_tip = Capture() +cable = {"anchor_x": 0.0, "anchor_y": 0.0, "anchor_z": 100.0} + +def update_cable_anchor(): + x, y, z = spindle_tip.world_pos(world) + cable["anchor_x"] = x + cable["anchor_y"] = y + cable["anchor_z"] = z + 50.0 + status.g5x_offset[2] + +# Orient a flexible hose or cable between the moving spindle tip and a derived anchor +hose = Track( + [CylinderZ(0, 4, 100, 4)], + spindle_tip, + ["cable.anchor_x", "cable.anchor_y", "{cable.anchor_z + comp.slack}"], + world, +) + +main(model, tooltip, work, 100, lat=-75, lon=215, function=update_cable_anchor) +---- + +Multiple prefix objects of the same or different types can be combined +within a single expression. Passing `function=update_cable_anchor` to +`main()` updates the `dict` values on every refresh cycle immediately +before the scene is redrawn. + +[NOTE] +==== +Any `linuxcnc.stat` instance referenced in a Vismach prefix or +expression is automatically registered and polled once per refresh +cycle before `function` runs. If a `linuxcnc.stat` instance is used +*exclusively* inside your custom `function` callback (and not referenced +in any Vismach part or transform), call `status.poll()` inside that +function so its attributes stay current. +==== + +=== Expression Parsing and `stat` Polling + +String arguments containing `"prefix.attr"` tokens or `"{prefix.attr}"` +expressions are compiled once when the model is constructed: + +* *Scope capture and compilation:* At initialization, Vismach captures + matching prefix objects (`hal.component`, `linuxcnc.stat`, `hal`, or + `dict`) from the caller's scope and compiles each expression into a + reusable bytecode object evaluated without Python built-ins. Standard + `math` functions (`sin`, `cos`, `tan`, `radians`, `degrees`, `sqrt`, + `hypot`, `abs`, `min`, `max`, `round`, `floor`, `ceil`, `pi`, etc.) + and conditional expressions (`a if cond else b`) are available inside + `{...}`. +* *Hyphenated HAL pins:* Pin names containing hyphens (such as + `"{c.pivot-z}"`) are extracted as single `{...}` tokens before + compilation, so they are resolved as pin lookups rather than parsed as + subtraction. +* *Once-per-frame `linuxcnc.stat` polling:* Any `linuxcnc.stat` object + referenced via a prefix or expression is registered automatically and + polled once at the start of each redraw cycle (`poll_all_stats()`), + avoiding redundant status polls across multiple model parts. + + // vim: set syntax=asciidoc: diff --git a/lib/python/vismach.py b/lib/python/vismach.py index 5da36dc3644..74758f7e8e8 100644 --- a/lib/python/vismach.py +++ b/lib/python/vismach.py @@ -14,7 +14,6 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -import copy import sys, rs274.OpenGLTk, signal, hal import tkinter @@ -22,24 +21,202 @@ from OpenGL.GLU import * from math import * import glnav +import inspect +import operator +import linuxcnc + +_registered_stats = [] +_stats_fresh = False + +_EXPR_MATH = { + "sin": sin, "cos": cos, "tan": tan, + "asin": asin, "acos": acos, "atan": atan, "atan2": atan2, + "hypot": hypot, "sqrt": sqrt, "pi": pi, "tau": tau, "e": e, + "abs": abs, "min": min, "max": max, "round": round, + "floor": floor, "ceil": ceil, "fmod": fmod, + "pow": pow, "exp": exp, "log": log, "log10": log10, + "radians": radians, "degrees": degrees, +} + +def _register_stat(st): + """Registers a linuxcnc.stat instance for once-per-frame polling.""" + if isinstance(st, linuxcnc.stat) and st not in _registered_stats: + _registered_stats.append(st) + +def _check_stats_ready(): + """Verifies at startup that all registered linuxcnc.stat instances can poll.""" + # Objects used in parts or Hud are already registered during scene construction + # (including local builder scopes and imported sub-assemblies). Scan main()'s + # caller globals as well to catch instances used only in function=... callbacks. + if not _registered_stats: + try: + caller_globals = sys._getframe(2).f_globals + for val in caller_globals.values(): + if isinstance(val, linuxcnc.stat): + _register_stat(val) + except ValueError: + pass + + for st in _registered_stats: + try: + st.poll() + except linuxcnc.error as exc: + sys.stderr.write( + "Vismach Error: Cannot poll linuxcnc.stat (%s). " + "Is LinuxCNC running?\n" % exc + ) + raise SystemExit(1) + +def poll_all_stats(): + """Polls all registered linuxcnc.stat instances once per update/redraw cycle.""" + global _stats_fresh + if _stats_fresh: + return + for st in _registered_stats: + st.poll() + _stats_fresh = True + +def _is_valid_prefix_obj(obj): + return isinstance(obj, (hal.component, linuxcnc.stat, dict)) or obj is hal + +def _capture_caller_prefixes(): + """Snapshots valid prefix objects (hal.component, linuxcnc.stat, hal, dict) from caller scope.""" + prefixes = {"hal": hal} + frame = inspect.currentframe() + try: + caller = frame.f_back + while caller is not None and caller.f_globals.get("__name__") == __name__: + caller = caller.f_back + if caller is not None: + for scope in (caller.f_globals, caller.f_locals): + for k, v in scope.items(): + if not k.startswith("_") and _is_valid_prefix_obj(v): + prefixes[k] = v + if isinstance(v, linuxcnc.stat): + _register_stat(v) + finally: + del frame + return prefixes + +def _split_comp(args): + """Detects an optional leading prefix (hal.component, linuxcnc.stat, hal, dict) in *args.""" + if args and _is_valid_prefix_obj(args[0]): + if isinstance(args[0], linuxcnc.stat): + _register_stat(args[0]) + return args[0], args[1:] + return None, args + +def _make_attr_getter(obj, attr_path): + """Creates a fast getter for 'attr' or 'attr[idx]' on a prefix object.""" + if isinstance(obj, hal.component): + return lambda c=obj, p=attr_path: c[p] + if obj is hal: + return lambda p=attr_path: hal.get_value(p) + if isinstance(obj, dict): + if "[" not in attr_path: + return lambda d=obj, k=attr_path: d[k] + head, tail = attr_path.split("[", 1) + code = compile("_d[%r][%s" % (head, tail), "", "eval") + return lambda c=code, d=obj: eval(c, {"__builtins__": None}, {"_d": d}) + if isinstance(obj, linuxcnc.stat): + _register_stat(obj) + if "[" not in attr_path: + getter = operator.attrgetter(attr_path) + return lambda o=obj, g=getter: g(o) + code = compile("_o." + attr_path, "", "eval") + return lambda c=code, o=obj: eval(c, {"__builtins__": None}, {"_o": o}) + +def _resolve_token(token, explicit_prefix, prefix_cache): + """Resolves a single 'prefix.attr' or bare 'attr' token into a zero-arg getter.""" + if explicit_prefix is not None: + if "." in token: + head, rest = token.split(".", 1) + if head in prefix_cache and prefix_cache[head] is explicit_prefix: + return _make_attr_getter(explicit_prefix, rest) + if head in prefix_cache: + return _make_attr_getter(prefix_cache[head], rest) + return _make_attr_getter(explicit_prefix, token) + + if "." not in token: + raise ValueError("No prefix passed: expected 'prefix.attribute', got %r" % token) + + head, rest = token.split(".", 1) + if head not in prefix_cache: + raise NameError("Prefix %r not found in caller scope" % head) + return _make_attr_getter(prefix_cache[head], rest) + +def _compile_arg(val, explicit_prefix, prefix_cache): + """ + Compiles a static value, 'prefix.attr' string, or '{prefix.attr}' math/conditional + expression into a zero-arg callable with {"__builtins__": None}. + """ + if not isinstance(val, str): + return lambda: val + + s = val.strip() + + if "{" in s or "}" in s: + getters = [] + parts = [] + i = 0 + n = len(s) + while i < n: + open_idx = s.find("{", i) + if open_idx == -1: + parts.append(s[i:]) + break + close_idx = s.find("}", open_idx + 1) + if close_idx == -1: + raise SyntaxError("Vismach Error: Unmatched '{' in expression %r" % val) + parts.append(s[i:open_idx]) + token = s[open_idx + 1:close_idx].strip() + slot = "__v%d" % len(getters) + getters.append(_resolve_token(token, explicit_prefix, prefix_cache)) + parts.append(slot) + i = close_idx + 1 + + py_expr = "".join(parts) + try: + code = compile(py_expr, "", "eval") + except SyntaxError as exc: + raise SyntaxError("Vismach Error: Cannot compile expression %r: %s" % (val, exc)) from exc + + # Pre-allocate a single reusable env and overwrite only the keys in-place on each evaluation + env = dict(_EXPR_MATH) + slots = [("__v%d" % idx, fn) for idx, fn in enumerate(getters)] + + def _eval_expr(): + for slot, fn in slots: + env[slot] = fn() + return eval(code, {"__builtins__": None}, env) + + return _eval_expr + + return _resolve_token(s, explicit_prefix, prefix_cache) + class Collection(object): def __init__(self, parts): self.parts = parts self.vol = 0 - def traverse(self): + def _build_steps(self): + steps = [] for p in self.parts: - if hasattr(p, "apply"): - p.apply() - if hasattr(p, "capture"): - p.capture() - if hasattr(p, "draw"): - p.draw() - if hasattr(p, "traverse"): - p.traverse() - if hasattr(p, "unapply"): - p.unapply() + for name in ("apply", "capture", "draw", "traverse", "unapply"): + fn = getattr(p, name, None) + if fn is not None: + steps.append(fn) + self._steps = steps + self._steps_parts = list(self.parts) + return steps + + def traverse(self): + steps = getattr(self, "_steps", None) + if steps is None or self._steps_parts != self.parts: + steps = self._build_steps() + for fn in steps: + fn() def volume(self): if hasattr(self, "vol") and self.vol != 0: @@ -56,32 +233,48 @@ def set_volume(self,vol): self.vol = vol; -def _split_comp(args): - """Detects an optional leading hal.component instance in *args.""" - if args and isinstance(args[0], hal.component): - return args[0], args[1:] - return None, args - - def _cross3(a, b): return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] - def _polar3(v, stretch=1.0): length = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]) * stretch axis = (1, 0, 0) if hypot(v[0], v[1]) < 0.001 else _cross3(v, (0, 0, 1)) angle = -atan2(hypot(v[0], v[1]), v[2]) * 180.0 / pi return (length, angle, axis) - class ArgsBase(object): - """Resolves static numbers or HAL pin strings against an optional hal.component.""" - def __init__(self, comp, *args): + """Resolves static values, 'prefix.attr' paths, and '{prefix.attr}' expressions.""" + def __init__(self, *args): + if args and (args[0] is None or _is_valid_prefix_obj(args[0])): + comp, rest = args[0], args[1:] + if isinstance(comp, linuxcnc.stat): + _register_stat(comp) + else: + comp, rest = _split_comp(args) + self.comp = comp - self._args = args + self._args = rest + if not any(isinstance(v, str) for v in rest): + self._static_vals = list(rest) + self._resolvers = None + else: + self._static_vals = None + prefix_cache = _capture_caller_prefixes() + self._resolvers = [_compile_arg(v, comp, prefix_cache) for v in rest] + + # redundant once we move to OpenGl 3.3 + @property + def q(self): + quad = self.__dict__.get("_q") + if quad is None: + quad = gluNewQuadric() + self.__dict__["_q"] = quad + return quad def coords(self): - return [self.comp[v] if isinstance(v, str) else v for v in self._args] + if self._static_vals is not None: + return self._static_vals + return [fn() for fn in self._resolvers] def cross(self, a, b): return _cross3(a, b) @@ -89,6 +282,9 @@ def cross(self, a, b): def polar(self, v, stretch=1.0): return _polar3(v, stretch) +# legacy used in: /rotarydelta.py:61:class HexPrismZ(CoordsBase) +CoordsBase = ArgsBase + class Translate(Collection, ArgsBase): """ @@ -292,69 +488,165 @@ def unapply(self): HalShow = Show -class Track(Collection): - '''move and rotate an object to point from one capture()'d - coordinate system to another. - we need "world" to convert coordinates from GL_MODELVIEW coordinates - to our coordinate system''' - def __init__(self, parts, position, target, world): +def matmul(a, b): + """Multiplies two 4x4 transformation matrices.""" + out = [[0.0] * 4 for _ in range(4)] + for i in range(4): + for j in range(4): + out[i][j] = ( + a[i][0] * b[0][j] + + a[i][1] * b[1][j] + + a[i][2] * b[2][j] + + a[i][3] * b[3][j] + ) + return out + +def invert(src): + '''' function to invert a transform matrix based on + http://steve.hollasch.net/cgindex/math/matrix/afforthinv.c with simplifications since + we don't do scaling. + This function inverts a 4x4 matrix that is affine and orthogonal. In other words, + the perspective components are [0 0 0 1], and the basis vectors are orthogonal to + each other. In addition, the matrix must not do scaling''' + r00, r01, r02 = src[0][0], src[0][1], src[0][2] + r10, r11, r12 = src[1][0], src[1][1], src[1][2] + r20, r21, r22 = src[2][0], src[2][1], src[2][2] + tx, ty, tz = src[3][0], src[3][1], src[3][2] + return [ + [r00, r10, r20, 0.0], + [r01, r11, r21, 0.0], + [r02, r12, r22, 0.0], + [ + -(tx * r00 + ty * r01 + tz * r02), + -(tx * r10 + ty * r11 + tz * r12), + -(tx * r20 + ty * r21 + tz * r22), + 1.0, + ], + ] + +class Track(Collection, ArgsBase): + """move and rotate an object to point from one capture()'d coordinate system to another. + We need "world" to convert coordinates from GL_MODELVIEW coordinates to our coordinate system + Supports: + - Track(parts, position, target, world) + - Track(parts, prefix, position, target, world) + """ + def __init__(self, parts, *args): self.parts = parts - self.target = target - self.position = position - self.world2view = world - - def angle_to(self,x,y,z): - '''returns polar coordinates in degrees to a point from the origin - a rotates around the x-axis; b rotates around the y axis; r is the distance''' - azimuth = atan2(y, x)*180/pi #longitude - elevation = atan2(z, sqrt(x**2 + y**2))*180/pi - radius = sqrt(x**2+y**2+z**2) - return((azimuth, elevation, radius)) - - def map_coords(self,tx,ty,tz,transform): - # now we have to transform them to the world frame - wx = tx*transform[0][0]+ty*transform[1][0]+tz*transform[2][0]+transform[3][0] - wy = tx*transform[0][1]+ty*transform[1][1]+tz*transform[2][1]+transform[3][1] - wz = tx*transform[0][2]+ty*transform[1][2]+tz*transform[2][2]+transform[3][2] - return([wx,wy,wz]) + comp, rest = _split_comp(args) + if len(rest) != 3: + raise TypeError("Track expects (parts, [prefix,] position, target, world)") + + position, target, world = rest + self.world = world + + expr_args = [] + if isinstance(position, (list, tuple)): + if len(position) != 3: + raise ValueError("Track position list must have 3 coordinates") + self._pos_capture = None + self._pos_slice = (0, 3) + expr_args.extend(position) + else: + self._pos_capture = position + self._pos_slice = None + + if isinstance(target, (list, tuple)): + if len(target) != 3: + raise ValueError("Track target list must have 3 coordinates") + self._tgt_capture = None + start = len(expr_args) + self._tgt_slice = (start, start + 3) + expr_args.extend(target) + else: + self._tgt_capture = target + self._tgt_slice = None + + ArgsBase.__init__(self, comp, *expr_args) + + def _resolve_endpoints(self, vals): + w_inv = invert(self.world.t) + if self._pos_capture is not None: + p = matmul(self._pos_capture.t, w_inv) + x1, y1, z1 = p[3][0], p[3][1], p[3][2] + else: + x1, y1, z1 = vals[self._pos_slice[0]:self._pos_slice[1]] + + if self._tgt_capture is not None: + t = matmul(self._tgt_capture.t, w_inv) + x2, y2, z2 = t[3][0], t[3][1], t[3][2] + else: + x2, y2, z2 = vals[self._tgt_slice[0]:self._tgt_slice[1]] + + return x1, y1, z1, x2, y2, z2 def apply(self): - # make sure we have something to work with first - if len(self.world2view.t) < 4: + vals = self.coords() + x1, y1, z1, x2, y2, z2 = self._resolve_endpoints(vals) + dx, dy, dz = x2 - x1, y2 - y1, z2 - z1 + length = sqrt(dx * dx + dy * dy + dz * dz) + if length < 1e-9: glPushMatrix() + glTranslatef(x1, y1, z1) return - view2world = invert(self.world2view.t) - px, py, pz = self.position.t[3][:3] - px, py, pz = self.map_coords(px,py,pz,view2world) - tx, ty, tz = self.target.t[3][:3] - tx, ty, tz = self.map_coords(tx,ty,tz,view2world) - dx = tx - px; dy = ty - py; dz = tz - pz; - (az,el,r) = self.angle_to(dx,dy,dz) - if(hasattr(HUD, "debug_track") and HUD.debug_track == 1): - HUD.strs = [] - HUD.strs += ["current coords: %3.4f %3.4f %3.4f " % (px, py, pz)] - HUD.strs += ["target coords: %3.4f %3.4f %3.4f" % (tx, ty, tz)] - HUD.strs += ["az,el,r: %3.4f %3.4f %3.4f" % (az,el,r)] + axis = (1, 0, 0) if hypot(dx, dy) < 0.001 else self.cross((dx, dy, dz), (0, 0, 1)) + angle = -atan2(hypot(dx, dy), dz) * 180.0 / pi glPushMatrix() - glTranslatef(px,py,pz) - glRotatef(az-90,0,0,1) - glRotatef(el-90,1,0,0) + glTranslatef(x1, y1, z1) + glRotatef(angle, *axis) def unapply(self): - glPopMatrix() + glPopMatrix() -class CoordsBase(ArgsBase): +def _is_parts_list(obj): + if isinstance(obj, Collection): + return True + if isinstance(obj, (list, tuple)): + if len(obj) == 0: + return True + if len(obj) not in (3, 4): + return True + return hasattr(obj[0], "traverse") or hasattr(obj[0], "draw") + return False + +class Color(Collection, ArgsBase): + """ + Supports: + - Color(parts, color) + - Color(parts, prefix, color) + - Color(color, parts) # legacy swapped order + """ def __init__(self, *args): - if args and (args[0] is None or isinstance(args[0], hal.component)): - comp, rest = args[0], args[1:] + if not args: + raise TypeError("Color expects (parts, [prefix,] color) or (color, parts)") + if _is_parts_list(args[0]): + parts = args[0] + comp, rest = _split_comp(args[1:]) + if len(rest) != 1: + raise TypeError("Color expects (parts, [prefix,] color)") + color = rest[0] + elif len(args) == 2 and _is_parts_list(args[1]): + color, parts, comp = args[0], args[1], None else: - comp, rest = _split_comp(args) - ArgsBase.__init__(self, comp, *rest) - self.q = gluNewQuadric() + raise TypeError("Color expects (parts, [prefix,] color) or (color, parts)") + + self.parts = parts + rgba = list(color) + ([1.0] if len(color) == 3 else []) + if len(rgba) != 4: + raise ValueError("Color specification must have 3 (RGB) or 4 (RGBA) channels") + ArgsBase.__init__(self, comp, *rgba) + + def apply(self): + rgba = self.coords() + glPushAttrib(GL_LIGHTING_BIT) + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, rgba) + + def unapply(self): + glPopAttrib() -class Line(CoordsBase): +class Line(ArgsBase): def __init__(self, *args, **kwargs): comp, rest = _split_comp(args) if len(rest) < 6 or len(rest) > 8: @@ -362,7 +654,7 @@ def __init__(self, *args, **kwargs): x1, y1, z1, x2, y2, z2 = rest[:6] stretch = rest[6] if len(rest) >= 7 else kwargs.get("stretch", 1) r = rest[7] if len(rest) == 8 else kwargs.get("r", 5) - CoordsBase.__init__(self, comp, x1, y1, z1, x2, y2, z2, stretch, r) + ArgsBase.__init__(self, comp, x1, y1, z1, x2, y2, z2, stretch, r) def draw(self): x1, y1, z1, x2, y2, z2, stretch, r = self.coords() @@ -409,8 +701,7 @@ def _draw_grid_lines(s): glVertex3f(i, s_int, 0) glEnd() - -class Grid(CoordsBase): +class Grid(ArgsBase): """ Unifies legacy classes: - HalGrid([comp,] s=500) @@ -424,17 +715,17 @@ def __init__(self, *args, **kwargs): if n in (0, 1): self._mode = "origin" s = rest[0] if n == 1 else kwargs.get("s", 500) - CoordsBase.__init__(self, comp, s) + ArgsBase.__init__(self, comp, s) elif n in (6, 7): self._mode = "normal" x, y, z, vx, vy, vz = rest[:6] s = rest[6] if n == 7 else kwargs.get("s", 500) - CoordsBase.__init__(self, comp, x, y, z, vx, vy, vz, s) + ArgsBase.__init__(self, comp, x, y, z, vx, vy, vz, s) elif n in (9, 10): self._mode = "normal_dir" ox, oy, oz, xx, xy, xz, zx, zy, zz = rest[:9] s = rest[9] if n == 10 else kwargs.get("s", 500) - CoordsBase.__init__(self, comp, ox, oy, oz, xx, xy, xz, zx, zy, zz, s) + ArgsBase.__init__(self, comp, ox, oy, oz, xx, xy, xz, zx, zy, zz, s) else: raise TypeError( "Grid expects 0-1, 6-7 (origin + normal), or " @@ -463,7 +754,7 @@ def unapply(self): HalGridFromNormalAndDirection = Grid -class Plane(CoordsBase): +class Plane(ArgsBase): """ Replaces legacy class: - HalPlaneFromNormal([comp,] x, y, z, vx, vy, vz, s=500) @@ -478,17 +769,17 @@ def __init__(self, *args, **kwargs): if n in (0, 1): self._mode = "origin" s = rest[0] if n == 1 else kwargs.get("s", 500) - CoordsBase.__init__(self, comp, s) + ArgsBase.__init__(self, comp, s) elif n in (6, 7): self._mode = "normal" x, y, z, vx, vy, vz = rest[:6] s = rest[6] if n == 7 else kwargs.get("s", 500) - CoordsBase.__init__(self, comp, x, y, z, vx, vy, vz, s) + ArgsBase.__init__(self, comp, x, y, z, vx, vy, vz, s) elif n in (9, 10): self._mode = "normal_dir" ox, oy, oz, xx, xy, xz, zx, zy, zz = rest[:9] s = rest[9] if n == 10 else kwargs.get("s", 500) - CoordsBase.__init__(self, comp, ox, oy, oz, xx, xy, xz, zx, zy, zz, s) + ArgsBase.__init__(self, comp, ox, oy, oz, xx, xy, xz, zx, zy, zz, s) else: raise TypeError("Plane expects 0-1, 6-7, or 9-10 arguments after optional comp") @@ -521,7 +812,7 @@ def unapply(self): HalPlaneFromNormal = Plane -class Coords(CoordsBase): +class Coords(ArgsBase): """ Replaces legacy class: - HalCoordsFromNormalAndDirection ([comp,] ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch=1, r=5) @@ -537,19 +828,19 @@ def __init__(self, *args, **kwargs): self._mode = "origin" stretch = rest[0] if n >= 1 else kwargs.get("stretch", 1) r = rest[1] if n == 2 else kwargs.get("r", 5) - CoordsBase.__init__(self, comp, stretch, r) + ArgsBase.__init__(self, comp, stretch, r) elif n in (6, 7, 8): self._mode = "normal" ox, oy, oz, zx, zy, zz = rest[:6] stretch = rest[6] if n >= 7 else kwargs.get("stretch", 1) r = rest[7] if n == 8 else kwargs.get("r", 5) - CoordsBase.__init__(self, comp, ox, oy, oz, zx, zy, zz, stretch, r) + ArgsBase.__init__(self, comp, ox, oy, oz, zx, zy, zz, stretch, r) elif n in (9, 10, 11): self._mode = "normal_dir" ox, oy, oz, xx, xy, xz, zx, zy, zz = rest[:9] stretch = rest[9] if n >= 10 else kwargs.get("stretch", 1) r = rest[10] if n == 11 else kwargs.get("r", 5) - CoordsBase.__init__(self, comp, ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch, r) + ArgsBase.__init__(self, comp, ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch, r) else: raise TypeError("Coords expects 0-2, 6-8, or 9-11 arguments after optional comp") @@ -583,7 +874,7 @@ def unapply(self): HalCoordsFromNormalAndDirection = Coords -class _CylinderAxis(CoordsBase): +class _CylinderAxis(ArgsBase): """Shared base class for axis-aligned capped cylinders (X, Y, or Z).""" _axis_rotation = None # (angle_deg, x, y, z) or None for Z-axis @@ -629,7 +920,7 @@ class CylinderZ(_CylinderAxis): # give center and radius -class Sphere(CoordsBase): +class Sphere(ArgsBase): def draw(self): x, y, z, r = self.coords() # need to translate the whole thing to x,y,z @@ -648,7 +939,7 @@ def volume(self): # triangular plate in XY plane # specify the corners Z values for each side -class TriangleXY(CoordsBase): +class TriangleXY(ArgsBase): def draw(self): x1, y1, x2, y2, x3, y3, z1, z2 = self.coords() x12 = x1-x2 @@ -762,7 +1053,7 @@ def volume(self): return vol -class ArcX(CoordsBase): +class ArcX(ArgsBase): def draw(self): x1, x2, r1, r2, a1, a2, steps = self.coords() if x1 > x2: @@ -871,7 +1162,7 @@ def volume(self): # six coordinate version - specify each side of the box -class Box(CoordsBase): +class Box(ArgsBase): def draw(self): x1, y1, z1, x2, y2, z2 = self.coords() if x1 > x2: @@ -936,52 +1227,62 @@ def volume(self): # specify the width in X and Y, and the height in Z # the box is centered on the origin class BoxCentered(Box): - def __init__(self, xw, yw, zw): - Box.__init__(self, -xw/2.0, -yw/2.0, -zw/2.0, xw/2.0, yw/2.0, zw/2.0) + def __init__(self, *args): + comp, rest = _split_comp(args) + if len(rest) == 0: + ArgsBase.__init__(self, comp) + elif len(rest) == 3: + ArgsBase.__init__(self, comp, *rest) + else: + raise TypeError("BoxCentered expects ([prefix,] xw, yw, zw)") + + def coords(self): + xw, yw, zw = ArgsBase.coords(self) + return [-xw / 2.0, -yw / 2.0, -zw / 2.0, xw / 2.0, yw / 2.0, zw / 2.0] + # specify the width in X and Y, and the height in Z # the box is centered in X and Y, and runs from Z=0 up # (or down) to the specified Z value class BoxCenteredXY(Box): - def __init__(self, xw, yw, zw): - Box.__init__(self, -xw/2.0, -yw/2.0, 0, xw/2.0, yw/2.0, zw) + def __init__(self, *args): + comp, rest = _split_comp(args) + if len(rest) == 0: + ArgsBase.__init__(self, comp) + elif len(rest) == 3: + ArgsBase.__init__(self, comp, *rest) + else: + raise TypeError("BoxCenteredXY expects ([prefix,] xw, yw, zw)") + + def coords(self): + xw, yw, zw = ArgsBase.coords(self) + return [-xw / 2.0, -yw / 2.0, 0, xw / 2.0, yw / 2.0, zw] + # capture current transformation matrix # note that this transforms from the current coordinate system # to the viewport system, NOT to the world system class Capture(object): def __init__(self): - self.t = [] + self.t = [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ] def capture(self): self.t = glGetDoublev(GL_MODELVIEW_MATRIX) - - def volume(self): - return 0.0 -# function to invert a transform matrix -# based on http://steve.hollasch.net/cgindex/math/matrix/afforthinv.c -# with simplifications since we don't do scaling + def world_pos(self, world=None): + if world is not None: + m = matmul(self.t, invert(world.t)) + return [m[3][0], m[3][1], m[3][2]] + return [self.t[3][0], self.t[3][1], self.t[3][2]] -# This function inverts a 4x4 matrix that is affine and orthogonal. In -# other words, the perspective components are [0 0 0 1], and the basis -# vectors are orthogonal to each other. In addition, the matrix must -# not do scaling + def volume(self): + return 0.0 -def invert(src): - # make a copy - inv=copy.deepcopy(src) - # The inverse of the upper 3x3 is the transpose (since the basis - # vectors are orthogonal to each other. - inv[0][1],inv[1][0] = inv[1][0],inv[0][1] - inv[0][2],inv[2][0] = inv[2][0],inv[0][2] - inv[1][2],inv[2][1] = inv[2][1],inv[1][2] - # The inverse of the translation component is just the negation - # of the translation after dotting with the new upper3x3 rows. */ - inv[3][0] = -(src[3][0]*inv[0][0] + src[3][1]*inv[1][0] + src[3][2]*inv[2][0]) - inv[3][1] = -(src[3][0]*inv[0][1] + src[3][1]*inv[1][1] + src[3][2]*inv[2][1]) - inv[3][2] = -(src[3][0]*inv[0][2] + src[3][1]*inv[1][2] + src[3][2]*inv[2][2]) - return inv # head up display - draws a semi-transparent text box. class Hud(object): @@ -1176,12 +1477,12 @@ def basic_lighting(self): glEnable(GL_DEPTH_TEST) glMatrixMode(GL_MODELVIEW) glLoadIdentity() - - - def redraw(self, *args): + global _stats_fresh if self.winfo_width() == 1: return + poll_all_stats() + _stats_fresh = False self.model.traverse() # current coords: world # the matrices tool2view, work2view, and world2view @@ -1269,17 +1570,6 @@ def redraw(self, *args): def plotclear(self): del self.plotdata[:self.plotlen] -class Color(Collection): - def __init__(self, color, parts): - self.color = color - Collection.__init__(self, parts) - - def apply(self): - glPushAttrib(GL_LIGHTING_BIT) - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, self.color) - - def unapply(self): - glPopAttrib() class AsciiSTL: def __init__(self, filename=None, data=None): @@ -1390,7 +1680,8 @@ def draw(self): old_plotclear = False -def main(model, tool, work, size=10, hud=0, rotation_vectors=None, lat=0, lon=0): +def main(model, tool, work, size=10, hud=0, rotation_vectors=None, lat=0, lon=0, function=None): + _check_stats_ready() app = tkinter.Tk() import nf hidpi = nf.init_hidpi(app) @@ -1434,13 +1725,18 @@ def main(model, tool, work, size=10, hud=0, rotation_vectors=None, lat=0, lon=0) t.pack(fill="both", expand=1) def update(): - global old_plotclear + global old_plotclear, _stats_fresh + _stats_fresh = False + poll_all_stats() + if function: + function() t.tkRedraw() new_plotclear = vcomp["plotclear"] if new_plotclear and not old_plotclear: t.plotclear() - old_plotclear=new_plotclear + old_plotclear = new_plotclear t.after(100, update) + update() def quit(*args): From 073aa8e6128dd02afb62ad8f3658c1ae7b65ffa4 Mon Sep 17 00:00:00 2001 From: David Date: Thu, 3 Dec 2026 11:16:22 +0100 Subject: [PATCH 3/7] vismach: add two-pass transparency and emissive glow to Color Render translucent parts in a second pass after opaque geometry and add configurable emissive glow to Color: - Render opaque geometry (alpha >= 1.0) first with depth writes enabled, followed by a second blended pass (alpha < 1.0) with depth writes disabled so internal components remain visible through translucent parts. - Keep legacy Color(color, parts) strictly backwards-compatible as opaque-only (forcing alpha to 1.0 without transparency or glow). - Add optional glow parameter (0.0..1.0) to Color(parts, [prefix,] color[, glow]) supporting static values, "prefix.attr" paths, and "{prefix.attr}" expressions via GL_EMISSION. - Update vismach.adoc to document two-pass transparency, legacy Color behavior, and glow. --- docs/src/gui/vismach.adoc | 18 +++++--- lib/python/vismach.py | 97 ++++++++++++++++++++++++++++++++------- 2 files changed, 93 insertions(+), 22 deletions(-) diff --git a/docs/src/gui/vismach.adoc b/docs/src/gui/vismach.adoc index 39da7aa872f..8e10535e54b 100644 --- a/docs/src/gui/vismach.adoc +++ b/docs/src/gui/vismach.adoc @@ -325,12 +325,18 @@ model = Collection([base, saddle, head, carousel]) == Other functions -* `part = Color([part], [prefix,] [colorspec])` + - (Legacy swapped order `Color([colorspec], [part])` is also supported.) + - Sets the display color of the part. The `colorspec` consists of the - three RGB values and an optional opacity (default `1.0`), for example - `[1, 0, 0, 0.5]` for a 50% opacity red. Each channel may be a static - number, `"prefix.attr"`, or `"{prefix.attr}"` expression. +* `part = Color([part], [prefix,] [colorspec], glow=0)` + + (Legacy swapped order `Color([colorspec], [part])` is also supported as + opaque only, without transparency or `glow`.) + + Sets the display color and optional emissive glow of the part. The + `colorspec` consists of the three RGB values and an optional opacity + (default `1.0`), for example `[1, 0, 0, 0.5]` for a 50% opacity red. + When opacity is less than `1.0`, the part is automatically rendered in + a second translucent pass after opaque parts so internal components + remain visible (`0.0` fades the part out completely). `glow` (`0.0` to + `1.0`) controls self-illuminated emission (`GL_EMISSION`). Each color + channel and `glow` may be a static number, `"prefix.attr"`, or + `"{prefix.attr}"` expression. * `part = Track([part], [prefix,] position, target, world)` + Aligns `part` along the vector from `position` to `target` in `world` space. `position` and `target` may each be a `Capture()` object or a diff --git a/lib/python/vismach.py b/lib/python/vismach.py index 74758f7e8e8..e65f78ee51b 100644 --- a/lib/python/vismach.py +++ b/lib/python/vismach.py @@ -27,6 +27,8 @@ _registered_stats = [] _stats_fresh = False +_render_pass = "opaque" +_has_transparent = False _EXPR_MATH = { "sin": sin, "cos": cos, "tan": tan, @@ -203,6 +205,9 @@ def __init__(self, parts): def _build_steps(self): steps = [] for p in self.parts: + if isinstance(p, Color): + steps.append(p.traverse) + continue for name in ("apply", "capture", "draw", "traverse", "unapply"): fn = getattr(p, name, None) if fn is not None: @@ -612,30 +617,65 @@ def _is_parts_list(obj): class Color(Collection, ArgsBase): """ + Sets RGBA material color and optional emissive glow (0.0..1.0). Supports: - - Color(parts, color) - - Color(parts, prefix, color) - - Color(color, parts) # legacy swapped order + - Color(parts, color[, glow]) + - Color(parts, prefix, color[, glow]) + - Color(color, parts) # legacy swapped order (opaque only, no glow) """ - def __init__(self, *args): + def __init__(self, *args, **kwargs): if not args: - raise TypeError("Color expects (parts, [prefix,] color) or (color, parts)") + raise TypeError("Color expects (parts, [prefix,] color[, glow]) or (color, parts)") + glow = kwargs.get("glow", 0.0) if _is_parts_list(args[0]): parts = args[0] comp, rest = _split_comp(args[1:]) - if len(rest) != 1: - raise TypeError("Color expects (parts, [prefix,] color)") - color = rest[0] + if len(rest) == 1: + color = rest[0] + elif len(rest) == 2: + color, glow = rest + else: + raise TypeError("Color expects (parts, [prefix,] color[, glow])") + rgba = list(color) + ([1.0] if len(color) == 3 else []) + if len(rgba) != 4: + raise ValueError("Color specification must have 3 (RGB) or 4 (RGBA) channels") elif len(args) == 2 and _is_parts_list(args[1]): - color, parts, comp = args[0], args[1], None + if "glow" in kwargs: + raise TypeError("Legacy Color(color, parts) does not support glow") + color, parts, comp, glow = args[0], args[1], None, 0.0 + if len(color) not in (3, 4): + raise ValueError("Color specification must have 3 (RGB) or 4 (RGBA) channels") + # Since GL_BLEND was off the legacy swapped order has always rendered opaque for any A + rgba = [color[0], color[1], color[2], 1.0] else: - raise TypeError("Color expects (parts, [prefix,] color) or (color, parts)") + raise TypeError("Color expects (parts, [prefix,] color[, glow]) or (color, parts)") self.parts = parts - rgba = list(color) + ([1.0] if len(color) == 3 else []) - if len(rgba) != 4: - raise ValueError("Color specification must have 3 (RGB) or 4 (RGBA) channels") - ArgsBase.__init__(self, comp, *rgba) + self.vol = 0 + ArgsBase.__init__(self, comp, *(rgba + [glow])) + + def traverse(self): + global _has_transparent + r, g, b, a, glow = self.coords() + is_transparent = a < 1.0 + if _render_pass == "opaque": + if is_transparent: + _has_transparent = True + return + elif not is_transparent: + return + if a <= 0.0: + return + + glPushAttrib(GL_LIGHTING_BIT | GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, [r, g, b, a]) + if glow: + g_val = float(glow) + glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, [r * g_val, g * g_val, b * g_val, 1.0]) + else: + glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, [0.0, 0.0, 0.0, 1.0]) + Collection.traverse(self) + glPopAttrib() def apply(self): rgba = self.coords() @@ -796,6 +836,8 @@ def draw(self): n = (zx, zy, zz) _apply_normal_or_basis((ox, oy, oz), n, (xx, xy, xz)) + glPushAttrib(GL_ENABLE_BIT) + glDisable(GL_CULL_FACE) glBegin(GL_QUADS) glNormal3f(*n) glVertex3f(s, s, 0) @@ -803,6 +845,7 @@ def draw(self): glVertex3f(-s, -s, 0) glVertex3f(s, -s, 0) glEnd() + glPopAttrib() def unapply(self): if self._mode != "origin": @@ -1469,6 +1512,7 @@ def basic_lighting(self): glLightfv(GL_LIGHT0+1, GL_AMBIENT, (.0,.0,.0,0)) glLightfv(GL_LIGHT0+1, GL_DIFFUSE, (.0,.0,.4,0)) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, (1,1,1,0)) + glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, (0.0, 0.0, 0.0, 1.0)) glDisable(GL_CULL_FACE) glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) @@ -1479,11 +1523,32 @@ def basic_lighting(self): glLoadIdentity() def redraw(self, *args): - global _stats_fresh + global _stats_fresh, _render_pass, _has_transparent if self.winfo_width() == 1: return poll_all_stats() - _stats_fresh = False + + # Pass 1: Opaque geometry (also updates all Capture() transforms) + _render_pass = "opaque" + _has_transparent = False + glDepthMask(GL_TRUE) + glDisable(GL_BLEND) self.model.traverse() + + # Pass 2: Translucent geometry (only if any alpha < 1.0 was seen) + if _has_transparent: + _render_pass = "transparent" + glEnable(GL_BLEND) + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) + glDepthMask(GL_FALSE) + glEnable(GL_CULL_FACE) + glCullFace(GL_BACK) + self.model.traverse() + glDisable(GL_CULL_FACE) + glDepthMask(GL_TRUE) + glDisable(GL_BLEND) + + _render_pass = "opaque" + _stats_fresh = False # current coords: world # the matrices tool2view, work2view, and world2view # transform from tool/work/world coords to viewport coords From 04fb9f550f843c793ebe99557538802bf45df026 Mon Sep 17 00:00:00 2001 From: David Date: Thu, 3 Dec 2026 15:10:06 +0100 Subject: [PATCH 4/7] vismach: add STL/OBJ loaders with Binary STL, live reload, and Hud expressions Unify STL and OBJ mesh loaders with runtime change-detected reloading and modernize Hud text and conditions with prefix/expression support: - Unify STL and OBJ under _MeshBase (with legacy AsciiSTL and AsciiOBJ aliases), adding automatic Binary STL detection, quad/polygon OBJ triangulation, fallback face-normal calculation, and change-detected reload(filename=None, data=None, force=False). - Support "{prefix.attr}" template expressions (including nested braces and format specifiers) in Hud.add_txt() and prefix/expression evaluation in Hud.add_pin(), show_tag_if_same(), show_tags_in_pin(), and hide_all() while keeping legacy HAL pin fallback. - Update vismach.adoc to document STL/OBJ reload() and Hud expression templates. --- docs/src/gui/vismach.adoc | 33 ++- lib/python/vismach.py | 423 +++++++++++++++++++++++++++----------- 2 files changed, 325 insertions(+), 131 deletions(-) diff --git a/docs/src/gui/vismach.adoc b/docs/src/gui/vismach.adoc index 8e10535e54b..ad9ed96e200 100644 --- a/docs/src/gui/vismach.adoc +++ b/docs/src/gui/vismach.adoc @@ -70,17 +70,26 @@ function tells loadusr it's ready. == Creating Parts It is probably easiest to create geometry in a CAD package and *import* -into the model script with the `AsciiSTL()` or `AsciiOBJ()` functions. +into the model script with the `STL()` or `OBJ()` functions. Both functions can take one of two named arguments, either a filename or raw data: -* `part = AsciiSTL(filename="path/to/file.stl") + - part = AsciiSTL(data="solid part1 facet normal ....") + - part = AsciiOBJ(filename="path/to/file.obj") + - part = AsciiOBJ(data="v 0.123 0.234 0.345 1.0 ...")` + +* `part = STL(filename="path/to/file.stl")` + + `part = STL(data="solid part1 facet normal ....")` + + (Legacy alias: `AsciiSTL`.) + + `part = OBJ(filename="path/to/file.obj")` + + `part = OBJ(data="v 0.123 0.234 0.345 ...")` + + (Legacy alias: `AsciiOBJ`.) + The parts will be created in the Vismach space in the same locations as they occupy in the STL or OBJ space. This means that it may be - possible to assemble the model in the CAD package. + possible to assemble the model in the CAD package. Both ASCII and + Binary STL files or `bytes` buffers are supported automatically, and + Wavefront OBJ files support triangles, quads, and convex polygons with + automatic face normals when `vn` normals are omitted. + + Both loaders provide a `.reload(filename=None, data=None, force=False)` + method to reload geometry from disk or new data at runtime whenever + the source file or buffer changes (pass `force=True` to force a + reload even if unchanged). Alternatively parts can be created inside the model script from a range of *shape primitives*. All primitives accept static numbers, an optional @@ -297,6 +306,7 @@ head = Translate([head],c,"Z",0,0,0.1) # base base = AsciiSTL(filename="./base.stl") base = Color([0.5,0.5,0.5,1],[base]) + # mount head on it base = Collection([head, base]) ---- @@ -343,8 +353,14 @@ model = Collection([base, saddle, head, carousel]) 3-element `[x, y, z]` list containing static numbers, `"prefix.attr"`, or `"{prefix.attr}"` expressions. * `myhud = Hud()` + - Creates a heads-up display in the Vismach GUI to display such items as - axis positions. + Creates a heads-up display in the Vismach GUI to display text, HAL + pins, `linuxcnc.stat` values, and `{prefix.attr}` expressions. + `myhud.add_txt("Z: {{s.actual_position[2]} - {s.g5x_offset[2]}:.3f}")` + evaluates embedded expressions (including math and conditionals) with + optional format specifiers on each redraw, and `add_pin`, + `show_tag_if_same`, `show_tags_in_pin`, and `hide_all` accept both + legacy HAL pin names and `"prefix.attr"` / `"{prefix.attr}"` + expressions. * `tooltip = Capture()` + Think of this as an invisible part that needs to be attached to the tooltip to track the position and orientation of the tool coordinate system. @@ -367,7 +383,6 @@ model = Collection([base, saddle, head, carousel]) the original viewpoint and it is advisable to do as the default initial viewpoint is rather unhelpfully from immediately overhead. ** _size_ sets the extent of the volume visualized in the initial view. -** _hud_ refers to a head-up display of axis positions. ** _function_ is an optional zero-argument callback executed on each periodic update cycle (after `linuxcnc.stat` polling and before redrawing), useful for computing derived values into a Python `dict` diff --git a/lib/python/vismach.py b/lib/python/vismach.py index e65f78ee51b..43802f73eed 100644 --- a/lib/python/vismach.py +++ b/lib/python/vismach.py @@ -21,6 +21,8 @@ from OpenGL.GLU import * from math import * import glnav +import os +import struct import inspect import operator import linuxcnc @@ -1302,6 +1304,209 @@ def coords(self): return [-xw / 2.0, -yw / 2.0, 0, xw / 2.0, yw / 2.0, zw] +def _mesh_source_stamp(filename, data): + """Returns a lightweight stamp for change detection on STL/OBJ sources.""" + if data is None and filename is not None: + st = os.stat(filename) + return ("file", os.path.abspath(filename), st.st_mtime_ns, st.st_size) + if isinstance(data, (str, bytes)): + return ("data", data) + return ("data", tuple(data)) + +def _compute_tri_normal(t): + dx1, dy1, dz1 = t[1][0] - t[0][0], t[1][1] - t[0][1], t[1][2] - t[0][2] + dx2, dy2, dz2 = t[2][0] - t[0][0], t[2][1] - t[0][1], t[2][2] - t[0][2] + return [dy1 * dz2 - dy2 * dz1, dz1 * dx2 - dz2 * dx1, dy1 * dx2 - dy2 * dx1] + +class _MeshBase: + """Shared base for reloadable STL and OBJ mesh loaders.""" + def __init__(self, filename=None, data=None): + self._filename = filename + self._data = data + self._source_stamp = None + self.list = None + self._stale_list = None + self._reset_storage() + self.reload(filename, data, force=True) + + def _reset_storage(self): + pass + + def _read_lines(self, filename=None, data=None): + if data is None: + with open(filename, "r", encoding="utf-8", errors="replace") as f: + return f.readlines() + if isinstance(data, bytes): + return data.decode("utf-8", errors="replace").splitlines() + if isinstance(data, str): + return data.split("\n") + return data + + def reload(self, filename=None, data=None, force=False): + """Reloads geometry only when the source file or data has changed (unless force=True).""" + if filename is not None: + self._filename = filename + self._data = None + elif data is not None: + self._data = data + self._filename = None + + new_stamp = _mesh_source_stamp(self._filename, self._data) + if not force and new_stamp == self._source_stamp: + return False + + self._load(self._filename, self._data) + self._source_stamp = new_stamp + if self.list is not None: + self._stale_list = self.list + self.list = None + return True + + def draw(self): + if self._stale_list is not None: + glDeleteLists(self._stale_list, 1) + self._stale_list = None + if self.list is None: + # OpenGL isn't ready yet in __init__ so the display list + # is created during the first draw + new_list = glGenLists(1) + glNewList(new_list, GL_COMPILE) + try: + self._emit_gl() + finally: + glEndList() + self.list = new_list + self._reset_storage() + glCallList(self.list) + + +class STL(_MeshBase): + """Loads both ASCII and Binary STL files or data buffers.""" + def _reset_storage(self): + self.d = [] + + def _load(self, filename=None, data=None): + raw_bytes = None + if data is None and filename is not None: + with open(filename, "rb") as f: + raw_bytes = f.read() + elif isinstance(data, bytes): + raw_bytes = data + + if raw_bytes is not None: + # Binary STL: 80-byte header + uint32 triangle count + 50 bytes per triangle + if len(raw_bytes) >= 84: + tri_count = struct.unpack("= 3 else None + if n: + glNormal3f(*self.vn[n - 1]) + else: + glNormal3f(*face_n) + glVertex3f(*self.v[v - 1]) + glEnd() + glPopAttrib() + + +AsciiSTL = STL +AsciiOBJ = OBJ + + # capture current transformation matrix # note that this transforms from the current coordinate system # to the viewport system, NOT to the world system @@ -1327,6 +1532,77 @@ def volume(self): return 0.0 +def _compile_hud_val(val, prefix_cache): + """Compiles a HUD value/condition into a zero-arg callable with legacy hal.get_value fallback.""" + if not isinstance(val, str): + return lambda v=val: v + s = val.strip() + if "{" in s or "}" in s: + return _compile_arg(s, None, prefix_cache) + if "." in s and s.split(".", 1)[0] in prefix_cache: + return _resolve_token(s, None, prefix_cache) + return lambda p=s: hal.get_value(p) + +def _compile_hud_template(template, prefix_cache): + """Compiles a HUD text string with optional '{expr}' or '{expr:.3f}' placeholders.""" + s = str(template) + if "{" not in s and "}" not in s: + return lambda text=s: text + + fmt_parts, getters = [], [] + i, n = 0, len(s) + while i < n: + open_idx = s.find("{", i) + if open_idx == -1: + fmt_parts.append(s[i:]) + break + # Only treat '{{...}}' as escaped literal braces when closed by '}}' + if open_idx + 1 < n and s[open_idx + 1] == "{" and "}}" in s[open_idx + 2:]: + close_esc = s.find("}}", open_idx + 2) + fmt_parts.append(s[i:close_esc + 2]) + i = close_esc + 2 + continue + + # Find matching closing '}' accounting for nested '{prefix.attr}' braces + brace_depth = 1 + j = open_idx + 1 + while j < n and brace_depth > 0: + if s[j] == "{": + brace_depth += 1 + elif s[j] == "}": + brace_depth -= 1 + j += 1 + if brace_depth != 0: + raise SyntaxError("Vismach Error: Unmatched '{' in Hud string %r" % template) + + close_idx = j - 1 + fmt_parts.append(s[i:open_idx]) + inner = s[open_idx + 1:close_idx].strip() + + expr_part, spec_part, depth = inner, "", 0 + for idx, ch in enumerate(inner): + if ch == "[": + depth += 1 + elif ch == "]": + depth = max(0, depth - 1) + elif ch == ":" and depth == 0: + expr_part = inner[:idx].strip() + spec_part = inner[idx:] + break + + if not expr_part: + fmt_parts.append("{" + spec_part + "}") + else: + wrapped = expr_part if "{" in expr_part else "{%s}" % expr_part + getters.append(_compile_arg(wrapped, None, prefix_cache)) + fmt_parts.append("{%d%s}" % (len(getters) - 1, spec_part)) + i = close_idx + 1 + + fmt_str = "".join(fmt_parts) + if not getters: + return lambda f=fmt_str: f + return lambda f=fmt_str, gs=getters: f.format(*[g() for g in gs]) + # head up display - draws a semi-transparent text box. class Hud(object): def __init__(self, showme=1): @@ -1359,25 +1635,31 @@ def show(self, string): self.hide_hud = False self.add_txt(string) - # displays a string, optionally a tag or list of tags can be assigned + # displays a string (supports '{prefix.attr}' expressions), optionally a tag or list of tags can be assigned def add_txt(self, string, tag=None): - self.hud_lines += [[str(string), None, tag]] + prefix_cache = _capture_caller_prefixes() + self.hud_lines += [[_compile_hud_template(string, prefix_cache), None, tag]] - # displays a formatted pin value (can be embedded in a string) + # displays a formatted pin or expression value (can be embedded in a string) def add_pin(self, string, pin=None, tag=None): - self.hud_lines += [[str(string), pin, tag]] + prefix_cache = _capture_caller_prefixes() + pin_fn = _compile_hud_val(pin, prefix_cache) if pin is not None else None + self.hud_lines += [[str(string), pin_fn, tag]] - # shows all lines with the specified tag if the pin value = val + # shows all lines with the specified tag if the pin/expression value = val def show_tag_if_same(self, tag, pin, val=True): - self.show_tags += [[tag, pin, val]] + prefix_cache = _capture_caller_prefixes() + self.show_tags += [[tag, _compile_hud_val(pin, prefix_cache), val]] - # shows all lines with a tag equal to the pin value + offset + # shows all lines with a tag equal to the pin/expression value + offset def show_tags_in_pin(self, pin, offs=0): - self.show_tags += [[pin, None, offs]] + prefix_cache = _capture_caller_prefixes() + self.show_tags += [[_compile_hud_val(pin, prefix_cache), None, offs]] - # hides the complete hud if the pin value is equal to val + # hides the complete hud if the pin/expression value is equal to val def hide_all(self, pin, val=True): - self.hide_alls += [[pin, val]] + prefix_cache = _capture_caller_prefixes() + self.hide_alls += [[_compile_hud_val(pin, prefix_cache), val]] # changes the hud color and transparency def set_hud_rgba(self, r, g, b, a): @@ -1399,16 +1681,19 @@ def draw(self): # check if hud should be hidden hide_hud_requested = False for a in self.hide_alls: - if hal.get_value(a[0]) == a[1]: + cur_val = a[0]() if callable(a[0]) else hal.get_value(a[0]) + if cur_val == a[1]: hide_hud_requested = True if not self.hide_hud and not hide_hud_requested: # create list of all line tags to be shown for b in self.show_tags: tag = None if b[1] == None: # _show_tags_in_pin - tag = int(hal.get_value(b[0]) + b[2]) + raw_val = b[0]() if callable(b[0]) else hal.get_value(b[0]) + tag = int(raw_val + b[2]) else: # _show_tag_if_same - if hal.get_value(b[1]) == b[2]: + cur_val = b[1]() if callable(b[1]) else hal.get_value(b[1]) + if cur_val == b[2]: tag = b[0] if not isinstance(tag, list): tag = [tag] @@ -1420,9 +1705,10 @@ def draw(self): c[2] = [c[2]] if any(item in c[2] for item in show_list): if c[1] == None: # _txt - messages += [c[0]] + messages += [c[0]() if callable(c[0]) else c[0]] else: # _pin - messages += [c[0].format(hal.get_value(c[1]))] + val = c[1]() if callable(c[1]) else hal.get_value(c[1]) + messages += [c[0].format(val)] drawtext = self.strs + messages # draw head-up-display @@ -1636,113 +1922,6 @@ def plotclear(self): del self.plotdata[:self.plotlen] -class AsciiSTL: - def __init__(self, filename=None, data=None): - if data is None: - data = open(filename, "r") - elif isinstance(data, str): - data = data.split("\n") - self.list = None - t = [] - n = [0,0,0] - self.d = d = [] - for line in data: - if line.find("normal") != -1: - line = line.split() - x, y, z = list(map(float, line[-3:])) - n = [x,y,z] - elif line.find("vertex") != -1: - line = line.split() - x, y, z = list(map(float, line[-3:])) - t.append([x,y,z]) - if len(t) == 3: - if n == [0,0,0]: - dx1 = t[1][0] - t[0][0] - dy1 = t[1][1] - t[0][1] - dz1 = t[1][2] - t[0][2] - dx2 = t[2][0] - t[0][0] - dy2 = t[2][1] - t[0][1] - dz2 = t[2][2] - t[0][2] - n = [dy1*dz2 - dy2*dz1, dz1*dx2 - dz2*dx1, dy1*dx2 - dy2*dx1] - d.append((n, t)) - t = [] - n = [0,0,0] - - def draw(self): - if self.list is None: - # OpenGL isn't ready yet in __init__ so the display list - # is created during the first draw - self.list = glGenLists(1) - glNewList(self.list, GL_COMPILE) - glBegin(GL_TRIANGLES) - for n, t in self.d: - glNormal3f(*n) - glVertex3f(*t[0]) - glVertex3f(*t[1]) - glVertex3f(*t[2]) - glEnd() - glEndList() - del self.d - glCallList(self.list) - -class AsciiOBJ: - def __init__(self, filename=None, data=None): - if data is None: - data = open(filename, "r") - elif isinstance(data, str): - data = data.split("\n") - - self.v = v = [] - self.vn = vn = [] - self.f = f = [] - for line in data: - if line.startswith("#"): continue - if line.startswith("vn"): - vn.append([float(w) for w in line.split()[1:]]) - elif line.startswith("v"): - v.append([float(w) for w in line.split()[1:]]) - elif line.startswith("f"): - f.append(self.parse_face(line)) - -# print v[:5] -# print vn[:5] -# print f[:5] - - self.list = None - - - def parse_int(self, i): - if i == '': return None - return int(i) - - def parse_slash(self, word): - return [self.parse_int(i) for i in word.split("/")] - - def parse_face(self, line): - return [self.parse_slash(w) for w in line.split()[1:]] - - def draw(self): - if self.list is None: - # OpenGL isn't ready yet in __init__ so the display list - # is created during the first draw - self.list = glGenLists(1) - glNewList(self.list, GL_COMPILE) - glDisable(GL_CULL_FACE) - glBegin(GL_TRIANGLES) - #print "obj", len(self.f) - for f in self.f: - for v, t, n in f: - if n: - glNormal3f(*self.vn[n-1]) - glVertex3f(*self.v[v-1]) - glEnd() - glEndList() - del self.v - del self.vn - del self.f - glCallList(self.list) - - old_plotclear = False def main(model, tool, work, size=10, hud=0, rotation_vectors=None, lat=0, lon=0, function=None): From e0ebc8e7dc3db542e54094477ac7928136ce5667 Mon Sep 17 00:00:00 2001 From: David Date: Fri, 4 Dec 2026 14:54:32 +0100 Subject: [PATCH 5/7] vismach: replace fixed-function matrix stack with pure-Python 4x4 matrices Introduce a column-major 4x4 matrix stack (_Mat4) and migrate all scene transforms, primitives, Track, Capture, and delta models away from OpenGL fixed-function matrix operations: - Add column-major 4x4 matrix helpers (_Mat4) and update Translate, VectorTranslate, Scale, Rotate, RotateEuler, Show, Track, Capture, and primitives to use the Python matrix stack instead of glPushMatrix, glPopMatrix, glTranslate*, glRotate*, glScale*, glMultMatrix*, and glGetDoublev. - Update lineardelta.py and rotarydelta.py to use standard Vismach primitives (TriangleXY, CylinderZ, Track, Scale) and _Mat4-ready transforms without direct legacy OpenGL calls. --- configs/sim/axis/vismach/delta/lineardelta.py | 235 ++++------- configs/sim/axis/vismach/delta/rotarydelta.py | 268 ++++++------ lib/python/vismach.py | 395 ++++++++++++------ 3 files changed, 487 insertions(+), 411 deletions(-) diff --git a/configs/sim/axis/vismach/delta/lineardelta.py b/configs/sim/axis/vismach/delta/lineardelta.py index 82b27967400..cadf395c2e8 100755 --- a/configs/sim/axis/vismach/delta/lineardelta.py +++ b/configs/sim/axis/vismach/delta/lineardelta.py @@ -14,6 +14,7 @@ # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + from vismach import * import hal import lineardeltakins @@ -35,172 +36,112 @@ c['R'], c['L'] = lineardeltakins.get_geometry() c.ready() -class DeltaTranslate(Collection): +class DeltaTranslate(Translate): + """Computes forward linear delta kinematics and feeds Translate.""" def __init__(self, parts, comp): self.comp = comp self.parts = parts - self.x = self.y = self.z = 0 + self.x = self.y = self.z = 0.0 - def apply(self): - glPushMatrix() - lineardeltakins.set_geometry(self.comp['R'], self.comp['L']) - f = lineardeltakins.forward(self.comp['joint0'], self.comp['joint1'], self.comp['joint2']) + def coords(self): + lineardeltakins.set_geometry(self.comp["R"], self.comp["L"]) + f = lineardeltakins.forward( + self.comp["joint0"], self.comp["joint1"], self.comp["joint2"] + ) if f is not None: - self.x = x = f[0] - self.y = y = f[1] - self.z = z = f[2] - else: - x = self.x - y = self.y - z = self.z - glTranslatef(x, y, z) - - def unapply(self): - glPopMatrix() - -class TriangularPrismZ: - def __init__(self, z0, z1, h): - self.z0 = z0 - self.z1 = z1 - self.h = h - - def draw(self): - x0 = 0 - x1 = -self.h*sin(pi/3) - x2 = self.h*sin(pi/3) - y0 = self.h - y1 = y2 = -self.h*cos(pi/3) - z0 = self.z0 - z1 = self.z1 - - glBegin(GL_TRIANGLES) - glNormal3f(0, 0, 1) - glVertex3f(x0, y0, z1) - glVertex3f(x1, y1, z1) - glVertex3f(x2, y2, z1) - - glNormal3f(0, 0, -1) - glVertex3f(x2, y2, z0) - glVertex3f(x1, y1, z0) - glVertex3f(x0, y0, z0) - - glNormal3f(-cos(pi/3), sin(pi/3), 0) - glVertex3f(x0, y0, z1) - glVertex3f(x1, y1, z0) - glVertex3f(x1, y1, z1) - glVertex3f(x0, y0, z1) - glVertex3f(x0, y0, z0) - glVertex3f(x1, y1, z0) - - glNormal3f(0, -1, 0) - glVertex3f(x1, y1, z1) - glVertex3f(x2, y2, z0) - glVertex3f(x2, y2, z1) - glVertex3f(x1, y1, z1) - glVertex3f(x1, y1, z0) - glVertex3f(x2, y2, z0) - - glNormal3f(cos(pi/3), sin(pi/3), 0) - glVertex3f(x2, y2, z1) - glVertex3f(x0, y0, z0) - glVertex3f(x0, y0, z1) - glVertex3f(x2, y2, z1) - glVertex3f(x2, y2, z0) - glVertex3f(x0, y0, z0) - - glEnd() -def build_joint(angle, joint): + self.x, self.y, self.z = f[0], f[1], f[2] + return [1, self.x, self.y, self.z] + + +def build_triangular_prism_z(z0, z1, h): + """Builds an equilateral triangular prism along Z using TriangleXY.""" + x0 = 0.0 + x1 = -h * sin(pi / 3.0) + x2 = h * sin(pi / 3.0) + y0 = h + y1 = y2 = -h * cos(pi / 3.0) + return TriangleXY(x0, y0, x1, y1, x2, y2, z0, z1) + + +def build_joint(angle, joint, carr_left, carr_right): + """Builds a vertical rail, sliding carriage, and two strut Capture anchors.""" + oo = 0.4 * CARRIAGE_OFFSET return Rotate([ Translate([ - HalTranslate([ + Translate([ CylinderZ(MIN_JOINT, 5, MAX_JOINT, 5), - HalTranslate([ - Box(-CARRIAGE_OFFSET, -20, -20, 0, 20, 20) - ], c, joint, 0, 0, 1) - ], c, "R", 1, 0, 0) - ], EFFECTOR_OFFSET + CARRIAGE_OFFSET, 0, 0) + Translate([ + Box(-CARRIAGE_OFFSET, -20, -20, 0, 20, 20), + Translate([carr_left], -CARRIAGE_OFFSET, oo, 0), + Translate([carr_right], -CARRIAGE_OFFSET, -oo, 0), + ], c, joint, 0, 0, 1), + ], c, "R", 1, 0, 0), + ], EFFECTOR_OFFSET + CARRIAGE_OFFSET, 0, 0), ], angle, 0, 0, 1) -class Strut: - def __init__(self, platform, angle, component, joint): - self.platform = platform - self.angle = radians(angle) - self.component = component - self.joint = joint - self.q = gluNewQuadric() - - def draw(self): - c = cos(self.angle) - s = sin(self.angle) - o = CARRIAGE_OFFSET - oo = .4 * o - x0 = self.platform.x + c*o - sx = oo * -s - y0 = self.platform.y + s*o - sy = oo * c - z0 = self.platform.z - r2 = self.component['R'] + CARRIAGE_OFFSET - x1 = r2 * cos(self.angle) - y1 = r2 * sin(self.angle) - z1 = self.component[self.joint] - - d = x1-x0, y1-y0, z1-z0 - mag = sqrt(sum(di*di for di in d)) - dx, dy, dz = (di/mag for di in d) - L = self.component['L'] - theta = atan2(dz, hypot(dx,dy)) - phi = atan2(dy, dx) - - glPushMatrix() - glTranslatef(x0+sx, y0+sy, z0) - glRotatef(degrees(phi), 0, 0, 1) - glRotatef(90-degrees(theta), 0, 1, 0) - self.cylinder(L) - glPopMatrix() - - glPushMatrix() - glTranslatef(x0-sx, y0-sy, z0) - glRotatef(degrees(phi), 0, 0, 1) - glRotatef(90-degrees(theta), 0, 1, 0) - self.cylinder(L) - glPopMatrix() - - def cylinder(self, L): - gluCylinder(self.q, 5, 5, L, 32, 1) - # bottom cap - glRotatef(180,1,0,0) - gluDisk(self.q, 0, 5, 32, 1) - glRotatef(180,1,0,0) - # the top cap needs flipped and translated - glTranslatef(0,0, L) - gluDisk(self.q, 0, 5, 32, 1) - + +def build_strut_pair(plat_left, plat_right, carr_left, carr_right, world_cap): + """Connects two platform anchors to two carriage anchors with capped CylinderZ rods.""" + return Collection([ + Track([CylinderZ(c, 0, 5, "L", 5)], plat_left, carr_left, world_cap), + Track([CylinderZ(c, 0, 5, "L", 5)], plat_right, carr_right, world_cap), + ]) + + + +world = Capture() tooltip = Capture() + +oo = 0.4 * CARRIAGE_OFFSET +plat0_l, plat0_r = Capture(), Capture() +plat1_l, plat1_r = Capture(), Capture() +plat2_l, plat2_r = Capture(), Capture() + +effector_anchors = Collection([ + Rotate([ + Translate([plat0_l], CARRIAGE_OFFSET, oo, 0), + Translate([plat0_r], CARRIAGE_OFFSET, -oo, 0), + ], 90, 0, 0, 1), + Rotate([ + Translate([plat1_l], CARRIAGE_OFFSET, oo, 0), + Translate([plat1_r], CARRIAGE_OFFSET, -oo, 0), + ], 210, 0, 0, 1), + Rotate([ + Translate([plat2_l], CARRIAGE_OFFSET, oo, 0), + Translate([plat2_r], CARRIAGE_OFFSET, -oo, 0), + ], 330, 0, 0, 1), +]) + tool = DeltaTranslate([ + effector_anchors, Translate([ - Color((.5,.5,.5,0), [ - Translate([tooltip], 0,0,-40), - Rotate([TriangularPrismZ(0, 5, EFFECTOR_OFFSET*2)], 180, 0, 0, 1), + Color((0.5, 0.5, 0.5, 0), [ + Translate([tooltip], 0, 0, -40), + Rotate([build_triangular_prism_z(0, 5, EFFECTOR_OFFSET * 2)], 180, 0, 0, 1), CylinderZ(-40, 0, -30, 10), - CylinderZ(-30, 10, 10, 10) + CylinderZ(-30, 10, 10, 10), ]) - ], 0, 0, -5)], c) + ], 0, 0, -5), +], c) -red = (1,.5,.5,0) -green = (.5,1,.5,0) -blue = (.5,.5,1,0) +red = (1, 0.5, 0.5, 0) +green = (0.5, 1, 0.5, 0) +blue = (0.5, 0.5, 1, 0) -joint0 = Color(red, [build_joint(90, "joint0")]) -joint1 = Color(green, [build_joint(210, "joint1")]) -joint2 = Color(blue, [build_joint(330, "joint2")]) +carr0_l, carr0_r = Capture(), Capture() +carr1_l, carr1_r = Capture(), Capture() +carr2_l, carr2_r = Capture(), Capture() -work = Capture() +joint0 = Color(red, [build_joint(90, "joint0", carr0_l, carr0_r)]) +joint1 = Color(green, [build_joint(210, "joint1", carr1_l, carr1_r)]) +joint2 = Color(blue, [build_joint(330, "joint2", carr2_l, carr2_r)]) -strut0 = Color(red, [Strut(tool, 90, c, "joint0")]) -strut1 = Color(green, [Strut(tool, 210, c, "joint1")]) -strut2 = Color(blue, [Strut(tool, 330, c, "joint2")]) +strut0 = Color(red, [build_strut_pair(plat0_l, plat0_r, carr0_l, carr0_r, world)]) +strut1 = Color(green, [build_strut_pair(plat1_l, plat1_r, carr1_l, carr1_r, world)]) +strut2 = Color(blue, [build_strut_pair(plat2_l, plat2_r, carr2_l, carr2_r, world)]) -table = CylinderZ(MIN_JOINT-5, 300, MIN_JOINT, 300) +work = Capture() +table = CylinderZ(MIN_JOINT - 5, 300, MIN_JOINT, 300) -model = Collection([table, joint0, joint1, joint2, tool, strut0, strut1, strut2, work]) +model = Collection([table, joint0, joint1, joint2, tool, strut0, strut1, strut2, work, world]) main(model, tooltip, work, 1500) diff --git a/configs/sim/axis/vismach/delta/rotarydelta.py b/configs/sim/axis/vismach/delta/rotarydelta.py index b6032be6613..4db178caa5b 100755 --- a/configs/sim/axis/vismach/delta/rotarydelta.py +++ b/configs/sim/axis/vismach/delta/rotarydelta.py @@ -35,172 +35,146 @@ c['pfr'], c['tl'], c['sl'], c['fr'] = rotarydeltakins.get_geometry() c.ready() -class DeltaTranslate(Collection): +class DeltaTranslate(Translate): + """Computes forward rotary delta kinematics and feeds Translate.""" def __init__(self, parts, comp): self.comp = comp self.parts = parts - self.x = self.y = self.z = 0 - - def apply(self): - glPushMatrix() - rotarydeltakins.set_geometry(self.comp['pfr'], self.comp['tl'], self.comp['sl'], self.comp['fr']) - f = rotarydeltakins.forward(self.comp['joint0'], self.comp['joint1'], self.comp['joint2']) + self.x = self.y = self.z = 0.0 + + def coords(self): + rotarydeltakins.set_geometry( + self.comp["pfr"], self.comp["tl"], self.comp["sl"], self.comp["fr"] + ) + f = rotarydeltakins.forward( + self.comp["joint0"], self.comp["joint1"], self.comp["joint2"] + ) if f is not None: - self.x = x = f[0] - self.y = y = f[1] - self.z = z = f[2] - else: - x = self.x - y = self.y - z = self.z - glTranslatef(x, y, z) - - def unapply(self): - glPopMatrix() - -class HexPrismZ(CoordsBase): - def draw(self): - z0, z1, h = self.coords() - h /= cos(pi/6) - - glBegin(GL_TRIANGLE_FAN) - glNormal3f(0, 0, 1) - glVertex3f(0, 0, z1) - for i in range(7): - d = (2*pi/6) * i - glVertex3f(h * cos(d), h * sin(d), z1) - glEnd() - - glBegin(GL_TRIANGLE_FAN) - glNormal3f(0, 0, -1) - glVertex3f(0, 0, z0) - for i in range(7): - d = (2*pi/6) * i - glVertex3f(h * cos(d), h * sin(d), z0) - glEnd() - - glBegin(GL_TRIANGLES) - for i in range(6): - d1 = (2*pi/6) * i - cd1 = h * cos(d1) - sd1 = h * sin(d1) - - d2 = (2*pi/6) * (i+1) - cd2 = h * cos(d2) - sd2 = h * sin(d2) - - glNormal3f(cos(d1), sin(d1), 0) - glVertex3f(cd1, sd1, z1) - glVertex3f(cd2, sd2, z0) - glVertex3f(cd2, sd2, z1) - glVertex3f(cd1, sd1, z1) - glVertex3f(cd1, sd1, z0) - glVertex3f(cd2, sd2, z0) - glEnd() - -def build_joint(angle, joint): + self.x, self.y, self.z = f[0], f[1], f[2] + return [1, self.x, self.y, self.z] + + +def build_hex_prism_z(z0, z1, apothem=1.0): + """Builds a regular hexagonal prism along Z from 6 TriangleXY wedges.""" + r = apothem / cos(pi / 6.0) + wedges = [] + for i in range(6): + a1 = (2.0 * pi / 6.0) * i + a2 = (2.0 * pi / 6.0) * (i + 1) + wedges.append( + TriangleXY( + 0.0, 0.0, + r * cos(a1), r * sin(a1), + r * cos(a2), r * sin(a2), + z0, z1, + ) + ) + return Collection(wedges) + + +def build_joint(angle, joint, arm_left, arm_right): + """Builds a rotary delta shoulder pivot, upper arm, and elbow Capture anchors.""" return Rotate([ - HalTranslate([ + Translate([ CylinderY(-1, 1, 6, 1), - HalRotate([ - CylinderX(c, 0, .5, 'tl', .5) - ], c, joint, 1, 0, 1, 0) - ], c, "pfr", 1, 0, 0) + Rotate([ + CylinderX(c, 0, 0.5, "tl", 0.5), + Translate([ + Translate([arm_left], c, 0, "fr", 0, 0.2), + Translate([arm_right], c, 0, "fr", 0, -0.2), + ], c, "tl", 1, 0, 0), + ], c, joint, 1, 0, 1, 0), + ], c, "pfr", 1, 0, 0), ], angle, 0, 0, 1) -class Strut: - def __init__(self, platform, angle, component, joint): - self.platform = platform - self.angle = radians(angle) - self.component = component - self.joint = joint - self.q = gluNewQuadric() - - def draw(self): - c = cos(self.angle) - s = sin(self.angle) - o = self.component['fr'] - oo = .2 * o - x0 = self.platform.x + c*o - sx = oo * -s - y0 = self.platform.y + s*o - sy = oo * c - z0 = self.platform.z - j = -radians(self.component[self.joint]) - r2 = self.component['pfr'] + self.component['tl'] * cos(j) - x1 = r2 * cos(self.angle) - y1 = r2 * sin(self.angle) - z1 = self.component['tl'] * sin(j) - - d = x1-x0, y1-y0, z1-z0 - mag = sqrt(sum(di*di for di in d)) - dx, dy, dz = (di/mag for di in d) - L = self.component['sl'] - theta = atan2(dz, hypot(dx,dy)) - phi = atan2(dy, dx) - - glPushMatrix() - glTranslatef(x0+sx, y0+sy, z0) - glRotatef(degrees(phi), 0, 0, 1) - glRotatef(90-degrees(theta), 0, 1, 0) - self.cylinder(L) - glPopMatrix() - - glPushMatrix() - glTranslatef(x0-sx, y0-sy, z0) - glRotatef(degrees(phi), 0, 0, 1) - glRotatef(90-degrees(theta), 0, 1, 0) - self.cylinder(L) - glPopMatrix() - - def cylinder(self, L): - gluCylinder(self.q, .5, .5, L, 32, 1) - # bottom cap - glRotatef(180,1,0,0) - gluDisk(self.q, 0, .5, 32, 1) - glRotatef(180,1,0,0) - # the top cap needs flipped and translated - glTranslatef(0,0, L) - gluDisk(self.q, 0, .5, 32, 1) - + +def build_strut_pair(plat_left, plat_right, arm_left, arm_right, world_cap): + """Connects two effector platform anchors to two upper-arm elbow anchors.""" + return Collection([ + Track([CylinderZ(c, 0, 0.5, "sl", 0.5)], plat_left, arm_left, world_cap), + Track([CylinderZ(c, 0, 0.5, "sl", 0.5)], plat_right, arm_right, world_cap), + ]) + + +world = Capture() tooltip = Capture() - + +plat0_l, plat0_r = Capture(), Capture() +plat1_l, plat1_r = Capture(), Capture() +plat2_l, plat2_r = Capture(), Capture() + +effector_anchors = Collection([ + Rotate([ + Translate([ + Translate([plat0_l], c, 0, "fr", 0, 0.2), + Translate([plat0_r], c, 0, "fr", 0, -0.2), + ], c, "fr", 1, 0, 0), + ], -90, 0, 0, 1), + Rotate([ + Translate([ + Translate([plat1_l], c, 0, "fr", 0, 0.2), + Translate([plat1_r], c, 0, "fr", 0, -0.2), + ], c, "fr", 1, 0, 0), + ], 30, 0, 0, 1), + Rotate([ + Translate([ + Translate([plat2_l], c, 0, "fr", 0, 0.2), + Translate([plat2_r], c, 0, "fr", 0, -0.2), + ], c, "fr", 1, 0, 0), + ], 150, 0, 0, 1), +]) + +# Unit-apothem hex prism scaled dynamically in X and Y by c["fr"] (Z stays 0..0.5) +hex_plate = Scale([ + Translate([build_hex_prism_z(0, 1, 1.0)], 0, 0, 0) +], c, 1, 1, 0.5, "fr") +# Note: Scale multiplies all 3 axes by "fr", so we counter-scale Z via a wrapper or keep Z=0.5/fr: +hex_plate = Translate([ + Scale([build_hex_prism_z(0, 0.5, 1.0)], c, 1, 1, 0, "fr"), +], 0, 0, 0) tool = DeltaTranslate([ + effector_anchors, Translate([ - Color((.5,.5,.5,0), [ - Translate([tooltip], 0,0,-2), - HexPrismZ(c, 0, .5, 'fr'), - CylinderZ(-2, 0, -1.5, .25), - CylinderZ(-1.5, .25, 1, .25) + Color((0.5, 0.5, 0.5, 0), [ + Translate([tooltip], 0, 0, -2), + # Dynamic XY scaling by "fr" while keeping thickness fixed at 0.5 + Translate([ + Scale([build_hex_prism_z(0, 0.5, 1.0)], c, 1, 1, 0, "fr") + ], 0, 0, 0), + CylinderZ(-2, 0, -1.5, 0.25), + CylinderZ(-1.5, 0.25, 1, 0.25), ]) - ], 0, 0, -.5)], c) + ], 0, 0, -0.5), +], c) -red = (1,.5,.5,0) -green = (.5,1,.5,0) -blue = (.5,.5,1,0) +red = (1, 0.5, 0.5, 0) +green = (0.5, 1, 0.5, 0) +blue = (0.5, 0.5, 1, 0) -joint0 = Color(red, [build_joint(-90, "joint0")]) -joint1 = Color(green, [build_joint(30, "joint1")]) -joint2 = Color(blue, [build_joint(150, "joint2")]) +arm0_l, arm0_r = Capture(), Capture() +arm1_l, arm1_r = Capture(), Capture() +arm2_l, arm2_r = Capture(), Capture() -work = Capture() +joint0 = Color(red, [build_joint(-90, "joint0", arm0_l, arm0_r)]) +joint1 = Color(green, [build_joint(30, "joint1", arm1_l, arm1_r)]) +joint2 = Color(blue, [build_joint(150, "joint2", arm2_l, arm2_r)]) + +strut0 = Color(red, [build_strut_pair(plat0_l, plat0_r, arm0_l, arm0_r, world)]) +strut1 = Color(green, [build_strut_pair(plat1_l, plat1_r, arm1_l, arm1_r, world)]) +strut2 = Color(blue, [build_strut_pair(plat2_l, plat2_r, arm2_l, arm2_r, world)]) -strut0 = Color(red, [Strut(tool, -90, c, "joint0")]) -strut1 = Color(green, [Strut(tool, 30, c, "joint1")]) -strut2 = Color(blue, [Strut(tool, 150, c, "joint2")]) +work = Capture() table = Collection([ CylinderZ(-22, 8, -21, 8), Translate([ - CylinderZ(7, c['pfr']+3.5, 8, c['pfr']+3.5), - Rotate( [Box(1, -c['pfr']+3, 1, 5, -c['pfr']-2, 8)], 0, 0, 0, 1), - Rotate( [Box(1, -c['pfr']+3, 1, 5, -c['pfr']-2, 8)], 120, 0, 0, 1), - Rotate( [Box(1, -c['pfr']+3, 1, 5, -c['pfr']-2, 8)], 240, 0, 0, 1)], - 0, 0, -3) - ]) - -model = Collection([table, joint0, joint1, joint2, tool, -strut0, strut1, strut2, -work]) + CylinderZ(7, c["pfr"] + 3.5, 8, c["pfr"] + 3.5), + Rotate([Box(1, -c["pfr"] + 3, 1, 5, -c["pfr"] - 2, 8)], 0, 0, 0, 1), + Rotate([Box(1, -c["pfr"] + 3, 1, 5, -c["pfr"] - 2, 8)], 120, 0, 0, 1), + Rotate([Box(1, -c["pfr"] + 3, 1, 5, -c["pfr"] - 2, 8)], 240, 0, 0, 1), + ], 0, 0, -3), +]) + +model = Collection([table, joint0, joint1, joint2, tool, strut0, strut1, strut2, work, world]) main(model, tooltip, work, 60) diff --git a/lib/python/vismach.py b/lib/python/vismach.py index 43802f73eed..6d74667e5cc 100644 --- a/lib/python/vismach.py +++ b/lib/python/vismach.py @@ -32,6 +32,194 @@ _render_pass = "opaque" _has_transparent = False +# --------------------------------------------------------------------------- +# Pure-Python Column-Major 4x4 Matrix Stack & Camera Math (OpenGL 3.3 Core) +# --------------------------------------------------------------------------- +_IDENTITY_4X4 = ( + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0, +) +_matrix_stack = [list(_IDENTITY_4X4)] +_proj_matrix = list(_IDENTITY_4X4) +_view_matrix = list(_IDENTITY_4X4) + + +def _mat4_mul(a, b): + """Multiplies two column-major 16-element 4x4 matrices (a * b).""" + out = [0.0] * 16 + for col in range(4): + c4 = col * 4 + b0, b1, b2, b3 = b[c4], b[c4 + 1], b[c4 + 2], b[c4 + 3] + out[c4] = a[0] * b0 + a[4] * b1 + a[8] * b2 + a[12] * b3 + out[c4 + 1] = a[1] * b0 + a[5] * b1 + a[9] * b2 + a[13] * b3 + out[c4 + 2] = a[2] * b0 + a[6] * b1 + a[10] * b2 + a[14] * b3 + out[c4 + 3] = a[3] * b0 + a[7] * b1 + a[11] * b2 + a[15] * b3 + return out + + +def _mat4_to_rows(m): + """Converts a column-major 16-element list into legacy 4x4 row-of-columns format.""" + return [ + [m[0], m[1], m[2], m[3]], + [m[4], m[5], m[6], m[7]], + [m[8], m[9], m[10], m[11]], + [m[12], m[13], m[14], m[15]], + ] + + +def _rows_to_mat4(rows): + """Converts a legacy 4x4 row-of-columns matrix into a column-major 16-element list.""" + return [ + rows[0][0], rows[0][1], rows[0][2], rows[0][3], + rows[1][0], rows[1][1], rows[1][2], rows[1][3], + rows[2][0], rows[2][1], rows[2][2], rows[2][3], + rows[3][0], rows[3][1], rows[3][2], rows[3][3], + ] + + +def _mat4_perspective(fovy_deg, aspect, znear, zfar): + f = 1.0 / tan(radians(fovy_deg) * 0.5) + nf = 1.0 / (znear - zfar) + return [ + f / aspect, 0.0, 0.0, 0.0, + 0.0, f, 0.0, 0.0, + 0.0, 0.0, (zfar + znear) * nf, -1.0, + 0.0, 0.0, 2.0 * zfar * znear * nf, 0.0, + ] + + +def _mat4_ortho(left, right, bottom, top, znear, zfar): + rl = 1.0 / (right - left) + tb = 1.0 / (top - bottom) + fn = 1.0 / (zfar - znear) + return [ + 2.0 * rl, 0.0, 0.0, 0.0, + 0.0, 2.0 * tb, 0.0, 0.0, + 0.0, 0.0, -2.0 * fn, 0.0, + -(right + left) * rl, -(top + bottom) * tb, -(zfar + znear) * fn, 1.0, + ] + + +def _mat4_normal_3x3(mv): + """Computes the 9-element column-major inverse-transpose 3x3 normal matrix from MV.""" + a00, a01, a02 = mv[0], mv[1], mv[2] + a10, a11, a12 = mv[4], mv[5], mv[6] + a20, a21, a22 = mv[8], mv[9], mv[10] + + c00 = a11 * a22 - a12 * a21 + c01 = -(a10 * a22 - a12 * a20) + c02 = a10 * a21 - a11 * a20 + + c10 = -(a01 * a22 - a02 * a21) + c11 = a00 * a22 - a02 * a20 + c12 = -(a00 * a21 - a01 * a20) + + c20 = a01 * a12 - a02 * a11 + c21 = -(a00 * a12 - a02 * a10) + c22 = a00 * a11 - a01 * a10 + + det = a00 * c00 + a01 * c01 + a02 * c02 + if abs(det) < 1e-12: + return (1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0) + inv_det = 1.0 / det + return ( + c00 * inv_det, c01 * inv_det, c02 * inv_det, + c10 * inv_det, c11 * inv_det, c12 * inv_det, + c20 * inv_det, c21 * inv_det, c22 * inv_det, + ) + + +def _load_matrix(m): + _matrix_stack[-1] = list(m) + + +def _push_matrix(): + _matrix_stack.append(list(_matrix_stack[-1])) + + +def _pop_matrix(): + if len(_matrix_stack) > 1: + _matrix_stack.pop() + + +def _current_matrix(): + return _matrix_stack[-1] + + +def _translate(x, y, z): + m = _matrix_stack[-1] + fx, fy, fz = float(x), float(y), float(z) + m[12] += m[0] * fx + m[4] * fy + m[8] * fz + m[13] += m[1] * fx + m[5] * fy + m[9] * fz + m[14] += m[2] * fx + m[6] * fy + m[10] * fz + m[15] += m[3] * fx + m[7] * fy + m[11] * fz + + +def _scale(sx, sy, sz): + m = _matrix_stack[-1] + fx, fy, fz = float(sx), float(sy), float(sz) + m[0] *= fx; m[1] *= fx; m[2] *= fx; m[3] *= fx + m[4] *= fy; m[5] *= fy; m[6] *= fy; m[7] *= fy + m[8] *= fz; m[9] *= fz; m[10] *= fz; m[11] *= fz + + +def _rotate(angle_deg, x, y, z): + if angle_deg == 0.0: + return + m = _matrix_stack[-1] + rad = radians(angle_deg) + c = cos(rad) + s = sin(rad) + if x == 1.0 and y == 0.0 and z == 0.0: + m4, m5, m6, m7 = m[4], m[5], m[6], m[7] + m8, m9, m10, m11 = m[8], m[9], m[10], m[11] + m[4] = m4 * c + m8 * s; m[8] = m8 * c - m4 * s + m[5] = m5 * c + m9 * s; m[9] = m9 * c - m5 * s + m[6] = m6 * c + m10 * s; m[10] = m10 * c - m6 * s + m[7] = m7 * c + m11 * s; m[11] = m11 * c - m7 * s + return + if x == 0.0 and y == 1.0 and z == 0.0: + m0, m1, m2, m3 = m[0], m[1], m[2], m[3] + m8, m9, m10, m11 = m[8], m[9], m[10], m[11] + m[0] = m0 * c - m8 * s; m[8] = m0 * s + m8 * c + m[1] = m1 * c - m9 * s; m[9] = m1 * s + m9 * c + m[2] = m2 * c - m10 * s; m[10] = m2 * s + m10 * c + m[3] = m3 * c - m11 * s; m[11] = m3 * s + m11 * c + return + if x == 0.0 and y == 0.0 and z == 1.0: + m0, m1, m2, m3 = m[0], m[1], m[2], m[3] + m4, m5, m6, m7 = m[4], m[5], m[6], m[7] + m[0] = m0 * c + m4 * s; m[4] = m4 * c - m0 * s + m[1] = m1 * c + m5 * s; m[5] = m5 * c - m1 * s + m[2] = m2 * c + m6 * s; m[6] = m6 * c - m2 * s + m[3] = m3 * c + m7 * s; m[7] = m7 * c - m3 * s + return + + length = sqrt(x * x + y * y + z * z) + if length < 1e-12: + return + ux, uy, uz = x / length, y / length, z / length + omc = 1.0 - c + r = [ + ux * ux * omc + c, uy * ux * omc + uz * s, uz * ux * omc - uy * s, 0.0, + ux * uy * omc - uz * s, uy * uy * omc + c, uz * uy * omc + ux * s, 0.0, + ux * uz * omc + uy * s, uy * uz * omc - ux * s, uz * uz * omc + c, 0.0, + 0.0, 0.0, 0.0, 1.0, + ] + _matrix_stack[-1] = _mat4_mul(m, r) + + +def _mult_matrix(m): + _matrix_stack[-1] = _mat4_mul(_matrix_stack[-1], m) + + +def _sync_gl_modelview(): + """Uploads the current pure-Python modelview matrix to legacy GL (removed in Commit 3).""" + glMatrixMode(GL_MODELVIEW) + glLoadMatrixf((GLfloat * 16)(*_current_matrix())) + _EXPR_MATH = { "sin": sin, "cos": cos, "tan": tan, "asin": asin, "acos": acos, "atan": atan, "atan2": atan2, @@ -230,7 +418,6 @@ def volume(self): vol = self.vol else: vol = sum(part.volume() for part in self.parts) - #print "Collection.volume", vol return vol # a collection consisting of overlapping parts will have an incorrect @@ -313,11 +500,11 @@ def __init__(self, parts, *args): def apply(self): v, x, y, z = self.coords() - glPushMatrix() - glTranslatef(x * v, y * v, z * v) + _push_matrix() + _translate(x * v, y * v, z * v) def unapply(self): - glPopMatrix() + _pop_matrix() class VectorTranslate(Collection, ArgsBase): @@ -339,11 +526,11 @@ def __init__(self, parts, *args, **kwargs): def apply(self): x, y, z, sc = self.coords() - glPushMatrix() - glTranslatef(sc * x, sc * y, sc * z) + _push_matrix() + _translate(sc * x, sc * y, sc * z) def unapply(self): - glPopMatrix() + _pop_matrix() HalTranslate = Translate @@ -370,11 +557,11 @@ def __init__(self, parts, *args): def apply(self): x, y, z, factor = self.coords() - glPushMatrix() - glScalef(x * factor, y * factor, z * factor) + _push_matrix() + _scale(x * factor, y * factor, z * factor) def unapply(self): - glPopMatrix() + _pop_matrix() HalScale = Scale @@ -406,11 +593,11 @@ def apply(self): th, x, y, z = self.get_values() else: var, th, x, y, z = self.coords() - glPushMatrix() - glRotatef(th * var, x, y, z) + _push_matrix() + _rotate(th * var, x, y, z) def unapply(self): - glPopMatrix() + _pop_matrix() HalRotate = Rotate HalVectorRotate = Rotate @@ -432,7 +619,7 @@ def __init__(self, parts, *args, order=123): def apply(self): order, th1, th2, th3 = self.coords() order = int(order) - glPushMatrix() + _push_matrix() axes = { 131: ((1, 0, 0), (0, 0, 1), (1, 0, 0)), 121: ((1, 0, 0), (0, 1, 0), (1, 0, 0)), @@ -449,12 +636,12 @@ def apply(self): } if order in axes: a1, a2, a3 = axes[order] - glRotatef(th1, *a1) - glRotatef(th2, *a2) - glRotatef(th3, *a3) + _rotate(th1, *a1) + _rotate(th2, *a2) + _rotate(th3, *a3) def unapply(self): - glPopMatrix() + _pop_matrix() HalRotateEuler = RotateEuler @@ -482,15 +669,14 @@ def __init__(self, parts, *args): def apply(self): const, var, scaleby_true, scaleby_false = self.coords() - glPushMatrix() + _push_matrix() if const == var: - glScalef(scaleby_true, scaleby_true, scaleby_true) + _scale(scaleby_true, scaleby_true, scaleby_true) else: - glScalef(scaleby_false, scaleby_false, scaleby_false) + _scale(scaleby_false, scaleby_false, scaleby_false) def unapply(self): - glPopMatrix() - + _pop_matrix() HalShow = Show @@ -593,17 +779,17 @@ def apply(self): dx, dy, dz = x2 - x1, y2 - y1, z2 - z1 length = sqrt(dx * dx + dy * dy + dz * dz) if length < 1e-9: - glPushMatrix() - glTranslatef(x1, y1, z1) + _push_matrix() + _translate(x1, y1, z1) return axis = (1, 0, 0) if hypot(dx, dy) < 0.001 else self.cross((dx, dy, dz), (0, 0, 1)) angle = -atan2(hypot(dx, dy), dz) * 180.0 / pi - glPushMatrix() - glTranslatef(x1, y1, z1) - glRotatef(angle, *axis) + _push_matrix() + _translate(x1, y1, z1) + _rotate(angle, *axis) def unapply(self): - glPopMatrix() + _pop_matrix() def _is_parts_list(obj): @@ -647,7 +833,7 @@ def __init__(self, *args, **kwargs): color, parts, comp, glow = args[0], args[1], None, 0.0 if len(color) not in (3, 4): raise ValueError("Color specification must have 3 (RGB) or 4 (RGBA) channels") - # Since GL_BLEND was off the legacy swapped order has always rendered opaque for any A + # Legacy swapped order has always rendered opaque for any A rgba = [color[0], color[1], color[2], 1.0] else: raise TypeError("Color expects (parts, [prefix,] color[, glow]) or (color, parts)") @@ -701,13 +887,14 @@ def __init__(self, *args, **kwargs): def draw(self): x1, y1, z1, x2, y2, z2, stretch, r = self.coords() length, angle, axis = self.polar([x2, y2, z2], stretch) - glPushMatrix() - glTranslate(x1, y1, z1) - glRotate(angle, *axis) + _push_matrix() + _translate(x1, y1, z1) + _rotate(angle, *axis) + _sync_gl_modelview() gluCylinder(self.q, r, r, length, 32, 1) def unapply(self): - glPopMatrix() + _pop_matrix() HalLine = Line @@ -717,21 +904,21 @@ def _apply_normal_or_basis(origin, vec_z, vec_x=None): ox, oy, oz = origin if vec_x is None: _, angle, axis = _polar3(vec_z) - glPushMatrix() - glTranslate(ox, oy, oz) - glRotate(angle, *axis) + _push_matrix() + _translate(ox, oy, oz) + _rotate(angle, *axis) else: xx, xy, xz = vec_x zx, zy, zz = vec_z yx, yy, yz = _cross3(vec_z, vec_x) - m_t = [ - [xx, xy, xz, 0], - [yx, yy, yz, 0], - [zx, zy, zz, 0], - [ox, oy, oz, 1], + m_col = [ + xx, xy, xz, 0.0, + yx, yy, yz, 0.0, + zx, zy, zz, 0.0, + ox, oy, oz, 1.0, ] - glPushMatrix() - glMultMatrixf(m_t) + _push_matrix() + _mult_matrix(m_col) def _draw_grid_lines(s): s_int = int(s) @@ -784,11 +971,12 @@ def draw(self): ox, oy, oz, xx, xy, xz, zx, zy, zz, s = self.coords() _apply_normal_or_basis((ox, oy, oz), (zx, zy, zz), (xx, xy, xz)) + _sync_gl_modelview() _draw_grid_lines(s) def unapply(self): if self._mode != "origin": - glPopMatrix() + _pop_matrix() HalGrid = Grid @@ -838,6 +1026,7 @@ def draw(self): n = (zx, zy, zz) _apply_normal_or_basis((ox, oy, oz), n, (xx, xy, xz)) + _sync_gl_modelview() glPushAttrib(GL_ENABLE_BIT) glDisable(GL_CULL_FACE) glBegin(GL_QUADS) @@ -851,7 +1040,7 @@ def draw(self): def unapply(self): if self._mode != "origin": - glPopMatrix() + _pop_matrix() HalPlaneFromNormal = Plane @@ -890,13 +1079,14 @@ def __init__(self, *args, **kwargs): raise TypeError("Coords expects 0-2, 6-8, or 9-11 arguments after optional comp") def draw_vector(self, r, stretch, color): + _sync_gl_modelview() glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color) gluCylinder(self.q, r, r, 50 * stretch, 32, 1) def draw(self): if self._mode == "origin": stretch, r = self.coords() - glPushMatrix() + _push_matrix() elif self._mode == "normal": ox, oy, oz, zx, zy, zz, stretch, r = self.coords() _apply_normal_or_basis((ox, oy, oz), (zx, zy, zz)) @@ -906,14 +1096,14 @@ def draw(self): glPushAttrib(GL_LIGHTING_BIT) self.draw_vector(r, stretch, [0, 0, 1, 1]) - glRotate(90, 0, 1, 0) + _rotate(90, 0, 1, 0) self.draw_vector(r, stretch, [1, 0, 0, 1]) - glRotate(-90, 1, 0, 0) + _rotate(-90, 1, 0, 0) self.draw_vector(r, stretch, [0, 1, 0, 1]) glPopAttrib() def unapply(self): - glPopMatrix() + _pop_matrix() HalCoordsFromNormalAndDirection = Coords @@ -929,23 +1119,26 @@ def draw(self): p1, p2 = p2, p1 r1, r2 = r2, r1 - glPushMatrix() + _push_matrix() if self._axis_rotation is not None: - glRotatef(*self._axis_rotation) - glTranslatef(0, 0, p1) + _rotate(*self._axis_rotation) + _translate(0, 0, p1) + _sync_gl_modelview() gluCylinder(self.q, r1, r2, p2 - p1, 32, 1) # Bottom cap - glRotatef(180, 1, 0, 0) + _rotate(180, 1, 0, 0) + _sync_gl_modelview() gluDisk(self.q, 0, r1, 32, 1) - glRotatef(180, 1, 0, 0) + _rotate(180, 1, 0, 0) # Top cap - glPushMatrix() - glTranslatef(0, 0, p2 - p1) + _push_matrix() + _translate(0, 0, p2 - p1) + _sync_gl_modelview() gluDisk(self.q, 0, r2, 32, 1) - glPopMatrix() - glPopMatrix() + _pop_matrix() + _pop_matrix() def volume(self): p1, r1, p2, r2 = self.coords() @@ -968,17 +1161,15 @@ class CylinderZ(_CylinderAxis): class Sphere(ArgsBase): def draw(self): x, y, z, r = self.coords() - # need to translate the whole thing to x,y,z - glPushMatrix() - glTranslatef(x,y,z) - # the sphere starts out at the origin + _push_matrix() + _translate(x, y, z) + _sync_gl_modelview() gluSphere(self.q, r, 32, 16) - glPopMatrix() + _pop_matrix() def volume(self): x, y, z, r = self.coords() vol = 1.3333333*3.1415927*r*r*r - #print "Sphere.volume", vol return vol @@ -986,6 +1177,7 @@ def volume(self): # specify the corners Z values for each side class TriangleXY(ArgsBase): def draw(self): + _sync_gl_modelview() x1, y1, x2, y2, x3, y3, z1, z2 = self.coords() x12 = x1-x2 y12 = y1-y2 @@ -1056,7 +1248,6 @@ def volume(self): area = 0.5*abs(x2*y3 - x3*y2) thk = abs(z1-z2) vol = area*thk - #print "TriangleXY.volume = area * thickness)",vol, area, thk return vol # triangular plate in XZ plane @@ -1066,16 +1257,15 @@ def coords(self): return x1, z1, x2, z2, x3, z3, -y1, -y2 def draw(self): - glPushMatrix() - glRotatef(90,1,0,0) + _push_matrix() + _rotate(90,1,0,0) # create the triangle in XY plane TriangleXY.draw(self) # bottom cap - glPopMatrix() + _pop_matrix() def volume(self): vol = TriangleXY.volume(self) - #print " TriangleXZ.volume",vol return vol # triangular plate in YZ plane @@ -1085,21 +1275,21 @@ def coords(self): return z1, y1, z2, y2, z3, y3, -x1, -x2 def draw(self): - glPushMatrix() - glRotatef(90,0,-1,0) + _push_matrix() + _rotate(90,0,-1,0) # create the triangle in XY plane TriangleXY.draw(self) # bottom cap - glPopMatrix() + _pop_matrix() def volume(self): vol = TriangleXY.volume(self) - #print " TriangleYZ.volume",vol return vol class ArcX(ArgsBase): def draw(self): + _sync_gl_modelview() x1, x2, r1, r2, a1, a2, steps = self.coords() if x1 > x2: tmp = x1 @@ -1200,7 +1390,6 @@ def volume(self): angle = a2 - a1 area = (angle/360.0)*pi*(r2*r2-r1*r1) vol = area * height - #print "Arc.volume = angle * area * height",vol, angle, area, height return vol @@ -1209,6 +1398,7 @@ def volume(self): # six coordinate version - specify each side of the box class Box(ArgsBase): def draw(self): + _sync_gl_modelview() x1, y1, z1, x2, y2, z2 = self.coords() if x1 > x2: tmp = x1 @@ -1265,7 +1455,6 @@ def draw(self): def volume(self): x1, y1, z1, x2, y2, z2 = self.coords() vol = abs((x1-x2)*(y1-y2)*(z1-z2)) - #print "Box.volume", vol return vol @@ -1363,6 +1552,7 @@ def reload(self, filename=None, data=None, force=False): return True def draw(self): + _sync_gl_modelview() if self._stale_list is not None: glDeleteLists(self._stale_list, 1) self._stale_list = None @@ -1512,15 +1702,10 @@ def _emit_gl(self): # to the viewport system, NOT to the world system class Capture(object): def __init__(self): - self.t = [ - [1.0, 0.0, 0.0, 0.0], - [0.0, 1.0, 0.0, 0.0], - [0.0, 0.0, 1.0, 0.0], - [0.0, 0.0, 0.0, 1.0], - ] + self.t = _mat4_to_rows(_IDENTITY_4X4) def capture(self): - self.t = glGetDoublev(GL_MODELVIEW_MATRIX) + self.t = _mat4_to_rows(_current_matrix()) def world_pos(self, world=None): if world is not None: @@ -1531,7 +1716,6 @@ def world_pos(self, world=None): def volume(self): return 0.0 - def _compile_hud_val(val, prefix_cache): """Compiles a HUD value/condition into a zero-arg callable with legacy hal.get_value fallback.""" if not isinstance(val, str): @@ -1723,7 +1907,7 @@ def draw(self): if not self.fontbase: self.fontbase = int(self.app.loadbitmapfont("9x15")) char_width, char_height = 9, 15 - xmargin,ymargin = 5,5 + xmargin, ymargin = 5, 5 ypos = float(self.app.winfo_height()) glOrtho(0.0, self.app.winfo_width(), 0.0, ypos, -1.0, 1.0) @@ -1781,9 +1965,6 @@ class O(rs274.OpenGLTk.Opengl): def __init__(self, *args, **kw): rs274.OpenGLTk.Opengl.__init__(self, *args, **kw) self.r_back = self.g_back = self.b_back = 0 - #self.q1 = gluNewQuadric() - #self.q2 = gluNewQuadric() - #self.q3 = gluNewQuadric() self.plotdata = [] self.plotlen = 16000 #does not show HUD by default @@ -1812,6 +1993,8 @@ def redraw(self, *args): global _stats_fresh, _render_pass, _has_transparent if self.winfo_width() == 1: return poll_all_stats() + cam_mv = glGetFloatv(GL_MODELVIEW_MATRIX) + _load_matrix([float(v) for row in cam_mv for v in row]) # Pass 1: Opaque geometry (also updates all Capture() transforms) _render_pass = "opaque" @@ -1861,40 +2044,18 @@ def redraw(self, *args): # wx, wy, wz are the values to use for backplot # so we save them in a buffer if len(self.plotdata) == self.plotlen: - del self.plotdata[:self.plotlen / 10] + del self.plotdata[:self.plotlen // 10] point = [ wx, wy, wz ] if not self.plotdata or point != self.plotdata[-1]: self.plotdata.append(point) - # now lets draw something in the tool coordinate system - #glPushMatrix() - # matrixes take effect in reverse order, so the next - # two lines do "tool -> view -> world" - #glMultMatrixd(view2world) - #glMultMatrixd(self.tool2view.t) - - # do drawing here - # cylinder normally goes to +Z, we want it down - #glTranslatef(0,0,-60) - #gluCylinder(self.q1, 20, 20, 60, 32, 16) - - # back to world coords - #glPopMatrix() - - # we can also draw in the work coord system - glPushMatrix() + _push_matrix() # "work -> view -> world" - glMultMatrixd(view2world) - glMultMatrixd(self.work2view.t) - # now we can draw in work coords, and whatever we draw - # will move with the work, (if the work is attached to - # a table or indexer or something that moves with - # respect to the world - - # just a test object, sitting on the table - #gluCylinder(self.q2, 40, 20, 60, 32, 16) - + _mult_matrix(_rows_to_mat4(view2world)) + _mult_matrix(_rows_to_mat4(self.work2view.t)) + _sync_gl_modelview() + #draw head up display if(hasattr(self.hud, "draw")): self.hud.draw() @@ -1916,7 +2077,7 @@ def redraw(self, *args): glDepthFunc(GL_LESS) # back to world again - glPopMatrix() + _pop_matrix() def plotclear(self): del self.plotdata[:self.plotlen] From 8e85f364759f3a1de563d1335baa13df23cb93a1 Mon Sep 17 00:00:00 2001 From: David Date: Fri, 4 Dec 2026 16:34:07 +0100 Subject: [PATCH 6/7] vismach: migrate primitives, meshes, and HUD to OpenGL 3.3 shaders and VBOs Replace legacy fixed-function lighting, display lists, GLU quadrics, and bitmap font calls with GLSL 3.30 Core shaders and VAO/VBO buffers: - Add _ShaderProgram, _VBOMesh, and _GL33Renderer with a two-light + emissive glow 3D shader, a flat line shader, and a 2D HUD shader. - Replace gluCylinder, gluDisk, gluSphere, glBegin/glEnd, and glGenLists display lists with cached VBO/VAO meshes across all primitives, STL/OBJ loaders, Grid, and backplot traces. - Replace Hud's fixed-function X11 bitmap font rendering with an Xft / 8x13 bitmap font texture atlas and 2D orthographic shader. - Properly scope Color state via apply()/unapply() so inner child colors no longer leak onto parent or sibling parts. - Guard shutdown in main() against SystemExit and TclError mid-frame. --- lib/python/vismach.py | 2262 +++++++++++++++++++++++++---------------- 1 file changed, 1376 insertions(+), 886 deletions(-) diff --git a/lib/python/vismach.py b/lib/python/vismach.py index 6d74667e5cc..0c2794ea26a 100644 --- a/lib/python/vismach.py +++ b/lib/python/vismach.py @@ -14,11 +14,12 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +import ctypes +import ctypes.util import sys, rs274.OpenGLTk, signal, hal import tkinter from OpenGL.GL import * -from OpenGL.GLU import * from math import * import glnav import os @@ -214,11 +215,366 @@ def _rotate(angle_deg, x, y, z): def _mult_matrix(m): _matrix_stack[-1] = _mat4_mul(_matrix_stack[-1], m) +# --------------------------------------------------------------------------- +# OpenGL 3.3 Core Profile Shaders & VBO/VAO Mesh Cache +# --------------------------------------------------------------------------- +_LIT_VERT_SRC = """#version 330 core +layout(location = 0) in vec3 a_pos; +layout(location = 1) in vec3 a_normal; + +uniform mat4 u_mvp; +uniform mat4 u_mv; +uniform mat3 u_normal_mat; + +out vec3 v_normal_eye; + +void main() { + v_normal_eye = normalize(u_normal_mat * a_normal); + gl_Position = u_mvp * vec4(a_pos, 1.0); +} +""" + +_LIT_FRAG_SRC = """#version 330 core +in vec3 v_normal_eye; + +uniform vec4 u_color; +uniform vec3 u_emission; + +out vec4 frag_color; + +void main() { + vec3 n = normalize(v_normal_eye); + if (!gl_FrontFacing) { + n = -n; + } + + // Two directional lights tuned halfway between legacy and bright shader + vec3 l0_dir = normalize(vec3(1.0, 0.0, 0.8)); + vec3 l1_dir = normalize(vec3(-1.0, -1.0, 0.3)); + + float diff0 = max(dot(n, l0_dir), 0.0); + float diff1 = max(dot(n, l1_dir), 0.0); + + vec3 ambient = vec3(0.24) * u_color.rgb; + vec3 diffuse = (diff0 * vec3(0.68, 0.68, 0.58) + diff1 * vec3(0.22, 0.22, 0.42)) * u_color.rgb; + vec3 rgb = min(ambient + diffuse + u_emission, vec3(1.0)); + + frag_color = vec4(rgb, u_color.a); +} +""" + +_FLAT_VERT_SRC = """#version 330 core +layout(location = 0) in vec3 a_pos; + +uniform mat4 u_mvp; + +void main() { + gl_Position = u_mvp * vec4(a_pos, 1.0); +} +""" + +_FLAT_FRAG_SRC = """#version 330 core +uniform vec4 u_color; +out vec4 frag_color; + +void main() { + frag_color = u_color; +} +""" + +_HUD_VERT_SRC = """#version 330 core +layout(location = 0) in vec2 a_pos; +layout(location = 1) in vec2 a_uv; + +uniform mat4 u_proj; +out vec2 v_uv; + +void main() { + v_uv = a_uv; + gl_Position = u_proj * vec4(a_pos, 0.0, 1.0); +} +""" + +_HUD_FRAG_SRC = """#version 330 core +in vec2 v_uv; + +uniform vec4 u_color; +uniform sampler2D u_tex; +uniform int u_use_tex; + +out vec4 frag_color; + +void main() { + if (u_use_tex != 0) { + float alpha = texture(u_tex, v_uv).r; + if (alpha < 0.1) { + discard; + } + frag_color = vec4(u_color.rgb, u_color.a * alpha); + } else { + frag_color = u_color; + } +} +""" + +_active_prog = 0 + +class _ShaderProgram: + """Compiles and caches an OpenGL 3.3 Core GLSL shader program and uniform locations.""" + def __init__(self, vert_src, frag_src): + vs = self._compile(GL_VERTEX_SHADER, vert_src) + fs = self._compile(GL_FRAGMENT_SHADER, frag_src) + prog = glCreateProgram() + glAttachShader(prog, vs) + glAttachShader(prog, fs) + glLinkProgram(prog) + glDeleteShader(vs) + glDeleteShader(fs) + if not glGetProgramiv(prog, GL_LINK_STATUS): + log = glGetProgramInfoLog(prog).decode("utf-8", errors="replace") + glDeleteProgram(prog) + raise RuntimeError("Vismach Shader Link Error:\n%s" % log) + self.prog = prog + self._uniforms = {} + self._m16 = (GLfloat * 16)() + self._m9 = (GLfloat * 9)() + + @staticmethod + def _compile(shader_type, src): + sh = glCreateShader(shader_type) + glShaderSource(sh, src) + glCompileShader(sh) + if not glGetShaderiv(sh, GL_COMPILE_STATUS): + log = glGetShaderInfoLog(sh).decode("utf-8", errors="replace") + glDeleteShader(sh) + raise RuntimeError("Vismach Shader Compile Error:\n%s" % log) + return sh + + def use(self): + global _active_prog + if _active_prog != self.prog: + _active_prog = self.prog + glUseProgram(self.prog) + + def loc(self, name): + u = self._uniforms.get(name) + if u is None: + u = glGetUniformLocation(self.prog, name) + self._uniforms[name] = u + return u + + def set_mat4(self, name, m16): + buf = self._m16 + buf[:] = m16 + glUniformMatrix4fv(self.loc(name), 1, GL_FALSE, buf) + + def set_mat3(self, name, m9): + buf = self._m9 + buf[:] = m9 + glUniformMatrix3fv(self.loc(name), 1, GL_FALSE, buf) + + def set_vec4(self, name, x, y, z, w): + glUniform4f(self.loc(name), float(x), float(y), float(z), float(w)) + + def set_vec3(self, name, x, y, z): + glUniform3f(self.loc(name), float(x), float(y), float(z)) + + def set_int(self, name, val): + glUniform1i(self.loc(name), int(val)) + + +class _VBOMesh: + """Holds an OpenGL 3.3 Core VAO + VBO for interleaved (pos, normal) or pos-only geometry.""" + def __init__(self, floats, stride_floats=6, mode=GL_TRIANGLES): + self.mode = mode + self.stride_floats = stride_floats + self.vertex_count = len(floats) // stride_floats + self.vao = None + self.vbo = None + if self.vertex_count == 0: + return + + self.vao = glGenVertexArrays(1) + self.vbo = glGenBuffers(1) + glBindVertexArray(self.vao) + glBindBuffer(GL_ARRAY_BUFFER, self.vbo) + raw = struct.pack("<%df" % len(floats), *floats) + glBufferData(GL_ARRAY_BUFFER, len(raw), raw, GL_STATIC_DRAW) + + stride_bytes = stride_floats * 4 + glEnableVertexAttribArray(0) + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride_bytes, ctypes.c_void_p(0)) + if stride_floats >= 6: + glEnableVertexAttribArray(1) + glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, stride_bytes, ctypes.c_void_p(12)) + + glBindBuffer(GL_ARRAY_BUFFER, 0) + glBindVertexArray(0) + + def draw(self): + if self.vao is None or self.vertex_count == 0: + return + glBindVertexArray(self.vao) + glDrawArrays(self.mode, 0, self.vertex_count) + glBindVertexArray(0) + + def delete(self): + if self.vbo is not None: + glDeleteBuffers(1, [self.vbo]) + self.vbo = None + if self.vao is not None: + glDeleteVertexArrays(1, [self.vao]) + self.vao = None + + +class _GL33Renderer: + """Central Core Profile shader & cached unit-primitive state.""" + def __init__(self): + self.lit = None + self.flat = None + self.hud = None + self.color = [1.0, 1.0, 1.0, 1.0] + self.emission = [0.0, 0.0, 0.0] + self.unit_meshes = {} + + def init(self): + if self.lit is not None: + return + self.lit = _ShaderProgram(_LIT_VERT_SRC, _LIT_FRAG_SRC) + self.flat = _ShaderProgram(_FLAT_VERT_SRC, _FLAT_FRAG_SRC) + self.hud = _ShaderProgram(_HUD_VERT_SRC, _HUD_FRAG_SRC) + + def draw_lit(self, mesh): + if self.lit is None or mesh is None: + return + mv = _current_matrix() + mvp = _mat4_mul(_proj_matrix, mv) + nmat = _mat4_normal_3x3(mv) + self.lit.use() + self.lit.set_mat4("u_mvp", mvp) + self.lit.set_mat4("u_mv", mv) + self.lit.set_mat3("u_normal_mat", nmat) + self.lit.set_vec4("u_color", *self.color) + self.lit.set_vec3("u_emission", *self.emission) + mesh.draw() + + def draw_flat(self, mesh): + if self.flat is None or mesh is None: + return + mvp = _mat4_mul(_proj_matrix, _current_matrix()) + self.flat.use() + self.flat.set_mat4("u_mvp", mvp) + self.flat.set_vec4("u_color", *self.color) + mesh.draw() + + def get_unit_cylinder(self, slices=32): + key = ("cyl", slices) + m = self.unit_meshes.get(key) + if m is None: + floats = [] + for i in range(slices): + a0 = (2.0 * pi * i) / slices + a1 = (2.0 * pi * (i + 1)) / slices + c0, s0 = cos(a0), sin(a0) + c1, s1 = cos(a1), sin(a1) + # Side quad (2 triangles), Z in, radius 1 + floats.extend([ + c0, s0, 0.0, c0, s0, 0.0, + c1, s1, 0.0, c1, s1, 0.0, + c1, s1, 1.0, c1, s1, 0.0, + c0, s0, 0.0, c0, s0, 0.0, + c1, s1, 1.0, c1, s1, 0.0, + c0, s0, 1.0, c0, s0, 0.0, + ]) + m = _VBOMesh(floats, stride_floats=6, mode=GL_TRIANGLES) + self.unit_meshes[key] = m + return m + + def get_unit_disk(self, slices=32): + key = ("disk", slices) + m = self.unit_meshes.get(key) + if m is None: + floats = [] + for i in range(slices): + a0 = (2.0 * pi * i) / slices + a1 = (2.0 * pi * (i + 1)) / slices + floats.extend([ + 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, + cos(a0), sin(a0), 0.0, 0.0, 0.0, 1.0, + cos(a1), sin(a1), 0.0, 0.0, 0.0, 1.0, + ]) + m = _VBOMesh(floats, stride_floats=6, mode=GL_TRIANGLES) + self.unit_meshes[key] = m + return m + + def get_unit_sphere(self, slices=32, stacks=16): + key = ("sphere", slices, stacks) + m = self.unit_meshes.get(key) + if m is None: + floats = [] + for st in range(stacks): + phi0 = pi * st / stacks - pi * 0.5 + phi1 = pi * (st + 1) / stacks - pi * 0.5 + cp0, sp0 = cos(phi0), sin(phi0) + cp1, sp1 = cos(phi1), sin(phi1) + for sl in range(slices): + th0 = 2.0 * pi * sl / slices + th1 = 2.0 * pi * (sl + 1) / slices + ct0, st0 = cos(th0), sin(th0) + ct1, st1 = cos(th1), sin(th1) + + p00 = (cp0 * ct0, cp0 * st0, sp0) + p10 = (cp0 * ct1, cp0 * st1, sp0) + p11 = (cp1 * ct1, cp1 * st1, sp1) + p01 = (cp1 * ct0, cp1 * st0, sp1) + + for p in (p00, p10, p11, p00, p11, p01): + floats.extend([p[0], p[1], p[2], p[0], p[1], p[2]]) + m = _VBOMesh(floats, stride_floats=6, mode=GL_TRIANGLES) + self.unit_meshes[key] = m + return m + + def get_unit_box(self): + key = ("box",) + m = self.unit_meshes.get(key) + if m is None: + # Unit cube [0, 1]^3 with outward face normals + faces = [ + ((0, 0, -1), ((0, 0, 0), (0, 1, 0), (1, 1, 0), (1, 0, 0))), + ((0, 0, 1), ((0, 0, 1), (1, 0, 1), (1, 1, 1), (0, 1, 1))), + ((0, -1, 0), ((0, 0, 0), (1, 0, 0), (1, 0, 1), (0, 0, 1))), + ((0, 1, 0), ((0, 1, 0), (0, 1, 1), (1, 1, 1), (1, 1, 0))), + ((-1, 0, 0), ((0, 0, 0), (0, 0, 1), (0, 1, 1), (0, 1, 0))), + (( 1, 0, 0), ((1, 0, 0), (1, 1, 0), (1, 1, 1), (1, 0, 1))), + ] + floats = [] + for n, (v0, v1, v2, v3) in faces: + for v in (v0, v1, v2, v0, v2, v3): + floats.extend([v[0], v[1], v[2], n[0], n[1], n[2]]) + m = _VBOMesh(floats, stride_floats=6, mode=GL_TRIANGLES) + self.unit_meshes[key] = m + return m + + def get_unit_quad(self): + key = ("quad",) + m = self.unit_meshes.get(key) + if m is None: + # Unit XY quad [-0.5, 0.5]^2 at Z=0 with +Z normal + floats = [ + -0.5, -0.5, 0.0, 0.0, 0.0, 1.0, + 0.5, -0.5, 0.0, 0.0, 0.0, 1.0, + 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, + -0.5, -0.5, 0.0, 0.0, 0.0, 1.0, + 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, + -0.5, 0.5, 0.0, 0.0, 0.0, 1.0, + ] + m = _VBOMesh(floats, stride_floats=6, mode=GL_TRIANGLES) + self.unit_meshes[key] = m + return m + + +_gl33 = _GL33Renderer() -def _sync_gl_modelview(): - """Uploads the current pure-Python modelview matrix to legacy GL (removed in Commit 3).""" - glMatrixMode(GL_MODELVIEW) - glLoadMatrixf((GLfloat * 16)(*_current_matrix())) _EXPR_MATH = { "sin": sin, "cos": cos, "tan": tan, @@ -291,8 +647,8 @@ def _capture_caller_prefixes(): return prefixes def _split_comp(args): - """Detects an optional leading prefix (hal.component, linuxcnc.stat, hal, dict) in *args.""" - if args and _is_valid_prefix_obj(args[0]): + """Detects an optional leading prefix (None, hal.component, linuxcnc.stat, hal, dict) in *args.""" + if args and (args[0] is None or _is_valid_prefix_obj(args[0])): if isinstance(args[0], linuxcnc.stat): _register_stat(args[0]) return args[0], args[1:] @@ -456,15 +812,6 @@ def __init__(self, *args): prefix_cache = _capture_caller_prefixes() self._resolvers = [_compile_arg(v, comp, prefix_cache) for v in rest] - # redundant once we move to OpenGl 3.3 - @property - def q(self): - quad = self.__dict__.get("_q") - if quad is None: - quad = gluNewQuadric() - self.__dict__["_q"] = quad - return quad - def coords(self): if self._static_vals is not None: return self._static_vals @@ -804,99 +1151,92 @@ def _is_parts_list(obj): return False class Color(Collection, ArgsBase): - """ - Sets RGBA material color and optional emissive glow (0.0..1.0). - Supports: - - Color(parts, color[, glow]) - - Color(parts, prefix, color[, glow]) - - Color(color, parts) # legacy swapped order (opaque only, no glow) - """ + """Sets RGBA color and optional emissive glow on parts.""" def __init__(self, *args, **kwargs): - if not args: - raise TypeError("Color expects (parts, [prefix,] color[, glow]) or (color, parts)") - glow = kwargs.get("glow", 0.0) - if _is_parts_list(args[0]): - parts = args[0] - comp, rest = _split_comp(args[1:]) - if len(rest) == 1: - color = rest[0] - elif len(rest) == 2: - color, glow = rest - else: - raise TypeError("Color expects (parts, [prefix,] color[, glow])") - rgba = list(color) + ([1.0] if len(color) == 3 else []) - if len(rgba) != 4: - raise ValueError("Color specification must have 3 (RGB) or 4 (RGBA) channels") - elif len(args) == 2 and _is_parts_list(args[1]): - if "glow" in kwargs: - raise TypeError("Legacy Color(color, parts) does not support glow") - color, parts, comp, glow = args[0], args[1], None, 0.0 - if len(color) not in (3, 4): - raise ValueError("Color specification must have 3 (RGB) or 4 (RGBA) channels") - # Legacy swapped order has always rendered opaque for any A - rgba = [color[0], color[1], color[2], 1.0] - else: - raise TypeError("Color expects (parts, [prefix,] color[, glow]) or (color, parts)") + if len(args) == 2 and not _is_parts_list(args[0]) and _is_parts_list(args[1]): + self._legacy_mode = True + self._legacy_color = args[0] + Collection.__init__(self, args[1]) + return - self.parts = parts - self.vol = 0 - ArgsBase.__init__(self, comp, *(rgba + [glow])) + self._legacy_mode = False + parts = args[0] + Collection.__init__(self, parts) + prefix, rest = _split_comp(args[1:]) + if not rest: + raise TypeError("Color expects (parts, [prefix,] color[, glow])") + color = rest[0] + glow = rest[1] if len(rest) > 1 else kwargs.get("glow", 0.0) + + c_vals = list(color) + if len(c_vals) == 3: + c_vals.append(1.0) + elif len(c_vals) != 4: + raise TypeError("Color expects [R, G, B] or [R, G, B, A]") + + ArgsBase.__init__(self, prefix, c_vals[0], c_vals[1], c_vals[2], c_vals[3], glow) def traverse(self): global _has_transparent - r, g, b, a, glow = self.coords() - is_transparent = a < 1.0 - if _render_pass == "opaque": - if is_transparent: + if not self._legacy_mode: + _, _, _, a, _ = self.coords() + a = max(0.0, min(1.0, float(a))) + if a < 1.0: _has_transparent = True + if _render_pass == "opaque": + return + elif _render_pass == "transparent": return - elif not is_transparent: - return - if a <= 0.0: + + self.apply() + try: + super().traverse() + finally: + self.unapply() + + def apply(self): + global _has_transparent + self._prev_color = list(_gl33.color) + self._prev_emission = list(_gl33.emission) + + if self._legacy_mode: + c = self._legacy_color + r, g, b = float(c[0]), float(c[1]), float(c[2]) + _gl33.color = [r, g, b, 1.0] + _gl33.emission = [0.0, 0.0, 0.0] return - glPushAttrib(GL_LIGHTING_BIT | GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, [r, g, b, a]) - if glow: - g_val = float(glow) - glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, [r * g_val, g * g_val, b * g_val, 1.0]) + r, g, b, a, glow = self.coords() + r, g, b = float(r), float(g), float(b) + a = max(0.0, min(1.0, float(a))) + glow = max(0.0, min(1.0, float(glow))) + + if a < 1.0: + _has_transparent = True + if _render_pass == "opaque": + return else: - glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, [0.0, 0.0, 0.0, 1.0]) - Collection.traverse(self) - glPopAttrib() + if _render_pass == "transparent": + return - def apply(self): - rgba = self.coords() - glPushAttrib(GL_LIGHTING_BIT) - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, rgba) + _gl33.color = [r, g, b, a] + _gl33.emission = [r * glow, g * glow, b * glow] def unapply(self): - glPopAttrib() + _gl33.color = self._prev_color + _gl33.emission = self._prev_emission -class Line(ArgsBase): - def __init__(self, *args, **kwargs): - comp, rest = _split_comp(args) - if len(rest) < 6 or len(rest) > 8: - raise TypeError("Line expects ([comp,] x1, y1, z1, x2, y2, z2, stretch=1, r=5)") - x1, y1, z1, x2, y2, z2 = rest[:6] - stretch = rest[6] if len(rest) >= 7 else kwargs.get("stretch", 1) - r = rest[7] if len(rest) == 8 else kwargs.get("r", 5) - ArgsBase.__init__(self, comp, x1, y1, z1, x2, y2, z2, stretch, r) - - def draw(self): - x1, y1, z1, x2, y2, z2, stretch, r = self.coords() - length, angle, axis = self.polar([x2, y2, z2], stretch) - _push_matrix() - _translate(x1, y1, z1) - _rotate(angle, *axis) - _sync_gl_modelview() - gluCylinder(self.q, r, r, length, 32, 1) +HalColor = Color - def unapply(self): - _pop_matrix() -HalLine = Line +def _split_prefix_and_args(args, expected_counts): + prefix, vals = _split_comp(args) + if len(vals) <= 1 and len(vals) not in expected_counts: + return prefix, vals + if len(vals) not in expected_counts: + raise TypeError("Expected %s arguments (plus optional prefix), got %d" % (expected_counts, len(vals))) + return prefix, vals def _apply_normal_or_basis(origin, vec_z, vec_x=None): @@ -920,168 +1260,138 @@ def _apply_normal_or_basis(origin, vec_z, vec_x=None): _push_matrix() _mult_matrix(m_col) -def _draw_grid_lines(s): - s_int = int(s) - glBegin(GL_LINES) - for i in range(-s_int, s_int + 10, 10): - glVertex3f(-s_int, i, 0) - glVertex3f(s_int, i, 0) - glVertex3f(i, -s_int, 0) - glVertex3f(i, s_int, 0) - glEnd() - -class Grid(ArgsBase): - """ - Unifies legacy classes: - - HalGrid([comp,] s=500) - - HalGridFromNormal([comp,] x, y, z, vx, vy, vz, s=500) - - HalGridFromNormalAndDirection([comp,] ox, oy, oz, xx, xy, xz, zx, zy, zz, s=500) - """ - def __init__(self, *args, **kwargs): - comp, rest = _split_comp(args) - n = len(rest) - - if n in (0, 1): - self._mode = "origin" - s = rest[0] if n == 1 else kwargs.get("s", 500) - ArgsBase.__init__(self, comp, s) - elif n in (6, 7): - self._mode = "normal" - x, y, z, vx, vy, vz = rest[:6] - s = rest[6] if n == 7 else kwargs.get("s", 500) - ArgsBase.__init__(self, comp, x, y, z, vx, vy, vz, s) - elif n in (9, 10): - self._mode = "normal_dir" - ox, oy, oz, xx, xy, xz, zx, zy, zz = rest[:9] - s = rest[9] if n == 10 else kwargs.get("s", 500) - ArgsBase.__init__(self, comp, ox, oy, oz, xx, xy, xz, zx, zy, zz, s) - else: - raise TypeError( - "Grid expects 0-1, 6-7 (origin + normal), or " - "9-10 (origin + X-dir + normal) arguments after optional comp" - ) + +class Line(CoordsBase): + """Cylinder connecting (x1, y1, z1) to (x2, y2, z2) with stretch and radius r.""" + def __init__(self, *args): + prefix, vals = _split_prefix_and_args(args, (6, 7, 8)) + if len(vals) == 6: + vals = tuple(vals) + (1.0, 1.0) + elif len(vals) == 7: + vals = tuple(vals) + (1.0,) + self._origin = vals[:3] + super().__init__(prefix, *vals) + + def polar(self, p2, stretch): + x1, y1, z1 = self._origin + dx = p2[0] - x1 + dy = p2[1] - y1 + dz = p2[2] - z1 + length = sqrt(dx * dx + dy * dy + dz * dz) * stretch + if length == 0: + return 0, 0, (1, 0, 0) + axis = (1, 0, 0) if hypot(dx, dy) < 0.001 else self.cross((dx, dy, dz), (0, 0, 1)) + angle = -atan2(hypot(dx, dy), dz) * 180.0 / pi + return length, angle, axis def draw(self): - if self._mode == "origin": + x1, y1, z1, x2, y2, z2, stretch, r = self.coords() + length, angle, axis = self.polar([x2, y2, z2], stretch) + _push_matrix() + _translate(x1, y1, z1) + _rotate(angle, *axis) + _scale(r, r, length) + _gl33.draw_lit(_gl33.get_unit_cylinder()) + + def unapply(self): + _pop_matrix() + +HalLine = Line + + +_grid_mesh_cache = {} + +def _get_grid_mesh(size): + key = round(float(size), 5) + mesh = _grid_mesh_cache.get(key) + if mesh is None: + s = abs(float(size)) + # Legacy Vismach drew grid lines every 10 units (capped at 200 divisions per side) + d = max(10.0, s / 200.0) if s > 0 else 10.0 + n = int(round(s / d)) + verts = [] + for i in range(-n, n + 1): + p = i * d + verts.extend([p, -s, 0.0, p, s, 0.0]) + verts.extend([-s, p, 0.0, s, p, 0.0]) + mesh = _VBOMesh(verts, stride_floats=3, mode=GL_LINES) + _grid_mesh_cache[key] = mesh + return mesh + +class Grid(CoordsBase): + """Reference grid in XY, from normal, or from normal+X-direction.""" + def __init__(self, *args): + prefix, vals = _split_prefix_and_args(args, (0, 1, 6, 7, 9, 10)) + if len(vals) in (0, 6, 9): + vals = tuple(vals) + (500.0,) + self._mode = {1: "xy", 7: "normal", 10: "basis"}[len(vals)] + super().__init__(prefix, *vals) + + def draw(self): + if self._mode == "xy": (s,) = self.coords() + _push_matrix() elif self._mode == "normal": - x, y, z, vx, vy, vz, s = self.coords() - _apply_normal_or_basis((x, y, z), (vx, vy, vz)) + ox, oy, oz, nx, ny, nz, s = self.coords() + _apply_normal_or_basis((ox, oy, oz), (nx, ny, nz)) else: ox, oy, oz, xx, xy, xz, zx, zy, zz, s = self.coords() _apply_normal_or_basis((ox, oy, oz), (zx, zy, zz), (xx, xy, xz)) - - _sync_gl_modelview() - _draw_grid_lines(s) + _gl33.draw_flat(_get_grid_mesh(s)) def unapply(self): - if self._mode != "origin": - _pop_matrix() - + _pop_matrix() HalGrid = Grid HalGridFromNormal = Grid HalGridFromNormalAndDirection = Grid -class Plane(ArgsBase): - """ - Replaces legacy class: - - HalPlaneFromNormal([comp,] x, y, z, vx, vy, vz, s=500) - and adds: - - Plane([comp,] s=500) - - Plane([comp,] ox, oy, oz, xx, xy, xz, zx, zy, zz, s=500) - """ - def __init__(self, *args, **kwargs): - comp, rest = _split_comp(args) - n = len(rest) - - if n in (0, 1): - self._mode = "origin" - s = rest[0] if n == 1 else kwargs.get("s", 500) - ArgsBase.__init__(self, comp, s) - elif n in (6, 7): - self._mode = "normal" - x, y, z, vx, vy, vz = rest[:6] - s = rest[6] if n == 7 else kwargs.get("s", 500) - ArgsBase.__init__(self, comp, x, y, z, vx, vy, vz, s) - elif n in (9, 10): - self._mode = "normal_dir" - ox, oy, oz, xx, xy, xz, zx, zy, zz = rest[:9] - s = rest[9] if n == 10 else kwargs.get("s", 500) - ArgsBase.__init__(self, comp, ox, oy, oz, xx, xy, xz, zx, zy, zz, s) - else: - raise TypeError("Plane expects 0-1, 6-7, or 9-10 arguments after optional comp") +class Plane(CoordsBase): + """Square plane from normal or normal+X-direction.""" + def __init__(self, *args): + prefix, vals = _split_prefix_and_args(args, (6, 7, 9, 10)) + if len(vals) in (6, 9): + vals = tuple(vals) + (500.0,) + self._mode = {7: "normal", 10: "basis"}[len(vals)] + super().__init__(prefix, *vals) def draw(self): - if self._mode == "origin": - (s,) = self.coords() - n = (0, 0, 1) - elif self._mode == "normal": - x, y, z, vx, vy, vz, s = self.coords() - n = (vx, vy, vz) - _apply_normal_or_basis((x, y, z), n) + if self._mode == "normal": + ox, oy, oz, nx, ny, nz, s = self.coords() + _apply_normal_or_basis((ox, oy, oz), (nx, ny, nz)) else: ox, oy, oz, xx, xy, xz, zx, zy, zz, s = self.coords() - n = (zx, zy, zz) - _apply_normal_or_basis((ox, oy, oz), n, (xx, xy, xz)) - - _sync_gl_modelview() - glPushAttrib(GL_ENABLE_BIT) - glDisable(GL_CULL_FACE) - glBegin(GL_QUADS) - glNormal3f(*n) - glVertex3f(s, s, 0) - glVertex3f(-s, s, 0) - glVertex3f(-s, -s, 0) - glVertex3f(s, -s, 0) - glEnd() - glPopAttrib() + _apply_normal_or_basis((ox, oy, oz), (zx, zy, zz), (xx, xy, xz)) + _scale(s, s, 1.0) + _gl33.draw_lit(_gl33.get_unit_quad()) def unapply(self): - if self._mode != "origin": - _pop_matrix() - + _pop_matrix() HalPlaneFromNormal = Plane +HalPlaneFromNormalAndDirection = Plane -class Coords(ArgsBase): - """ - Replaces legacy class: - - HalCoordsFromNormalAndDirection ([comp,] ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch=1, r=5) - and adds: - - Coords([comp,] stretch=1, r=5) - - Coords([comp,] ox, oy, oz, zx, zy, zz, stretch=1, r=5) - """ - def __init__(self, *args, **kwargs): - comp, rest = _split_comp(args) - n = len(rest) - - if n <= 2: - self._mode = "origin" - stretch = rest[0] if n >= 1 else kwargs.get("stretch", 1) - r = rest[1] if n == 2 else kwargs.get("r", 5) - ArgsBase.__init__(self, comp, stretch, r) - elif n in (6, 7, 8): - self._mode = "normal" - ox, oy, oz, zx, zy, zz = rest[:6] - stretch = rest[6] if n >= 7 else kwargs.get("stretch", 1) - r = rest[7] if n == 8 else kwargs.get("r", 5) - ArgsBase.__init__(self, comp, ox, oy, oz, zx, zy, zz, stretch, r) - elif n in (9, 10, 11): - self._mode = "normal_dir" - ox, oy, oz, xx, xy, xz, zx, zy, zz = rest[:9] - stretch = rest[9] if n >= 10 else kwargs.get("stretch", 1) - r = rest[10] if n == 11 else kwargs.get("r", 5) - ArgsBase.__init__(self, comp, ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch, r) - else: - raise TypeError("Coords expects 0-2, 6-8, or 9-11 arguments after optional comp") +class Coords(CoordsBase): + """RGB XYZ coordinate triad at origin, from normal, or from normal+X-direction.""" + def __init__(self, *args): + prefix, vals = _split_prefix_and_args(args, (0, 1, 2, 6, 7, 8, 9, 10, 11)) + if len(vals) in (0, 6, 9): + vals = tuple(vals) + (1.0, 1.0) + elif len(vals) in (1, 7, 10): + vals = tuple(vals) + (1.0,) + self._mode = {2: "origin", 8: "normal", 11: "basis"}[len(vals)] + super().__init__(prefix, *vals) def draw_vector(self, r, stretch, color): - _sync_gl_modelview() - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color) - gluCylinder(self.q, r, r, 50 * stretch, 32, 1) + prev_col = list(_gl33.color) + _gl33.color = list(color) + _push_matrix() + _scale(r, r, 50.0 * stretch) + _gl33.draw_lit(_gl33.get_unit_cylinder()) + _pop_matrix() + _gl33.color = prev_col def draw(self): if self._mode == "origin": @@ -1094,55 +1404,104 @@ def draw(self): ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch, r = self.coords() _apply_normal_or_basis((ox, oy, oz), (zx, zy, zz), (xx, xy, xz)) - glPushAttrib(GL_LIGHTING_BIT) - self.draw_vector(r, stretch, [0, 0, 1, 1]) + self.draw_vector(r, stretch, [0.0, 0.0, 1.0, 1.0]) _rotate(90, 0, 1, 0) - self.draw_vector(r, stretch, [1, 0, 0, 1]) + self.draw_vector(r, stretch, [1.0, 0.0, 0.0, 1.0]) _rotate(-90, 1, 0, 0) - self.draw_vector(r, stretch, [0, 1, 0, 1]) - glPopAttrib() + self.draw_vector(r, stretch, [0.0, 1.0, 0.0, 1.0]) def unapply(self): _pop_matrix() - +HalCoordsFromNormal = Coords HalCoordsFromNormalAndDirection = Coords -class _CylinderAxis(ArgsBase): - """Shared base class for axis-aligned capped cylinders (X, Y, or Z).""" - _axis_rotation = None # (angle_deg, x, y, z) or None for Z-axis +_frustum_mesh_cache = {} + +def _get_frustum_mesh(r1, r2, h, slices=32): + key = (round(float(r1), 5), round(float(r2), 5), round(float(h), 5), slices) + mesh = _frustum_mesh_cache.get(key) + if mesh is None: + r1, r2, h = float(r1), float(r2), float(h) + slope_len = hypot(h, r1 - r2) + nr = (h / slope_len) if slope_len > 1e-12 else 1.0 + nz = ((r1 - r2) / slope_len) if slope_len > 1e-12 else 0.0 + floats = [] + for i in range(slices): + a0 = (2.0 * pi * i) / slices + a1 = (2.0 * pi * (i + 1)) / slices + c0, s0 = cos(a0), sin(a0) + c1, s1 = cos(a1), sin(a1) + n0 = (c0 * nr, s0 * nr, nz) + n1 = (c1 * nr, s1 * nr, nz) + p00 = (r1 * c0, r1 * s0, 0.0) + p10 = (r1 * c1, r1 * s1, 0.0) + p11 = (r2 * c1, r2 * s1, h) + p01 = (r2 * c0, r2 * s0, h) + floats.extend([ + *p00, *n0, *p10, *n1, *p11, *n1, + *p00, *n0, *p11, *n1, *p01, *n0, + ]) + mesh = _VBOMesh(floats, stride_floats=6, mode=GL_TRIANGLES) + _frustum_mesh_cache[key] = mesh + return mesh + + +class _CylinderAxis(CoordsBase): + """Base for closed cylinders/cones aligned along X, Y, or Z.""" + _axis_rotation = None + + def __init__(self, *args): + prefix, vals = _split_prefix_and_args(args, (4,)) + super().__init__(prefix, *vals) def draw(self): p1, r1, p2, r2 = self.coords() if p1 > p2: p1, p2 = p2, p1 r1, r2 = r2, r1 + h = p2 - p1 _push_matrix() if self._axis_rotation is not None: _rotate(*self._axis_rotation) - _translate(0, 0, p1) - _sync_gl_modelview() - gluCylinder(self.q, r1, r2, p2 - p1, 32, 1) + _translate(0.0, 0.0, p1) + + if abs(r1 - r2) < 1e-9: + _push_matrix() + _scale(r1, r1, h) + _gl33.draw_lit(_gl33.get_unit_cylinder()) + _pop_matrix() + else: + _gl33.draw_lit(_get_frustum_mesh(r1, r2, h)) # Bottom cap - _rotate(180, 1, 0, 0) - _sync_gl_modelview() - gluDisk(self.q, 0, r1, 32, 1) - _rotate(180, 1, 0, 0) + if r1 > 0.0: + _push_matrix() + _rotate(180.0, 1.0, 0.0, 0.0) + _scale(r1, r1, 1.0) + _gl33.draw_lit(_gl33.get_unit_disk()) + _pop_matrix() # Top cap - _push_matrix() - _translate(0, 0, p2 - p1) - _sync_gl_modelview() - gluDisk(self.q, 0, r2, 32, 1) - _pop_matrix() + if r2 > 0.0: + _push_matrix() + _translate(0.0, 0.0, h) + _scale(r2, r2, 1.0) + _gl33.draw_lit(_gl33.get_unit_disk()) + _pop_matrix() + _pop_matrix() def volume(self): p1, r1, p2, r2 = self.coords() - return (pi / 3.0) * abs(p1 - p2) * (r1 * r1 + r1 * r2 + r2 * r2) + h = abs(p1 - p2) + return pi * h / 3.0 * (r1 * r1 + r1 * r2 + r2 * r2) + + +class CylinderZ(_CylinderAxis): + _axis_rotation = None class CylinderX(_CylinderAxis): @@ -1153,344 +1512,205 @@ class CylinderY(_CylinderAxis): _axis_rotation = (-90, 1, 0, 0) -class CylinderZ(_CylinderAxis): - _axis_rotation = None - +class Sphere(CoordsBase): + def __init__(self, *args): + prefix, vals = _split_prefix_and_args(args, (4,)) + super().__init__(prefix, *vals) -# give center and radius -class Sphere(ArgsBase): def draw(self): x, y, z, r = self.coords() _push_matrix() _translate(x, y, z) - _sync_gl_modelview() - gluSphere(self.q, r, 32, 16) + _scale(r, r, r) + _gl33.draw_lit(_gl33.get_unit_sphere()) _pop_matrix() def volume(self): x, y, z, r = self.coords() - vol = 1.3333333*3.1415927*r*r*r - return vol + return 4.0 / 3.0 * pi * r * r * r -# triangular plate in XY plane -# specify the corners Z values for each side -class TriangleXY(ArgsBase): - def draw(self): - _sync_gl_modelview() - x1, y1, x2, y2, x3, y3, z1, z2 = self.coords() - x12 = x1-x2 - y12 = y1-y2 - x13 = x1-x3 - y13 = y1-y3 - cross = x12*y13 - x13*y12 - if cross < 0: - tmp = x2 - x2 = x3 - x3 = tmp - tmp = y2 - y2 = y3 - y3 = tmp +_tri_prism_cache = {} + + +def _get_tri_prism_mesh(x1, y1, x2, y2, x3, y3, z1, z2): + key = tuple(round(float(v), 5) for v in (x1, y1, x2, y2, x3, y3, z1, z2)) + mesh = _tri_prism_cache.get(key) + if mesh is None: + x1, y1, x2, y2, x3, y3, z1, z2 = [float(v) for v in key] if z1 > z2: - tmp = z1 - z1 = z2 - z2 = tmp - x12 = x1-x2 - y12 = y1-y2 - x23 = x2-x3 - y23 = y2-y3 - x31 = x3-x1 - y31 = y3-y1 - glBegin(GL_QUADS) - # side 1-2 - h = hypot(x12,y12) - glNormal3f(-y12/h,x12/h,0) - glVertex3f(x1, y1, z1) - glVertex3f(x2, y2, z1) - glVertex3f(x2, y2, z2) - glVertex3f(x1, y1, z2) - # side 2-3 - h = hypot(x23,y23) - glNormal3f(-y23/h,x23/h,0) - glVertex3f(x2, y2, z1) - glVertex3f(x3, y3, z1) - glVertex3f(x3, y3, z2) - glVertex3f(x2, y2, z2) - # side 3-1 - h = hypot(x31,y31) - glNormal3f(-y31/h,x31/h,0) - glVertex3f(x3, y3, z1) - glVertex3f(x1, y1, z1) - glVertex3f(x1, y1, z2) - glVertex3f(x3, y3, z2) - glEnd() - glBegin(GL_TRIANGLES) - # upper face - glNormal3f(0,0,1) - glVertex3f(x1, y1, z2) - glVertex3f(x2, y2, z2) - glVertex3f(x3, y3, z2) - # lower face - glNormal3f(0,0,-1) - glVertex3f(x1, y1, z1) - glVertex3f(x3, y3, z1) - glVertex3f(x2, y2, z1) - glEnd() + z1, z2 = z2, z1 + if (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1) < 0: + x2, x3 = x3, x2 + y2, y3 = y3, y2 + + floats = [] + # Bottom face (normal 0, 0, -1) + for vx, vy in ((x1, y1), (x3, y3), (x2, y2)): + floats.extend([vx, vy, z1, 0.0, 0.0, -1.0]) + # Top face (normal 0, 0, 1) + for vx, vy in ((x1, y1), (x2, y2), (x3, y3)): + floats.extend([vx, vy, z2, 0.0, 0.0, 1.0]) + # Three side quads + for (ax, ay), (bx, by) in (((x1, y1), (x2, y2)), ((x2, y2), (x3, y3)), ((x3, y3), (x1, y1))): + nx, ny = by - ay, ax - bx + nl = hypot(nx, ny) + if nl > 1e-12: + nx /= nl + ny /= nl + p0 = (ax, ay, z1, nx, ny, 0.0) + p1 = (bx, by, z1, nx, ny, 0.0) + p2 = (bx, by, z2, nx, ny, 0.0) + p3 = (ax, ay, z2, nx, ny, 0.0) + floats.extend([*p0, *p1, *p2, *p0, *p2, *p3]) + + mesh = _VBOMesh(floats, stride_floats=6, mode=GL_TRIANGLES) + _tri_prism_cache[key] = mesh + return mesh + + +class TriangleXY(CoordsBase): + def __init__(self, *args): + prefix, vals = _split_prefix_and_args(args, (8,)) + super().__init__(prefix, *vals) + + def draw(self): + _gl33.draw_lit(_get_tri_prism_mesh(*self.coords())) def volume(self): x1, y1, x2, y2, x3, y3, z1, z2 = self.coords() - # compute pts 2 and 3 relative to 1 (puts pt1 at origin) - x2 = x2-x1 - x3 = x3-x1 - y2 = y2-y1 - y3 = y3-y1 - # compute area of triangle - area = 0.5*abs(x2*y3 - x3*y2) - thk = abs(z1-z2) - vol = area*thk - return vol + area = abs(0.5 * ((x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1))) + return abs(z2 - z1) * area + -# triangular plate in XZ plane class TriangleXZ(TriangleXY): - def coords(self): - x1, z1, x2, z2, x3, z3, y1, y2 = TriangleXY.coords(self) - return x1, z1, x2, z2, x3, z3, -y1, -y2 - def draw(self): _push_matrix() - _rotate(90,1,0,0) - # create the triangle in XY plane - TriangleXY.draw(self) - # bottom cap + _rotate(90, 1, 0, 0) + super().draw() _pop_matrix() - def volume(self): - vol = TriangleXY.volume(self) - return vol -# triangular plate in YZ plane class TriangleYZ(TriangleXY): - def coords(self): - y1, z1, y2, z2, y3, z3, x1, x2 = TriangleXY.coords(self) - return z1, y1, z2, y2, z3, y3, -x1, -x2 - def draw(self): _push_matrix() - _rotate(90,0,-1,0) - # create the triangle in XY plane - TriangleXY.draw(self) - # bottom cap + _rotate(-90, 0, 1, 0) + super().draw() _pop_matrix() - def volume(self): - vol = TriangleXY.volume(self) - return vol +_arc_mesh_cache = {} -class ArcX(ArgsBase): - def draw(self): - _sync_gl_modelview() - x1, x2, r1, r2, a1, a2, steps = self.coords() + +def _get_arc_mesh(x1, x2, r1, r2, a1, a2, steps): + key = tuple(round(float(v), 5) for v in (x1, x2, r1, r2, a1, a2)) + (int(steps),) + mesh = _arc_mesh_cache.get(key) + if mesh is None: + x1, x2, r1, r2, a1, a2 = [float(v) for v in key[:6]] + steps = max(1, int(steps)) if x1 > x2: - tmp = x1 - x1 = x2 - x2 = tmp + x1, x2 = x2, x1 if r1 > r2: - tmp = r1 - r1 = r2 - r2 = tmp - while a1 > a2: - a2 = a2 + 360 - astep = ((a2-a1)/steps)*(pi/180) - a1rads = a1 * (pi/180) - # positive X end face - glBegin(GL_QUAD_STRIP) - glNormal3f(1,0,0) - n = 0 - while n <= steps: - angle = a1rads+n*astep - s = sin(angle) - c = cos(angle) - glVertex3f(x2, r1*s, r1*c) - glVertex3f(x2, r2*s, r2*c) - n = n + 1 - - glEnd() - # negative X end face - glBegin(GL_QUAD_STRIP) - glNormal3f(-1,0,0) - n = 0 - while n <= steps: - angle = a1rads+n*astep - s = sin(angle) - c = cos(angle) - glVertex3f(x1, r1*s, r1*c) - glVertex3f(x1, r2*s, r2*c) - n = n + 1 - glEnd() - # inner diameter - glBegin(GL_QUAD_STRIP) - n = 0 - while n <= steps: - angle = a1rads+n*astep - s = sin(angle) - c = cos(angle) - glNormal3f(0,-s, -c) - glVertex3f(x1, r1*s, r1*c) - glVertex3f(x2, r1*s, r1*c) - n = n + 1 - glEnd() - # outer diameter - glBegin(GL_QUAD_STRIP) - n = 0 - while n <= steps: - angle = a1rads+n*astep - s = sin(angle) - c = cos(angle) - glNormal3f(0, s, c) - glVertex3f(x1, r2*s, r2*c) - glVertex3f(x2, r2*s, r2*c) - n = n + 1 - glEnd() - # end plates - glBegin(GL_QUADS) - # first end plate - angle = a1 * (pi/180) - s = sin(angle) - c = cos(angle) - glNormal3f(0, -c, s) - glVertex3f(x1, r2*s, r2*c) - glVertex3f(x2, r2*s, r2*c) - glVertex3f(x2, r1*s, r1*c) - glVertex3f(x1, r1*s, r1*c) - # other end - angle = a2 * (pi/180) - s = sin(angle) - c = cos(angle) - glNormal3f(0, c, -s) - glVertex3f(x1, r2*s, r2*c) - glVertex3f(x2, r2*s, r2*c) - glVertex3f(x2, r1*s, r1*c) - glVertex3f(x1, r1*s, r1*c) - glEnd() + r1, r2 = r2, r1 + while a2 < a1: + a2 += 360.0 + a1 = radians(a1) + a2 = radians(a2) + da = (a2 - a1) / steps + + floats = [] + # End caps + for ang, sgn in ((a1, -1.0), (a2, 1.0)): + c, s = cos(ang), sin(ang) + n = (0.0, -s * sgn, c * sgn) + p0 = (x1, r1 * c, r1 * s) + p1 = (x2, r1 * c, r1 * s) + p2 = (x2, r2 * c, r2 * s) + p3 = (x1, r2 * c, r2 * s) + if sgn > 0: + floats.extend([*p0, *n, *p1, *n, *p2, *n, *p0, *n, *p2, *n, *p3, *n]) + else: + floats.extend([*p0, *n, *p2, *n, *p1, *n, *p0, *n, *p3, *n, *p2, *n]) + + for i in range(steps): + t0 = a1 + i * da + t1 = t0 + da + c0, s0 = cos(t0), sin(t0) + c1, s1 = cos(t1), sin(t1) + + # Inner & outer curved walls + for rad, nsgn in ((r1, -1.0), (r2, 1.0)): + n0 = (0.0, c0 * nsgn, s0 * nsgn) + n1 = (0.0, c1 * nsgn, s1 * nsgn) + p00 = (x1, rad * c0, rad * s0) + p10 = (x2, rad * c0, rad * s0) + p11 = (x2, rad * c1, rad * s1) + p01 = (x1, rad * c1, rad * s1) + if nsgn > 0: + floats.extend([*p00, *n0, *p10, *n0, *p11, *n1, *p00, *n0, *p11, *n1, *p01, *n1]) + else: + floats.extend([*p00, *n0, *p11, *n1, *p10, *n0, *p00, *n0, *p01, *n1, *p11, *n1]) + + # Left (x1) & right (x2) flat faces + for xval, xnorm in ((x1, -1.0), (x2, 1.0)): + n = (xnorm, 0.0, 0.0) + q0 = (xval, r1 * c0, r1 * s0) + q1 = (xval, r2 * c0, r2 * s0) + q2 = (xval, r2 * c1, r2 * s1) + q3 = (xval, r1 * c1, r1 * s1) + if xnorm > 0: + floats.extend([*q0, *n, *q1, *n, *q2, *n, *q0, *n, *q2, *n, *q3, *n]) + else: + floats.extend([*q0, *n, *q2, *n, *q1, *n, *q0, *n, *q3, *n, *q2, *n]) + + mesh = _VBOMesh(floats, stride_floats=6, mode=GL_TRIANGLES) + _arc_mesh_cache[key] = mesh + return mesh + + +class ArcX(CoordsBase): + def __init__(self, *args): + prefix, vals = _split_prefix_and_args(args, (6, 7)) + if len(vals) == 6: + vals = tuple(vals) + (16,) + super().__init__(prefix, *vals) + + def draw(self): + _gl33.draw_lit(_get_arc_mesh(*self.coords())) def volume(self): x1, x2, r1, r2, a1, a2, steps = self.coords() if x1 > x2: - tmp = x1 - x1 = x2 - x2 = tmp + x1, x2 = x2, x1 if r1 > r2: - tmp = r1 - r1 = r2 - r2 = tmp - while a1 > a2: - a2 = a2 + 360 - height = x2 - x1 - angle = a2 - a1 - area = (angle/360.0)*pi*(r2*r2-r1*r1) - vol = area * height - return vol - + r1, r2 = r2, r1 + while a2 < a1: + a2 += 360 + return abs(x2 - x1) * pi * (r2 * r2 - r1 * r1) * ((a2 - a1) / 360.0) +class Box(CoordsBase): + def __init__(self, *args): + prefix, vals = _split_prefix_and_args(args, (6,)) + super().__init__(prefix, *vals) -# six coordinate version - specify each side of the box -class Box(ArgsBase): def draw(self): - _sync_gl_modelview() x1, y1, z1, x2, y2, z2 = self.coords() if x1 > x2: - tmp = x1 - x1 = x2 - x2 = tmp + x1, x2 = x2, x1 if y1 > y2: - tmp = y1 - y1 = y2 - y2 = tmp + y1, y2 = y2, y1 if z1 > z2: - tmp = z1 - z1 = z2 - z2 = tmp - - glBegin(GL_QUADS) - # bottom face - glNormal3f(0,0,-1) - glVertex3f(x2, y1, z1) - glVertex3f(x1, y1, z1) - glVertex3f(x1, y2, z1) - glVertex3f(x2, y2, z1) - # positive X face - glNormal3f(1,0,0) - glVertex3f(x2, y1, z1) - glVertex3f(x2, y2, z1) - glVertex3f(x2, y2, z2) - glVertex3f(x2, y1, z2) - # positive Y face - glNormal3f(0,1,0) - glVertex3f(x1, y2, z1) - glVertex3f(x1, y2, z2) - glVertex3f(x2, y2, z2) - glVertex3f(x2, y2, z1) - # negative Y face - glNormal3f(0,-1,0) - glVertex3f(x2, y1, z2) - glVertex3f(x1, y1, z2) - glVertex3f(x1, y1, z1) - glVertex3f(x2, y1, z1) - # negative X face - glNormal3f(-1,0,0) - glVertex3f(x1, y1, z1) - glVertex3f(x1, y1, z2) - glVertex3f(x1, y2, z2) - glVertex3f(x1, y2, z1) - # top face - glNormal3f(0,0,1) - glVertex3f(x1, y2, z2) - glVertex3f(x1, y1, z2) - glVertex3f(x2, y1, z2) - glVertex3f(x2, y2, z2) - glEnd() + z1, z2 = z2, z1 + _push_matrix() + _translate(x1, y1, z1) + _scale(x2 - x1, y2 - y1, z2 - z1) + _gl33.draw_lit(_gl33.get_unit_box()) + _pop_matrix() def volume(self): x1, y1, z1, x2, y2, z2 = self.coords() - vol = abs((x1-x2)*(y1-y2)*(z1-z2)) - return vol - - -# specify the width in X and Y, and the height in Z -# the box is centered on the origin -class BoxCentered(Box): - def __init__(self, *args): - comp, rest = _split_comp(args) - if len(rest) == 0: - ArgsBase.__init__(self, comp) - elif len(rest) == 3: - ArgsBase.__init__(self, comp, *rest) - else: - raise TypeError("BoxCentered expects ([prefix,] xw, yw, zw)") - - def coords(self): - xw, yw, zw = ArgsBase.coords(self) - return [-xw / 2.0, -yw / 2.0, -zw / 2.0, xw / 2.0, yw / 2.0, zw / 2.0] - - -# specify the width in X and Y, and the height in Z -# the box is centered in X and Y, and runs from Z=0 up -# (or down) to the specified Z value -class BoxCenteredXY(Box): - def __init__(self, *args): - comp, rest = _split_comp(args) - if len(rest) == 0: - ArgsBase.__init__(self, comp) - elif len(rest) == 3: - ArgsBase.__init__(self, comp, *rest) - else: - raise TypeError("BoxCenteredXY expects ([prefix,] xw, yw, zw)") - - def coords(self): - xw, yw, zw = ArgsBase.coords(self) - return [-xw / 2.0, -yw / 2.0, 0, xw / 2.0, yw / 2.0, zw] + return abs((x2 - x1) * (y2 - y1) * (z2 - z1)) def _mesh_source_stamp(filename, data): @@ -1507,20 +1727,48 @@ def _compute_tri_normal(t): dx2, dy2, dz2 = t[2][0] - t[0][0], t[2][1] - t[0][1], t[2][2] - t[0][2] return [dy1 * dz2 - dy2 * dz1, dz1 * dx2 - dz2 * dx1, dy1 * dx2 - dy2 * dx1] + +class BoxCentered(Box): + def __init__(self, *args): + prefix, vals = _split_prefix_and_args(args, (3,)) + xw, yw, zw = vals + super().__init__( + prefix, + "{-0.5 * (%s)}" % xw if isinstance(xw, str) else -0.5 * xw, + "{-0.5 * (%s)}" % yw if isinstance(yw, str) else -0.5 * yw, + "{-0.5 * (%s)}" % zw if isinstance(zw, str) else -0.5 * zw, + "{0.5 * (%s)}" % xw if isinstance(xw, str) else 0.5 * xw, + "{0.5 * (%s)}" % yw if isinstance(yw, str) else 0.5 * yw, + "{0.5 * (%s)}" % zw if isinstance(zw, str) else 0.5 * zw, + ) + + +class BoxCenteredXY(Box): + def __init__(self, *args): + prefix, vals = _split_prefix_and_args(args, (3,)) + xw, yw, zw = vals + super().__init__( + prefix, + "{-0.5 * (%s)}" % xw if isinstance(xw, str) else -0.5 * xw, + "{-0.5 * (%s)}" % yw if isinstance(yw, str) else -0.5 * yw, + 0, + "{0.5 * (%s)}" % xw if isinstance(xw, str) else 0.5 * xw, + "{0.5 * (%s)}" % yw if isinstance(yw, str) else 0.5 * yw, + zw, + ) + + class _MeshBase: - """Shared base for reloadable STL and OBJ mesh loaders.""" + """Shared base for reloadable STL and OBJ mesh loaders (OpenGL 3.3 VBO/VAO).""" def __init__(self, filename=None, data=None): self._filename = filename self._data = data self._source_stamp = None - self.list = None - self._stale_list = None - self._reset_storage() + self._vbo_mesh = None + self._stale_mesh = None + self._pending_floats = [] self.reload(filename, data, force=True) - def _reset_storage(self): - pass - def _read_lines(self, filename=None, data=None): if data is None: with open(filename, "r", encoding="utf-8", errors="replace") as f: @@ -1544,38 +1792,26 @@ def reload(self, filename=None, data=None, force=False): if not force and new_stamp == self._source_stamp: return False - self._load(self._filename, self._data) + self._pending_floats = self._build_floats(self._filename, self._data) self._source_stamp = new_stamp - if self.list is not None: - self._stale_list = self.list - self.list = None + if self._vbo_mesh is not None: + self._stale_mesh = self._vbo_mesh + self._vbo_mesh = None return True def draw(self): - _sync_gl_modelview() - if self._stale_list is not None: - glDeleteLists(self._stale_list, 1) - self._stale_list = None - if self.list is None: - # OpenGL isn't ready yet in __init__ so the display list - # is created during the first draw - new_list = glGenLists(1) - glNewList(new_list, GL_COMPILE) - try: - self._emit_gl() - finally: - glEndList() - self.list = new_list - self._reset_storage() - glCallList(self.list) + if self._stale_mesh is not None: + self._stale_mesh.delete() + self._stale_mesh = None + if self._vbo_mesh is None: + self._vbo_mesh = _VBOMesh(self._pending_floats, stride_floats=6, mode=GL_TRIANGLES) + self._pending_floats = [] + _gl33.draw_lit(self._vbo_mesh) class STL(_MeshBase): """Loads both ASCII and Binary STL files or data buffers.""" - def _reset_storage(self): - self.d = [] - - def _load(self, filename=None, data=None): + def _build_floats(self, filename=None, data=None): raw_bytes = None if data is None and filename is not None: with open(filename, "rb") as f: @@ -1583,90 +1819,78 @@ def _load(self, filename=None, data=None): elif isinstance(data, bytes): raw_bytes = data - if raw_bytes is not None: - # Binary STL: 80-byte header + uint32 triangle count + 50 bytes per triangle - if len(raw_bytes) >= 84: - tri_count = struct.unpack("= 84: + tri_count = struct.unpack("= 3 else None + norm = vn[n_idx - 1] if n_idx else face_n + floats.extend([pos[0], pos[1], pos[2], norm[0], norm[1], norm[2]]) + return floats def parse_int(self, i): - if i == '': - return None - return int(i) + return None if i == "" else int(i) def parse_slash(self, word): return [self.parse_int(i) for i in word.split("/")] @@ -1674,24 +1898,6 @@ def parse_slash(self, word): def parse_face(self, line): return [self.parse_slash(w) for w in line.split()[1:]] - def _emit_gl(self): - glPushAttrib(GL_ENABLE_BIT) - glDisable(GL_CULL_FACE) - glBegin(GL_TRIANGLES) - for face in self.f: - v0, v1, v2 = self.v[face[0][0] - 1], self.v[face[1][0] - 1], self.v[face[2][0] - 1] - face_n = _compute_tri_normal((v0, v1, v2)) - for vert in face: - v = vert[0] - n = vert[2] if len(vert) >= 3 else None - if n: - glNormal3f(*self.vn[n - 1]) - else: - glNormal3f(*face_n) - glVertex3f(*self.v[v - 1]) - glEnd() - glPopAttrib() - AsciiSTL = STL AsciiOBJ = OBJ @@ -1788,177 +1994,469 @@ def _compile_hud_template(template, prefix_cache): return lambda f=fmt_str, gs=getters: f.format(*[g() for g in gs]) # head up display - draws a semi-transparent text box. +_FONT_8X13 = { + 32: (0,0,0,0,0,0,0,0,0,0,0,0,0), 33: (24,24,24,24,24,24,24,0,0,24,24,0,0), + 34: (102,102,102,36,0,0,0,0,0,0,0,0,0), 35: (0,36,36,126,36,36,36,126,36,36,0,0,0), + 36: (24,60,102,96,60,30,6,102,60,24,0,0,0), 37: (0,98,102,12,24,48,102,70,0,0,0,0,0), + 38: (56,108,108,56,118,220,204,204,118,0,0,0,0), 39: (24,24,24,48,0,0,0,0,0,0,0,0,0), + 40: (12,24,48,48,48,48,48,48,24,12,0,0,0), 41: (48,24,12,12,12,12,12,12,24,48,0,0,0), + 42: (0,0,102,60,255,60,102,0,0,0,0,0,0), 43: (0,0,24,24,126,24,24,0,0,0,0,0,0), + 44: (0,0,0,0,0,0,0,0,24,24,48,0,0), 45: (0,0,0,0,126,0,0,0,0,0,0,0,0), + 46: (0,0,0,0,0,0,0,0,24,24,0,0,0), 47: (6,6,12,24,24,48,96,96,0,0,0,0,0), + 48: (60,102,110,118,102,102,102,60,0,0,0,0,0), 49: (24,56,24,24,24,24,24,126,0,0,0,0,0), + 50: (60,102,6,12,24,48,96,126,0,0,0,0,0), 51: (60,102,6,28,6,6,102,60,0,0,0,0,0), + 52: (12,28,60,108,204,254,12,12,0,0,0,0,0), 53: (126,96,124,6,6,6,102,60,0,0,0,0,0), + 54: (60,96,96,124,102,102,102,60,0,0,0,0,0), 55: (126,102,6,12,24,24,24,24,0,0,0,0,0), + 56: (60,102,102,60,102,102,102,60,0,0,0,0,0), 57: (60,102,102,62,6,6,12,56,0,0,0,0,0), + 58: (0,0,24,24,0,0,24,24,0,0,0,0,0), 59: (0,0,24,24,0,0,24,24,48,0,0,0,0), + 60: (6,12,24,48,96,48,24,12,6,0,0,0,0), 61: (0,0,0,126,0,126,0,0,0,0,0,0,0), + 62: (96,48,24,12,6,12,24,48,96,0,0,0,0), 63: (60,102,6,12,24,24,0,24,24,0,0,0,0), + 64: (60,102,110,110,110,96,102,60,0,0,0,0,0), 65: (24,60,102,102,126,102,102,102,0,0,0,0,0), + 66: (124,102,102,124,102,102,102,124,0,0,0,0,0), 67: (60,102,96,96,96,96,102,60,0,0,0,0,0), + 68: (120,108,102,102,102,102,108,120,0,0,0,0,0), 69: (126,96,96,120,96,96,96,126,0,0,0,0,0), + 70: (126,96,96,120,96,96,96,96,0,0,0,0,0), 71: (60,102,96,96,110,102,102,62,0,0,0,0,0), + 72: (102,102,102,126,102,102,102,102,0,0,0,0,0), 73: (60,24,24,24,24,24,24,60,0,0,0,0,0), + 74: (30,12,12,12,12,108,108,56,0,0,0,0,0), 75: (102,108,120,112,120,108,102,102,0,0,0,0,0), + 76: (96,96,96,96,96,96,96,126,0,0,0,0,0), 77: (198,238,254,214,198,198,198,198,0,0,0,0,0), + 78: (102,118,126,126,110,102,102,102,0,0,0,0,0), 79: (60,102,102,102,102,102,102,60,0,0,0,0,0), + 80: (124,102,102,124,96,96,96,96,0,0,0,0,0), 81: (60,102,102,102,102,118,108,54,0,0,0,0,0), + 82: (124,102,102,124,120,108,102,102,0,0,0,0,0), 83: (60,102,96,60,6,6,102,60,0,0,0,0,0), + 84: (126,24,24,24,24,24,24,24,0,0,0,0,0), 85: (102,102,102,102,102,102,102,60,0,0,0,0,0), + 86: (102,102,102,102,102,60,60,24,0,0,0,0,0), 87: (198,198,198,198,214,254,238,198,0,0,0,0,0), + 88: (102,102,60,24,60,102,102,102,0,0,0,0,0), 89: (102,102,102,60,24,24,24,24,0,0,0,0,0), + 90: (126,6,12,24,48,96,96,126,0,0,0,0,0), 91: (60,48,48,48,48,48,48,48,48,60,0,0,0), + 92: (96,96,48,24,24,12,6,6,0,0,0,0,0), 93: (60,12,12,12,12,12,12,12,12,60,0,0,0), + 94: (24,60,102,0,0,0,0,0,0,0,0,0,0), 95: (0,0,0,0,0,0,0,0,0,255,0,0,0), + 96: (48,24,12,0,0,0,0,0,0,0,0,0,0), 97: (0,0,60,6,62,102,102,62,0,0,0,0,0), + 98: (96,96,124,102,102,102,102,124,0,0,0,0,0), 99: (0,0,60,102,96,96,102,60,0,0,0,0,0), + 100: (6,6,62,102,102,102,102,62,0,0,0,0,0), 101: (0,0,60,102,126,96,96,60,0,0,0,0,0), + 102: (28,54,48,124,48,48,48,48,0,0,0,0,0), 103: (0,0,62,102,102,62,6,102,60,0,0,0,0), + 104: (96,96,124,102,102,102,102,102,0,0,0,0,0), 105: (24,0,56,24,24,24,24,60,0,0,0,0,0), + 106: (12,0,28,12,12,12,12,108,56,0,0,0,0), 107: (96,96,102,108,120,108,102,102,0,0,0,0,0), + 108: (56,24,24,24,24,24,24,60,0,0,0,0,0), 109: (0,0,204,254,214,214,198,198,0,0,0,0,0), + 110: (0,0,124,102,102,102,102,102,0,0,0,0,0), 111: (0,0,60,102,102,102,102,60,0,0,0,0,0), + 112: (0,0,124,102,102,124,96,96,96,0,0,0,0), 113: (0,0,62,102,102,62,6,6,6,0,0,0,0), + 114: (0,0,110,118,96,96,96,96,0,0,0,0,0), 115: (0,0,62,96,60,6,6,124,0,0,0,0,0), + 116: (48,48,124,48,48,48,54,28,0,0,0,0,0), 117: (0,0,102,102,102,102,102,62,0,0,0,0,0), + 118: (0,0,102,102,102,60,60,24,0,0,0,0,0), 119: (0,0,198,198,214,254,108,108,0,0,0,0,0), + 120: (0,0,102,60,24,60,102,102,0,0,0,0,0), 121: (0,0,102,102,102,62,6,102,60,0,0,0,0), + 122: (0,0,126,12,24,48,96,126,0,0,0,0,0), 123: (14,24,24,112,24,24,24,14,0,0,0,0,0), + 124: (24,24,24,24,0,24,24,24,24,0,0,0,0), 125: (112,24,24,14,24,24,24,112,0,0,0,0,0), + 126: (54,108,0,0,0,0,0,0,0,0,0,0,0), +} + + class Hud(object): - def __init__(self, showme=1): - self.app = [] - self.strs = [] - self.messages = [] - self.fontbase = [] - self.hud_lines = [] - self.show_tags = [] - self.hide_alls = [] - self.hud_rgba_r = 0 - self.hud_rgba_g = 0.2 - self.hud_rgba_b = 0 - self.hud_rgba_a = 0.5 - self.hud_text_rgb_r = 1 - self.hud_text_rgb_g = 0.8 - self.hud_text_rgb_b = 0.4 - self.hide_hud = showme == 0 - - # legacy function, unconditionally hides the overlay - def hide(self): - self.hide_hud = True - - # legacy function, no longer supported, use add_txt() with a tag instead - def clear(self): - print("vismach.py, clear() deprecated, use add_txt() with a tag instead ") - - # legacy vismach models used this - def show(self, string): - self.hide_hud = False - self.add_txt(string) - - # displays a string (supports '{prefix.attr}' expressions), optionally a tag or list of tags can be assigned - def add_txt(self, string, tag=None): - prefix_cache = _capture_caller_prefixes() - self.hud_lines += [[_compile_hud_template(string, prefix_cache), None, tag]] + """Heads-up display rendered with an OpenGL 3.3 Core 2D shader and font atlas.""" + def __init__(self, showme=1): + self.app = [] + self.strs = [] + self.messages = [] + self.hud_lines = [] + self.show_tags = [] + self.hide_alls = [] + self.hud_rgba_r = 0 + self.hud_rgba_g = 0.2 + self.hud_rgba_b = 0 + self.hud_rgba_a = 0.5 + self.hud_text_rgb_r = 1 + self.hud_text_rgb_g = 0.8 + self.hud_text_rgb_b = 0.4 + self.hide_hud = showme == 0 + self._font_spec = None + self._font_size = 15 + self._glyph_w = 9.0 + self._glyph_h = 15.0 + self._char_step_x = 9.0 + self._use_linear_filter = False + self._tex = None + self._vao = None + self._vbo = None + self._cached_key = None + self._cached_bg_count = 0 + self._cached_glyph_count = 0 + + def set_font(self, font_name=None, size=15): + """Sets a custom Xft font family/pattern (e.g. 'DejaVu Sans Mono') and pixel size.""" + self._font_spec = font_name + self._font_size = int(size) + self._cached_key = None + if self._tex is not None: + glDeleteTextures([self._tex]) + self._tex = None + + def hide(self): + self.hide_hud = True + + def clear(self): + print("vismach.py, clear() deprecated, use add_txt() with a tag instead ") + + def show(self, string): + self.hide_hud = False + self.add_txt(string) + + def add_txt(self, string, tag=None): + prefix_cache = _capture_caller_prefixes() + self.hud_lines += [[_compile_hud_template(string, prefix_cache), None, tag]] + + def add_pin(self, string, pin=None, tag=None): + prefix_cache = _capture_caller_prefixes() + pin_fn = _compile_hud_val(pin, prefix_cache) if pin is not None else None + self.hud_lines += [[str(string), pin_fn, tag]] + + def show_tag_if_same(self, tag, pin, val=True): + prefix_cache = _capture_caller_prefixes() + self.show_tags += [[tag, _compile_hud_val(pin, prefix_cache), val]] + + def show_tags_in_pin(self, pin, offs=0): + prefix_cache = _capture_caller_prefixes() + self.show_tags += [[_compile_hud_val(pin, prefix_cache), None, offs]] + + def hide_all(self, pin, val=True): + prefix_cache = _capture_caller_prefixes() + self.hide_alls += [[_compile_hud_val(pin, prefix_cache), val]] + + def set_hud_rgba(self, r, g, b, a): + self.hud_rgba_r = r + self.hud_rgba_g = g + self.hud_rgba_b = b + self.hud_rgba_a = a + + def set_hud_text_rgb(self, r, g, b): + self.hud_text_rgb_r = r + self.hud_text_rgb_g = g + self.hud_text_rgb_b = b + def _rasterize_xft_atlas(self, font_spec): + """Renders an anti-aliased glyph atlas using Linux's native libXft + XGetImage.""" + dpy = getattr(self.app, "_dpy", None) + x11 = getattr(self.app, "_x11", None) + if not dpy or not x11: + return None + try: + xft_path = ctypes.util.find_library("Xft") or "libXft.so.2" + xft = ctypes.CDLL(xft_path) + + class _XftFont(ctypes.Structure): + _fields_ = [ + ("ascent", ctypes.c_int), ("descent", ctypes.c_int), + ("height", ctypes.c_int), ("max_advance_width", ctypes.c_int), + ("charset", ctypes.c_void_p), ("pattern", ctypes.c_void_p), + ] + + class _XGlyphInfo(ctypes.Structure): + _fields_ = [ + ("width", ctypes.c_ushort), ("height", ctypes.c_ushort), + ("x", ctypes.c_short), ("y", ctypes.c_short), + ("xOff", ctypes.c_short), ("yOff", ctypes.c_short), + ] + + class _XRenderColor(ctypes.Structure): + _fields_ = [ + ("red", ctypes.c_ushort), ("green", ctypes.c_ushort), + ("blue", ctypes.c_ushort), ("alpha", ctypes.c_ushort), + ] + + class _XftColor(ctypes.Structure): + _fields_ = [("pixel", ctypes.c_ulong), ("color", _XRenderColor)] + + class _XImage(ctypes.Structure): + _fields_ = [ + ("width", ctypes.c_int), ("height", ctypes.c_int), + ("xoffset", ctypes.c_int), ("format", ctypes.c_int), + ("data", ctypes.c_void_p), ("byte_order", ctypes.c_int), + ("bitmap_unit", ctypes.c_int), ("bitmap_bit_order", ctypes.c_int), + ("bitmap_pad", ctypes.c_int), ("depth", ctypes.c_int), + ("bytes_per_line", ctypes.c_int), ("bits_per_pixel", ctypes.c_int), + ] + + screen = x11.XDefaultScreen(dpy) + root = x11.XRootWindow(dpy, screen) + x11.XDefaultVisual.argtypes = [ctypes.c_void_p, ctypes.c_int] + x11.XDefaultVisual.restype = ctypes.c_void_p + x11.XDefaultColormap.argtypes = [ctypes.c_void_p, ctypes.c_int] + x11.XDefaultColormap.restype = ctypes.c_ulong + x11.XDefaultDepth.argtypes = [ctypes.c_void_p, ctypes.c_int] + x11.XDefaultDepth.restype = ctypes.c_int + x11.XCreatePixmap.argtypes = [ + ctypes.c_void_p, ctypes.c_ulong, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint + ] + x11.XCreatePixmap.restype = ctypes.c_ulong + x11.XFreePixmap.argtypes = [ctypes.c_void_p, ctypes.c_ulong] + x11.XCreateGC.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_void_p] + x11.XCreateGC.restype = ctypes.c_void_p + x11.XFreeGC.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + x11.XSetForeground.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_ulong] + x11.XFillRectangle.argtypes = [ + ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p, + ctypes.c_int, ctypes.c_int, ctypes.c_uint, ctypes.c_uint + ] + x11.XGetImage.argtypes = [ + ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, + ctypes.c_uint, ctypes.c_uint, ctypes.c_ulong, ctypes.c_int + ] + x11.XGetImage.restype = ctypes.POINTER(_XImage) + x11.XDestroyImage.argtypes = [ctypes.POINTER(_XImage)] + + xft.XftFontOpenName.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p] + xft.XftFontOpenName.restype = ctypes.POINTER(_XftFont) + xft.XftFontClose.argtypes = [ctypes.c_void_p, ctypes.POINTER(_XftFont)] + xft.XftTextExtentsUtf8.argtypes = [ + ctypes.c_void_p, ctypes.POINTER(_XftFont), ctypes.c_char_p, + ctypes.c_int, ctypes.POINTER(_XGlyphInfo) + ] + xft.XftDrawCreate.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_ulong] + xft.XftDrawCreate.restype = ctypes.c_void_p + xft.XftDrawDestroy.argtypes = [ctypes.c_void_p] + xft.XftColorAllocValue.argtypes = [ + ctypes.c_void_p, ctypes.c_void_p, ctypes.c_ulong, + ctypes.POINTER(_XRenderColor), ctypes.POINTER(_XftColor) + ] + xft.XftDrawStringUtf8.argtypes = [ + ctypes.c_void_p, ctypes.POINTER(_XftColor), ctypes.POINTER(_XftFont), + ctypes.c_int, ctypes.c_int, ctypes.c_char_p, ctypes.c_int + ] + + visual = x11.XDefaultVisual(dpy, screen) + cmap = x11.XDefaultColormap(dpy, screen) + depth = x11.XDefaultDepth(dpy, screen) + + font_ptr = xft.XftFontOpenName(dpy, screen, font_spec.encode("utf-8")) + if not font_ptr: + return None + + xf = font_ptr.contents + ext = _XGlyphInfo() + xft.XftTextExtentsUtf8(dpy, font_ptr, b"M", 1, ctypes.byref(ext)) + + gw = max(8, int(ext.xOff) if ext.xOff > 0 else int(xf.max_advance_width)) + gh = max(12, int(xf.height) if xf.height > 0 else int(xf.ascent + xf.descent)) + ascent = max(8, int(xf.ascent)) + atlas_w, atlas_h = 128 * gw, gh + + pixmap = x11.XCreatePixmap(dpy, root, atlas_w, atlas_h, depth) + gc = x11.XCreateGC(dpy, pixmap, 0, None) + x11.XSetForeground(dpy, gc, 0) + x11.XFillRectangle(dpy, pixmap, gc, 0, 0, atlas_w, atlas_h) + + draw = xft.XftDrawCreate(dpy, pixmap, visual, cmap) + rc = _XRenderColor(65535, 65535, 65535, 65535) + xft_col = _XftColor() + xft.XftColorAllocValue(dpy, visual, cmap, ctypes.byref(rc), ctypes.byref(xft_col)) + + for code in range(32, 127): + ch_bytes = chr(code).encode("utf-8") + xft.XftDrawStringUtf8( + draw, ctypes.byref(xft_col), font_ptr, code * gw, ascent, ch_bytes, len(ch_bytes) + ) + + x11.XSync(dpy, 0) + img_ptr = x11.XGetImage(dpy, pixmap, 0, 0, atlas_w, atlas_h, 0xFFFFFFFF, 2) + if not img_ptr or not img_ptr.contents.data: + return None + + img = img_ptr.contents + bpp = max(1, img.bits_per_pixel // 8) + raw = ctypes.string_at(img.data, img.bytes_per_line * atlas_h) + chan = 1 if bpp >= 3 else 0 + alpha_plane = bytearray(atlas_w * atlas_h) + for row in range(atlas_h): + row_off = row * img.bytes_per_line + dst_off = row * atlas_w + for col in range(atlas_w): + alpha_plane[dst_off + col] = raw[row_off + col * bpp + chan] + + x11.XDestroyImage(img_ptr) + xft.XftDrawDestroy(draw) + xft.XftFontClose(dpy, font_ptr) + x11.XFreeGC(dpy, gc) + x11.XFreePixmap(dpy, pixmap) + + self._glyph_w = float(gw) + self._glyph_h = float(gh) + self._char_step_x = float(gw) + return atlas_w, atlas_h, bytes(alpha_plane) + except Exception: + return None - # displays a formatted pin or expression value (can be embedded in a string) - def add_pin(self, string, pin=None, tag=None): - prefix_cache = _capture_caller_prefixes() - pin_fn = _compile_hud_val(pin, prefix_cache) if pin is not None else None - self.hud_lines += [[str(string), pin_fn, tag]] + def _ensure_gl_resources(self): + if self._tex is not None: + return - # shows all lines with the specified tag if the pin/expression value = val - def show_tag_if_same(self, tag, pin, val=True): - prefix_cache = _capture_caller_prefixes() - self.show_tags += [[tag, _compile_hud_val(pin, prefix_cache), val]] + pt_size = max(8, int(round(self._font_size * 0.75))) + family = self._font_spec or "DejaVu Sans Mono" + xft_res = self._rasterize_xft_atlas("%s:size=%d" % (family, pt_size)) - # shows all lines with a tag equal to the pin/expression value + offset - def show_tags_in_pin(self, pin, offs=0): - prefix_cache = _capture_caller_prefixes() - self.show_tags += [[_compile_hud_val(pin, prefix_cache), None, offs]] + if xft_res is not None: + atlas_w, atlas_h, pixels = xft_res + self._use_linear_filter = True + else: + atlas_w, atlas_h = 1024, 16 + self._glyph_w = 8.0 + self._glyph_h = 16.0 + self._char_step_x = 9.0 + self._use_linear_filter = False + pixels = bytearray(atlas_w * atlas_h) + for code, rows in _FONT_8X13.items(): + x0 = code * 8 + for r_idx, bits in enumerate(rows): + y_off = (r_idx + 1) * atlas_w + x0 + for bit in range(8): + if bits & (1 << (7 - bit)): + pixels[y_off + bit] = 255 + pixels = bytes(pixels) + + self._tex = glGenTextures(1) + glBindTexture(GL_TEXTURE_2D, self._tex) + glPixelStorei(GL_UNPACK_ALIGNMENT, 1) + glTexImage2D( + GL_TEXTURE_2D, 0, GL_R8, atlas_w, atlas_h, 0, + GL_RED, GL_UNSIGNED_BYTE, pixels, + ) + filt = GL_LINEAR if self._use_linear_filter else GL_NEAREST + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filt) + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filt) + glBindTexture(GL_TEXTURE_2D, 0) + + if self._vao is None: + self._vao = glGenVertexArrays(1) + self._vbo = glGenBuffers(1) + glBindVertexArray(self._vao) + glBindBuffer(GL_ARRAY_BUFFER, self._vbo) + stride = 4 * 4 + glEnableVertexAttribArray(0) + glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, stride, ctypes.c_void_p(0)) + glEnableVertexAttribArray(1) + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, stride, ctypes.c_void_p(8)) + glBindBuffer(GL_ARRAY_BUFFER, 0) + glBindVertexArray(0) + + def _upload_and_draw_hud(self, drawtext, w, h, bg_rgba, txt_rgb): + cache_key = (tuple(drawtext), w, h, self._tex) + glBindVertexArray(self._vao) + glBindBuffer(GL_ARRAY_BUFFER, self._vbo) + + if cache_key != self._cached_key: + char_width = self._char_step_x + char_height = self._glyph_h + xmargin, ymargin = 5.0, 5.0 + ypos = float(h) + + maxlen = max(len(p) for p in drawtext) + box_w = float(maxlen * char_width + 2.0 * xmargin) + box_h = float(len(drawtext) * char_height + 2.0 * ymargin) + x0, y0 = 0.0, ypos - box_h + x1, y1 = box_w, ypos + all_floats = [ + x0, y0, 0.0, 0.0, + x1, y0, 0.0, 0.0, + x1, y1, 0.0, 0.0, + x0, y0, 0.0, 0.0, + x1, y1, 0.0, 0.0, + x0, y1, 0.0, 0.0, + ] + self._cached_bg_count = 6 + + ty = ypos - ymargin - char_height + 2.0 + for string in drawtext: + tx = xmargin + for ch in str(string): + code = ord(ch) + if 32 <= code <= 126: + u0 = code / 128.0 + u1 = (code + 1) / 128.0 + gx0, gy0 = tx, ty + gx1, gy1 = tx + self._glyph_w, ty + self._glyph_h + all_floats.extend([ + gx0, gy0, u0, 1.0, + gx1, gy0, u1, 1.0, + gx1, gy1, u1, 0.0, + gx0, gy0, u0, 1.0, + gx1, gy1, u1, 0.0, + gx0, gy1, u0, 0.0, + ]) + tx += char_width + ty -= char_height + + self._cached_glyph_count = (len(all_floats) // 4) - self._cached_bg_count + raw = struct.pack("<%df" % len(all_floats), *all_floats) + glBufferData(GL_ARRAY_BUFFER, len(raw), raw, GL_DYNAMIC_DRAW) + self._cached_key = cache_key + + ortho = _mat4_ortho(0.0, float(w), 0.0, float(h), -1.0, 1.0) + _gl33.hud.use() + _gl33.hud.set_mat4("u_proj", ortho) + + _gl33.hud.set_vec4("u_color", *bg_rgba) + _gl33.hud.set_int("u_use_tex", 0) + glDrawArrays(GL_TRIANGLES, 0, self._cached_bg_count) + + if self._cached_glyph_count > 0: + glActiveTexture(GL_TEXTURE0) + glBindTexture(GL_TEXTURE_2D, self._tex) + _gl33.hud.set_int("u_tex", 0) + _gl33.hud.set_vec4("u_color", *txt_rgb) + _gl33.hud.set_int("u_use_tex", 1) + glDrawArrays(GL_TRIANGLES, self._cached_bg_count, self._cached_glyph_count) + glBindTexture(GL_TEXTURE_2D, 0) + + glBindBuffer(GL_ARRAY_BUFFER, 0) + glBindVertexArray(0) - # hides the complete hud if the pin/expression value is equal to val - def hide_all(self, pin, val=True): - prefix_cache = _capture_caller_prefixes() - self.hide_alls += [[_compile_hud_val(pin, prefix_cache), val]] - - # changes the hud color and transparency - def set_hud_rgba(self, r, g, b, a): - self.hud_rgba_r = r - self.hud_rgba_g = g - self.hud_rgba_b = b - self.hud_rgba_a = a - - # changes the hud text color - def set_hud_text_rgb(self, r, g, b): - self.hud_text_rgb_r = r - self.hud_text_rgb_g = g - self.hud_text_rgb_b = b - - # update the lines in the hud using the lists created above - def draw(self): - messages = [] - show_list = [None] - # check if hud should be hidden - hide_hud_requested = False - for a in self.hide_alls: - cur_val = a[0]() if callable(a[0]) else hal.get_value(a[0]) - if cur_val == a[1]: - hide_hud_requested = True - if not self.hide_hud and not hide_hud_requested: - # create list of all line tags to be shown - for b in self.show_tags: - tag = None - if b[1] == None: # _show_tags_in_pin - raw_val = b[0]() if callable(b[0]) else hal.get_value(b[0]) - tag = int(raw_val + b[2]) - else: # _show_tag_if_same - cur_val = b[1]() if callable(b[1]) else hal.get_value(b[1]) - if cur_val == b[2]: - tag = b[0] - if not isinstance(tag, list): - tag = [tag] - if tag is not None: - show_list = show_list + tag - # build the - for c in self.hud_lines: - if not isinstance(c[2], list): - c[2] = [c[2]] - if any(item in c[2] for item in show_list): - if c[1] == None: # _txt - messages += [c[0]() if callable(c[0]) else c[0]] - else: # _pin - val = c[1]() if callable(c[1]) else hal.get_value(c[1]) - messages += [c[0].format(val)] - drawtext = self.strs + messages - - # draw head-up-display - # see axis.py for more font/color configurability - if len(drawtext) == 0: - return + def draw(self): + if _gl33.hud is None: + return + messages = [] + show_list = [None] + hide_hud_requested = False + for a in self.hide_alls: + cur_val = a[0]() if callable(a[0]) else hal.get_value(a[0]) + if cur_val == a[1]: + hide_hud_requested = True + if not self.hide_hud and not hide_hud_requested: + for b in self.show_tags: + tag = None + if b[1] is None: + raw_val = b[0]() if callable(b[0]) else hal.get_value(b[0]) + tag = int(raw_val + b[2]) + else: + cur_val = b[1]() if callable(b[1]) else hal.get_value(b[1]) + if cur_val == b[2]: + tag = b[0] + if not isinstance(tag, list): + tag = [tag] + if tag is not None: + show_list = show_list + tag + for c in self.hud_lines: + if not isinstance(c[2], list): + c[2] = [c[2]] + if any(item in c[2] for item in show_list): + if c[1] is None: + messages += [c[0]() if callable(c[0]) else c[0]] + else: + val = c[1]() if callable(c[1]) else hal.get_value(c[1]) + messages += [c[0].format(val)] + drawtext = self.strs + messages + if not drawtext: + return + + self._ensure_gl_resources() + w = max(1, int(self.app.winfo_width())) + h = max(1, int(self.app.winfo_height())) - glMatrixMode(GL_PROJECTION) - glPushMatrix() - glLoadIdentity() - - if not self.fontbase: - self.fontbase = int(self.app.loadbitmapfont("9x15")) - char_width, char_height = 9, 15 - xmargin, ymargin = 5, 5 - ypos = float(self.app.winfo_height()) - - glOrtho(0.0, self.app.winfo_width(), 0.0, ypos, -1.0, 1.0) - glMatrixMode(GL_MODELVIEW) - glPushMatrix() - glLoadIdentity() - - # draw the text box - maxlen = max([len(p) for p in drawtext]) - box_width = maxlen * char_width - glDepthFunc(GL_ALWAYS) - glDepthMask(GL_FALSE) - glDisable(GL_LIGHTING) - glEnable(GL_BLEND) - glEnable(GL_NORMALIZE) - glBlendFunc(GL_ONE, GL_CONSTANT_ALPHA) - # sets the color of the hud overlay - glColor3f(self.hud_rgba_r, self.hud_rgba_g, self.hud_rgba_b) - # rgba, sets the transparency of the overlay using the 'a' value - glBlendColor(0,0,0,self.hud_rgba_a) - glBegin(GL_QUADS) - glVertex3f(0, ypos, 1) #upper left - glVertex3f(0, ypos - 2*ymargin - char_height*len(drawtext), 1) #lower left - glVertex3f(box_width+2*xmargin, ypos - 2*ymargin - char_height*len(drawtext), 1) #lower right - glVertex3f(box_width+2*xmargin, ypos , 1) #upper right - glEnd() - glDisable(GL_BLEND) - glEnable(GL_LIGHTING) - - # fill the box with text - maxlen = 0 - ypos -= char_height+ymargin - i = 0 - glDisable(GL_LIGHTING) - # sets the color of the text in the hud - glColor3f(self.hud_text_rgb_r, self.hud_text_rgb_g, self.hud_text_rgb_b) - for string in drawtext: - maxlen = max(maxlen, len(string)) - glRasterPos2i(xmargin, int(ypos)) - for char in string: - glCallList(self.fontbase + ord(char)) - ypos -= char_height - i = i + 1 - glDepthFunc(GL_LESS) - glDepthMask(GL_TRUE) - glEnable(GL_LIGHTING) - - glPopMatrix() - glMatrixMode(GL_PROJECTION) - glPopMatrix() - glMatrixMode(GL_MODELVIEW) + glDisable(GL_DEPTH_TEST) + glEnable(GL_BLEND) + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) + + self._upload_and_draw_hud( + drawtext, + w, + h, + (self.hud_rgba_r, self.hud_rgba_g, self.hud_rgba_b, self.hud_rgba_a), + (self.hud_text_rgb_r, self.hud_text_rgb_g, self.hud_text_rgb_b, 1.0), + ) + + glDisable(GL_BLEND) + glEnable(GL_DEPTH_TEST) class O(rs274.OpenGLTk.Opengl): @@ -1967,38 +2465,33 @@ def __init__(self, *args, **kw): self.r_back = self.g_back = self.b_back = 0 self.plotdata = [] self.plotlen = 16000 - #does not show HUD by default self.hud = Hud() def basic_lighting(self): + global _active_prog self.activate() - glLightfv(GL_LIGHT0, GL_POSITION, (1, -1, .5, 0)) - glLightfv(GL_LIGHT0, GL_AMBIENT, (.2,.2,.2,0)) - glLightfv(GL_LIGHT0, GL_DIFFUSE, (.6,.6,.4,0)) - glLightfv(GL_LIGHT0+1, GL_POSITION, (-1, -1, .5, 0)) - glLightfv(GL_LIGHT0+1, GL_AMBIENT, (.0,.0,.0,0)) - glLightfv(GL_LIGHT0+1, GL_DIFFUSE, (.0,.0,.4,0)) - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, (1,1,1,0)) - glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, (0.0, 0.0, 0.0, 1.0)) + _active_prog = 0 + _gl33.init() glDisable(GL_CULL_FACE) - glEnable(GL_LIGHTING) - glEnable(GL_LIGHT0) - glEnable(GL_LIGHT0+1) glDepthFunc(GL_LESS) glEnable(GL_DEPTH_TEST) - glMatrixMode(GL_MODELVIEW) - glLoadIdentity() + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) def redraw(self, *args): global _stats_fresh, _render_pass, _has_transparent - if self.winfo_width() == 1: return + if self.winfo_width() == 1: + return poll_all_stats() + cam_proj = glGetFloatv(GL_PROJECTION_MATRIX) cam_mv = glGetFloatv(GL_MODELVIEW_MATRIX) + _proj_matrix[:] = [float(v) for row in cam_proj for v in row] _load_matrix([float(v) for row in cam_mv for v in row]) # Pass 1: Opaque geometry (also updates all Capture() transforms) _render_pass = "opaque" _has_transparent = False + _gl33.color = [1.0, 1.0, 1.0, 1.0] + _gl33.emission = [0.0, 0.0, 0.0] glDepthMask(GL_TRUE) glDisable(GL_BLEND) self.model.traverse() @@ -2006,6 +2499,8 @@ def redraw(self, *args): # Pass 2: Translucent geometry (only if any alpha < 1.0 was seen) if _has_transparent: _render_pass = "transparent" + _gl33.color = [1.0, 1.0, 1.0, 1.0] + _gl33.emission = [0.0, 0.0, 0.0] glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glDepthMask(GL_FALSE) @@ -2018,65 +2513,38 @@ def redraw(self, *args): _render_pass = "opaque" _stats_fresh = False - # current coords: world - # the matrices tool2view, work2view, and world2view - # transform from tool/work/world coords to viewport coords - # if we want to draw in tool coords, we need to do - # "tool -> view -> world" (since the current frame is world) - # and if we want to draw in work coords, we need - # "work -> view -> world". For both, we need to invert - # the world2view matrix to do the second step + view2world = invert(self.world2view.t) - # likewise, for backplot, we want to transform the tooltip - # position from tool coords (where it is [0,0,0]) to work - # coords, so we need tool -> view -> work - # so lets also invert the work2view matrix view2work = invert(self.work2view.t) - # since backplot lines only need vertices, not orientation, - # and the tooltip is at the origin, getting the tool coords - # is easy tx, ty, tz = self.tool2view.t[3][:3] - # now we have to transform them to the work frame - wx = tx*view2work[0][0]+ty*view2work[1][0]+tz*view2work[2][0]+view2work[3][0] - wy = tx*view2work[0][1]+ty*view2work[1][1]+tz*view2work[2][1]+view2work[3][1] - wz = tx*view2work[0][2]+ty*view2work[1][2]+tz*view2work[2][2]+view2work[3][2] - # wx, wy, wz are the values to use for backplot - # so we save them in a buffer + wx = tx * view2work[0][0] + ty * view2work[1][0] + tz * view2work[2][0] + view2work[3][0] + wy = tx * view2work[0][1] + ty * view2work[1][1] + tz * view2work[2][1] + view2work[3][1] + wz = tx * view2work[0][2] + ty * view2work[1][2] + tz * view2work[2][2] + view2work[3][2] if len(self.plotdata) == self.plotlen: del self.plotdata[:self.plotlen // 10] - point = [ wx, wy, wz ] + point = [wx, wy, wz] if not self.plotdata or point != self.plotdata[-1]: self.plotdata.append(point) - # we can also draw in the work coord system _push_matrix() - # "work -> view -> world" _mult_matrix(_rows_to_mat4(view2world)) _mult_matrix(_rows_to_mat4(self.work2view.t)) - _sync_gl_modelview() - - #draw head up display - if(hasattr(self.hud, "draw")): - self.hud.draw() - # draw backplot - glDisable(GL_LIGHTING) - glLineWidth(2) - glColor3f(1.0,0.5,0.5) + if hasattr(self.hud, "draw"): + self.hud.draw() - glBegin(GL_LINE_STRIP) - for p in self.plotdata: - glVertex3f(*p) - glEnd() + if len(self.plotdata) >= 2: + glLineWidth(2) + _gl33.color = [1.0, 0.5, 0.5, 1.0] + line_floats = [] + for p in self.plotdata: + line_floats.extend([float(p[0]), float(p[1]), float(p[2])]) + bp_mesh = _VBOMesh(line_floats, stride_floats=3, mode=GL_LINE_STRIP) + _gl33.draw_flat(bp_mesh) + bp_mesh.delete() + glLineWidth(1) - glEnable(GL_LIGHTING) - glColor3f(1,1,1) - glLineWidth(1) - glDisable(GL_BLEND) - glDepthFunc(GL_LESS) - - # back to world again _pop_matrix() def plotclear(self): @@ -2129,25 +2597,47 @@ def main(model, tool, work, size=10, hud=0, rotation_vectors=None, lat=0, lon=0, t.pack(fill="both", expand=1) + _running = True + def update(): global old_plotclear, _stats_fresh - _stats_fresh = False - poll_all_stats() - if function: - function() - t.tkRedraw() - new_plotclear = vcomp["plotclear"] - if new_plotclear and not old_plotclear: - t.plotclear() - old_plotclear = new_plotclear - t.after(100, update) + if not _running: + return + try: + _stats_fresh = False + poll_all_stats() + if function: + function() + # Stop redrawing if the window was destroyed during shutdown + if not t.winfo_exists(): + return + t.tkRedraw() + new_plotclear = vcomp["plotclear"] + if new_plotclear and not old_plotclear: + t.plotclear() + old_plotclear = new_plotclear + if _running: + t.after(100, update) + except (SystemExit, tkinter.TclError): + # Ignore Tcl/exit errors triggered mid-frame during teardown + pass update() def quit(*args): - raise SystemExit + # Stop scheduled updates and exit mainloop cleanly instead of raising + # SystemExit inside a ctypes/OpenGL call + nonlocal _running + _running = False + try: + app.quit() + except tkinter.TclError: + pass signal.signal(signal.SIGTERM, quit) signal.signal(signal.SIGINT, quit) - app.mainloop() + try: + app.mainloop() + except SystemExit: + pass From 076ba1f2521684a788dfa110267ac8e7cae8bc78 Mon Sep 17 00:00:00 2001 From: David Date: Sat, 5 Dec 2026 10:53:29 +0100 Subject: [PATCH 7/7] vismach: replace OpenGLTk/glnav with standalone OpenGL 3.3 Core GLX canvas Complete the migration to OpenGL 3.3 Core Profile by removing all dependencies on rs274.OpenGLTk, glnav, and OpenGL.GLU: - Add _GL33Canvas(tkinter.Frame) creating a child X11/GLX window with matching FBConfig visual, 4x MSAA support, NorthWestGravity, and an explicit OpenGL 3.3 Core Profile context via glXCreateContextAttribsARB. - Implement glnav-compatible orbit, trackball rotation_vectors, screen-space pan, zoom, and flicker-free resize handling synced with the OpenGL clear color. - Subclass O from _GL33Canvas, compute projection/view matrices in Python without glGetFloatv, and incrementally upload backplot points via a persistent dynamic VBO. - Scale HUD font size for HiDPI displays so Xft renders anti-aliased glyph atlases at native resolution, and document Hud.set_font(). --- docs/src/gui/vismach.adoc | 2 + lib/python/vismach.py | 509 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 484 insertions(+), 27 deletions(-) diff --git a/docs/src/gui/vismach.adoc b/docs/src/gui/vismach.adoc index ad9ed96e200..c41eedc260c 100644 --- a/docs/src/gui/vismach.adoc +++ b/docs/src/gui/vismach.adoc @@ -361,6 +361,8 @@ model = Collection([base, saddle, head, carousel]) `show_tag_if_same`, `show_tags_in_pin`, and `hide_all` accept both legacy HAL pin names and `"prefix.attr"` / `"{prefix.attr}"` expressions. + `myhud.set_font(font_name="DejaVu Sans Mono", size=15)` selects an + installed Xft font family and pixel size for HUD text rendering. * `tooltip = Capture()` + Think of this as an invisible part that needs to be attached to the tooltip to track the position and orientation of the tool coordinate system. diff --git a/lib/python/vismach.py b/lib/python/vismach.py index 0c2794ea26a..be0d21fd76b 100644 --- a/lib/python/vismach.py +++ b/lib/python/vismach.py @@ -16,17 +16,18 @@ import ctypes import ctypes.util -import sys, rs274.OpenGLTk, signal, hal -import tkinter - -from OpenGL.GL import * +import hal +import inspect +import linuxcnc from math import * -import glnav +import operator import os +import signal import struct -import inspect -import operator -import linuxcnc +import sys +import tkinter + +from OpenGL.GL import * _registered_stats = [] _stats_fresh = False @@ -2458,10 +2459,419 @@ def draw(self): glDisable(GL_BLEND) glEnable(GL_DEPTH_TEST) +# --------------------------------------------------------------------------- +# OpenGL 3.3 Core Profile GLX Context & Camera Widget (Replaces OpenGLTk/glnav) +# --------------------------------------------------------------------------- +_GLX_DOUBLEBUFFER = 5 +_GLX_RED_SIZE = 8 +_GLX_GREEN_SIZE = 9 +_GLX_BLUE_SIZE = 10 +_GLX_DEPTH_SIZE = 12 +_GLX_DRAWABLE_TYPE = 0x8010 +_GLX_RENDER_TYPE = 0x8011 +_GLX_WINDOW_BIT = 0x00000001 +_GLX_RGBA_BIT = 0x00000001 +_GLX_CONTEXT_MAJOR_VERSION_ARB = 0x2091 +_GLX_CONTEXT_MINOR_VERSION_ARB = 0x2092 +_GLX_CONTEXT_PROFILE_MASK_ARB = 0x9126 +_GLX_CONTEXT_CORE_PROFILE_BIT_ARB = 0x00000001 + + +class _XVisualInfo(ctypes.Structure): + _fields_ = [ + ("visual", ctypes.c_void_p), + ("visualid", ctypes.c_ulong), + ("screen", ctypes.c_int), + ("depth", ctypes.c_int), + ("c_class", ctypes.c_int), + ("red_mask", ctypes.c_ulong), + ("green_mask", ctypes.c_ulong), + ("blue_mask", ctypes.c_ulong), + ("colormap_size", ctypes.c_int), + ("bits_per_rgb", ctypes.c_int), + ] + -class O(rs274.OpenGLTk.Opengl): +class _XSetWindowAttributes(ctypes.Structure): + _fields_ = [ + ("background_pixmap", ctypes.c_ulong), + ("background_pixel", ctypes.c_ulong), + ("border_pixmap", ctypes.c_ulong), + ("border_pixel", ctypes.c_ulong), + ("bit_gravity", ctypes.c_int), + ("win_gravity", ctypes.c_int), + ("backing_store", ctypes.c_int), + ("backing_planes", ctypes.c_ulong), + ("backing_pixel", ctypes.c_ulong), + ("save_under", ctypes.c_int), + ("event_mask", ctypes.c_long), + ("do_not_propagate_mask", ctypes.c_long), + ("override_redirect", ctypes.c_int), + ("colormap", ctypes.c_ulong), + ("cursor", ctypes.c_ulong), + ] + + +class _GL33Canvas(tkinter.Frame): + """Tkinter widget hosting a true OpenGL 3.3 Core Profile child X11/GLX window.""" + + def __init__(self, master=None, **kw): + for opt in ("double", "depth", "rgba"): + kw.pop(opt, None) + super().__init__(master, bg="black", **kw) + + self.r_back = self.g_back = self.b_back = 0.0 + self.perspective = True + self.distance = 30.0 + self.near = 0.1 + self.far = 1000.0 + self.fovy = 30.0 + self.lat = 0.0 + self.lon = 0.0 + self.min_lat = -180.0 + self.max_lat = 180.0 + self.xcenter = 0.0 + self.ycenter = 0.0 + self.zcenter = 0.0 + self.rotation_vectors = None + + self._x11 = None + self._glx = None + self._dpy = None + self._ctx = None + self._win_id = None + self._gl_initialized = False + self._redraw_scheduled = False + self._last_bg_hex = None + self._vp_w = 0 + self._vp_h = 0 + self._last_mx = 0 + self._last_my = 0 + + self.bind("", self._on_map) + self.bind("", self._on_expose) + self.bind("", self._on_configure) + self.bind("", self._on_destroy) + + self.bind("", self._on_btn1_press) + self.bind("", self._on_btn1_motion) + self.bind("", self._on_btn2_press) + self.bind("", self._on_btn2_motion) + self.bind("", self._on_btn3_press) + self.bind("", self._on_btn3_motion) + self.bind("", lambda e: self._zoom(0.9)) + self.bind("", lambda e: self._zoom(1.1)) + self.bind("", self._on_mousewheel) + + def _init_glx(self): + if self._ctx is not None or getattr(self, "_initializing_glx", False): + return + if not self.winfo_ismapped(): + return + self._initializing_glx = True + try: + self.update_idletasks() + parent_xid = self.winfo_id() + if not parent_xid: + return + x11_path = ctypes.util.find_library("X11") or "libX11.so.6" + gl_path = ctypes.util.find_library("GL") or "libGL.so.1" + self._x11 = ctypes.CDLL(x11_path) + self._glx = ctypes.CDLL(gl_path) + + self._x11.XOpenDisplay.argtypes = [ctypes.c_char_p] + self._x11.XOpenDisplay.restype = ctypes.c_void_p + self._x11.XDefaultScreen.argtypes = [ctypes.c_void_p] + self._x11.XDefaultScreen.restype = ctypes.c_int + self._x11.XRootWindow.argtypes = [ctypes.c_void_p, ctypes.c_int] + self._x11.XRootWindow.restype = ctypes.c_ulong + self._x11.XCreateColormap.argtypes = [ + ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_int + ] + self._x11.XCreateColormap.restype = ctypes.c_ulong + self._x11.XCreateWindow.argtypes = [ + ctypes.c_void_p, ctypes.c_ulong, + ctypes.c_int, ctypes.c_int, ctypes.c_uint, ctypes.c_uint, + ctypes.c_uint, ctypes.c_int, ctypes.c_uint, ctypes.c_void_p, + ctypes.c_ulong, ctypes.POINTER(_XSetWindowAttributes), + ] + self._x11.XCreateWindow.restype = ctypes.c_ulong + self._x11.XMapWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong] + self._x11.XResizeWindow.argtypes = [ + ctypes.c_void_p, ctypes.c_ulong, ctypes.c_uint, ctypes.c_uint + ] + self._x11.XDestroyWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong] + self._x11.XCloseDisplay.argtypes = [ctypes.c_void_p] + self._x11.XSync.argtypes = [ctypes.c_void_p, ctypes.c_int] + self._x11.XFlush.argtypes = [ctypes.c_void_p] + + self._glx.glXGetProcAddressARB.argtypes = [ctypes.c_char_p] + self._glx.glXGetProcAddressARB.restype = ctypes.c_void_p + self._glx.glXChooseFBConfig.argtypes = [ + ctypes.c_void_p, ctypes.c_int, + ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int), + ] + self._glx.glXChooseFBConfig.restype = ctypes.POINTER(ctypes.c_void_p) + self._glx.glXGetVisualFromFBConfig.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + self._glx.glXGetVisualFromFBConfig.restype = ctypes.POINTER(_XVisualInfo) + self._glx.glXMakeCurrent.argtypes = [ + ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p + ] + self._glx.glXMakeCurrent.restype = ctypes.c_bool + self._glx.glXSwapBuffers.argtypes = [ctypes.c_void_p, ctypes.c_ulong] + self._glx.glXDestroyContext.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + + self._dpy = self._x11.XOpenDisplay(None) + if not self._dpy: + raise RuntimeError("Vismach Error: Could not open X11 display for OpenGL 3.3") + screen = self._x11.XDefaultScreen(self._dpy) + root = self._x11.XRootWindow(self._dpy, screen) + + base_fb = [ + _GLX_DRAWABLE_TYPE, _GLX_WINDOW_BIT, + _GLX_RENDER_TYPE, _GLX_RGBA_BIT, + _GLX_DOUBLEBUFFER, 1, + _GLX_RED_SIZE, 8, + _GLX_GREEN_SIZE, 8, + _GLX_BLUE_SIZE, 8, + _GLX_DEPTH_SIZE, 24, + ] + fb_attribs = (ctypes.c_int * (len(base_fb) + 1))(*base_fb, 0) + msaa_extra = [100000, 1, 100001, 4] + fb_msaa = (ctypes.c_int * (len(base_fb) + len(msaa_extra) + 1))( + *base_fb, *msaa_extra, 0 + ) + n_configs = ctypes.c_int(0) + configs = self._glx.glXChooseFBConfig( + self._dpy, screen, fb_msaa, ctypes.byref(n_configs) + ) + if not configs or n_configs.value == 0: + configs = self._glx.glXChooseFBConfig( + self._dpy, screen, fb_attribs, ctypes.byref(n_configs) + ) + if not configs or n_configs.value == 0: + raise RuntimeError("Vismach Error: No suitable GLX framebuffer config found") + + fb_config = configs[0] + vis = self._glx.glXGetVisualFromFBConfig(self._dpy, fb_config).contents + + cmap = self._x11.XCreateColormap(self._dpy, root, vis.visual, 0) + swa = _XSetWindowAttributes() + swa.colormap = cmap + swa.border_pixel = 0 + swa.bit_gravity = 1 # NorthWestGravity: prevents X11 clearing exposed strips on resize + swa.event_mask = 0x00028000 # StructureNotifyMask | ExposureMask + + w = max(1, self.winfo_width()) + h = max(1, self.winfo_height()) + self._win_id = self._x11.XCreateWindow( + self._dpy, parent_xid, + 0, 0, w, h, 0, + vis.depth, 1, vis.visual, + (1 << 3) | (1 << 4) | (1 << 11) | (1 << 13), # CWBorderPixel | CWBitGravity | CWEventMask | CWColormap + ctypes.byref(swa), + ) + self._x11.XMapWindow(self._dpy, self._win_id) + self._x11.XSync(self._dpy, 0) + + addr = self._glx.glXGetProcAddressARB(b"glXCreateContextAttribsARB") + if addr: + create_ctx = ctypes.CFUNCTYPE( + ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, + ctypes.c_void_p, ctypes.c_bool, ctypes.POINTER(ctypes.c_int), + )(addr) + ctx_attribs = (ctypes.c_int * 7)( + _GLX_CONTEXT_MAJOR_VERSION_ARB, 3, + _GLX_CONTEXT_MINOR_VERSION_ARB, 3, + _GLX_CONTEXT_PROFILE_MASK_ARB, _GLX_CONTEXT_CORE_PROFILE_BIT_ARB, + 0, + ) + self._ctx = create_ctx(self._dpy, fb_config, None, True, ctx_attribs) + + if not self._ctx: + raise RuntimeError("Vismach Error: Failed to create OpenGL 3.3 Core context") + + if not self._glx.glXMakeCurrent(self._dpy, self._win_id, self._ctx): + self._glx.glXDestroyContext(self._dpy, self._ctx) + self._ctx = None + raise RuntimeError("Vismach Error: glXMakeCurrent failed on OpenGL 3.3 context") + self._gl_initialized = False + finally: + self._initializing_glx = False + + def activate(self): + if self._dpy and self._win_id and self._ctx: + self._glx.glXMakeCurrent(self._dpy, self._win_id, self._ctx) + + def swap_buffers(self): + if self._dpy and self._win_id: + self._glx.glXSwapBuffers(self._dpy, self._win_id) + + def _schedule_redraw(self): + if not self._redraw_scheduled: + self._redraw_scheduled = True + self.after_idle(self.tkRedraw) + + def _on_map(self, _event=None): + self._init_glx() + self._schedule_redraw() + + def _on_expose(self, _event=None): + self._schedule_redraw() + + def _on_configure(self, event): + w = max(1, int(event.width)) + h = max(1, int(event.height)) + self._vp_w = w + self._vp_h = h + if self._dpy and self._win_id: + self._x11.XResizeWindow(self._dpy, self._win_id, w, h) + self._x11.XFlush(self._dpy) + if self._ctx is not None: + self.tkRedraw() + return + self._schedule_redraw() + + def _on_destroy(self, _event=None): + if self._dpy: + self._glx.glXMakeCurrent(self._dpy, 0, None) + if self._ctx: + self._glx.glXDestroyContext(self._dpy, self._ctx) + self._ctx = None + if self._win_id: + self._x11.XDestroyWindow(self._dpy, self._win_id) + self._win_id = None + self._x11.XCloseDisplay(self._dpy) + self._dpy = None + + def set_latitudelimits(self, min_lat, max_lat): + self.min_lat = float(min_lat) + self.max_lat = float(max_lat) + + def set_viewangle(self, lat, lon, forcerotate=1): + self.lat = max(self.min_lat, min(self.max_lat, float(lat))) + self.lon = float(lon) % 360.0 + self.tkRedraw() + + def _on_btn1_press(self, event): + self._last_mx, self._last_my = event.x, event.y + + def _on_btn1_motion(self, event): + dx = event.x - self._last_mx + dy = event.y - self._last_my + self._last_mx, self._last_my = event.x, event.y + if event.state & 0x0001: # Shift + Button-1 -> orbit rotate (matches glnav) + self.lon = (self.lon + dx * 0.5) % 360.0 + self.lat = max(self.min_lat, min(self.max_lat, self.lat + dy * 0.5)) + else: # Button-1 drag -> screen-space pan + h = max(1.0, float(self.winfo_height())) + scale = (2.0 * self.distance * tan(radians(self.fovy) * 0.5)) / h + mv = _view_matrix + rx, ry, rz = mv[0], mv[4], mv[8] + ux, uy, uz = mv[1], mv[5], mv[9] + self.xcenter -= (dx * rx - dy * ux) * scale + self.ycenter -= (dx * ry - dy * uy) * scale + self.zcenter -= (dx * rz - dy * uz) * scale + self.tkRedraw() + + def _on_btn2_press(self, event): + self._last_mx, self._last_my = event.x, event.y + + def _on_btn2_motion(self, event): + dx = event.x - self._last_mx + dy = event.y - self._last_my + self._last_mx, self._last_my = event.x, event.y + self.lon = (self.lon + dx * 0.5) % 360.0 + self.lat = max(self.min_lat, min(self.max_lat, self.lat + dy * 0.5)) + self.tkRedraw() + + def _on_btn3_press(self, event): + self._last_mx, self._last_my = event.x, event.y + + def _on_btn3_motion(self, event): + dy = event.y - self._last_my + self._last_mx, self._last_my = event.x, event.y + self._zoom(1.0 + dy * 0.005) + + def _on_mousewheel(self, event): + self._zoom(0.9 if event.delta > 0 else 1.1) + + def _zoom(self, factor): + self.distance = max(1e-3, self.distance * factor) + self.tkRedraw() + + def _compute_camera_matrices(self): + w = max(1, self._vp_w or self.winfo_width()) + h = max(1, self._vp_h or self.winfo_height()) + aspect = float(w) / float(h) + if self.perspective: + proj = _mat4_perspective(self.fovy, aspect, self.near, self.far) + else: + half_h = self.distance * tan(radians(self.fovy) * 0.5) + half_w = half_h * aspect + proj = _mat4_ortho(-half_w, half_w, -half_h, half_h, self.near, self.far) + + _load_matrix(_IDENTITY_4X4) + _translate(0.0, 0.0, -self.distance) + if self.rotation_vectors and len(self.rotation_vectors) >= 2: + v1, v2 = self.rotation_vectors[0], self.rotation_vectors[1] + _rotate(self.lat, v1[0], v1[1], v1[2]) + _rotate(self.lon, v2[0], v2[1], v2[2]) + else: + _rotate(self.lat, 1.0, 0.0, 0.0) + _rotate(self.lon, 0.0, 0.0, 1.0) + _translate(-self.xcenter, -self.ycenter, -self.zcenter) + view = list(_current_matrix()) + _view_matrix[:] = view + return proj, view + + def _sync_tk_bg(self): + # Match Tk frame and root window background to the OpenGL clear color + # so window resizing never flashes mismatched border strips. + r = max(0, min(255, int(round(self.r_back * 255)))) + g = max(0, min(255, int(round(self.g_back * 255)))) + b = max(0, min(255, int(round(self.b_back * 255)))) + bg_hex = "#%02x%02x%02x" % (r, g, b) + if bg_hex != self._last_bg_hex: + self._last_bg_hex = bg_hex + try: + self.configure(bg=bg_hex) + if self.master is not None: + self.master.configure(bg=bg_hex) + except tkinter.TclError: + pass + + def tkRedraw(self, *_args): + self._redraw_scheduled = False + if not self.winfo_exists(): + return + if self._ctx is None: + self._init_glx() + if self._ctx is None: + return + self.activate() + if not self._gl_initialized: + self._gl_initialized = True + self.basic_lighting() + w = max(1, self._vp_w or self.winfo_width()) + h = max(1, self._vp_h or self.winfo_height()) + glViewport(0, 0, w, h) + self._sync_tk_bg() + glClearColor(self.r_back, self.g_back, self.b_back, 1.0) + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) + self.redraw() + self.swap_buffers() + + def basic_lighting(self): + pass + + def redraw(self): + pass + + +class O(_GL33Canvas): def __init__(self, *args, **kw): - rs274.OpenGLTk.Opengl.__init__(self, *args, **kw) + super().__init__(*args, **kw) self.r_back = self.g_back = self.b_back = 0 self.plotdata = [] self.plotlen = 16000 @@ -2471,21 +2881,70 @@ def basic_lighting(self): global _active_prog self.activate() _active_prog = 0 + _gl33.lit = None + _gl33.flat = None + _gl33.hud = None + _gl33.unit_meshes.clear() + _grid_mesh_cache.clear() + _frustum_mesh_cache.clear() + _tri_prism_cache.clear() + _arc_mesh_cache.clear() _gl33.init() glDisable(GL_CULL_FACE) glDepthFunc(GL_LESS) glEnable(GL_DEPTH_TEST) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) + def _draw_backplot(self): + count = len(self.plotdata) + if count < 2 or _gl33.flat is None: + return + if getattr(self, "_bp_vao", None) is None: + self._bp_vao = glGenVertexArrays(1) + self._bp_vbo = glGenBuffers(1) + self._bp_cap = 0 + self._bp_uploaded = 0 + glBindVertexArray(self._bp_vao) + glBindBuffer(GL_ARRAY_BUFFER, self._bp_vbo) + glEnableVertexAttribArray(0) + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 12, ctypes.c_void_p(0)) + glBindBuffer(GL_ARRAY_BUFFER, 0) + glBindVertexArray(0) + + glBindVertexArray(self._bp_vao) + glBindBuffer(GL_ARRAY_BUFFER, self._bp_vbo) + needed_bytes = count * 12 + if needed_bytes > self._bp_cap or count < self._bp_uploaded: + new_cap = max(needed_bytes, self.plotlen * 12) + glBufferData(GL_ARRAY_BUFFER, new_cap, None, GL_DYNAMIC_DRAW) + self._bp_cap = new_cap + self._bp_uploaded = 0 + + if self._bp_uploaded < count: + delta = self.plotdata[self._bp_uploaded:count] + floats = [float(c) for p in delta for c in p] + raw = struct.pack("<%df" % len(floats), *floats) + glBufferSubData(GL_ARRAY_BUFFER, self._bp_uploaded * 12, len(raw), raw) + self._bp_uploaded = count + + mvp = _mat4_mul(_proj_matrix, _current_matrix()) + _gl33.flat.use() + _gl33.flat.set_mat4("u_mvp", mvp) + _gl33.flat.set_vec4("u_color", 1.0, 0.5, 0.5, 1.0) + glLineWidth(2) + glDrawArrays(GL_LINE_STRIP, 0, count) + glLineWidth(1) + glBindBuffer(GL_ARRAY_BUFFER, 0) + glBindVertexArray(0) + def redraw(self, *args): global _stats_fresh, _render_pass, _has_transparent - if self.winfo_width() == 1: + if self.winfo_width() <= 1: return poll_all_stats() - cam_proj = glGetFloatv(GL_PROJECTION_MATRIX) - cam_mv = glGetFloatv(GL_MODELVIEW_MATRIX) - _proj_matrix[:] = [float(v) for row in cam_proj for v in row] - _load_matrix([float(v) for row in cam_mv for v in row]) + proj, view = self._compute_camera_matrices() + _proj_matrix[:] = proj + _load_matrix(view) # Pass 1: Opaque geometry (also updates all Capture() transforms) _render_pass = "opaque" @@ -2523,6 +2982,7 @@ def redraw(self, *args): wz = tx * view2work[0][2] + ty * view2work[1][2] + tz * view2work[2][2] + view2work[3][2] if len(self.plotdata) == self.plotlen: del self.plotdata[:self.plotlen // 10] + self._bp_uploaded = 0 point = [wx, wy, wz] if not self.plotdata or point != self.plotdata[-1]: self.plotdata.append(point) @@ -2534,21 +2994,13 @@ def redraw(self, *args): if hasattr(self.hud, "draw"): self.hud.draw() - if len(self.plotdata) >= 2: - glLineWidth(2) - _gl33.color = [1.0, 0.5, 0.5, 1.0] - line_floats = [] - for p in self.plotdata: - line_floats.extend([float(p[0]), float(p[1]), float(p[2])]) - bp_mesh = _VBOMesh(line_floats, stride_floats=3, mode=GL_LINE_STRIP) - _gl33.draw_flat(bp_mesh) - bp_mesh.delete() - glLineWidth(1) + self._draw_backplot() _pop_matrix() def plotclear(self): del self.plotdata[:self.plotlen] + self._bp_uploaded = 0 old_plotclear = False @@ -2556,10 +3008,11 @@ def plotclear(self): def main(model, tool, work, size=10, hud=0, rotation_vectors=None, lat=0, lon=0, function=None): _check_stats_ready() app = tkinter.Tk() + app.configure(bg="black") import nf hidpi = nf.init_hidpi(app) - # Togl's default 400x400 is in device pixels; scale it for HiDPI. + # Default 400x400 viewport is in device pixels; scale it for HiDPI. t = O(app, double=1, depth=1, width=int(round(400 * hidpi)), height=int(round(400 * hidpi))) # set which axes to rotate around @@ -2582,7 +3035,8 @@ def main(model, tool, work, size=10, hud=0, rotation_vectors=None, lat=0, lon=0, t.hud = HUD t.hud.app = t #HUD needs to know where to draw - + t.hud._font_size = int(round(t.hud._font_size * hidpi)) + # need to capture the world coordinate system world = Capture() @@ -2596,6 +3050,7 @@ def main(model, tool, work, size=10, hud=0, rotation_vectors=None, lat=0, lon=0, t.work2view = work t.pack(fill="both", expand=1) + app.update() _running = True