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/docs/src/gui/vismach.adoc b/docs/src/gui/vismach.adoc index f67066b08a7..c41eedc260c 100644 --- a/docs/src/gui/vismach.adoc +++ b/docs/src/gui/vismach.adoc @@ -70,44 +70,93 @@ 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*. 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, 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(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([prefix,] x, y, z, r)` + + Creates a sphere of radius `r` at `(x, y, z)`. +* `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(x1, x2, r1, r2, a1, a2)` + - Create an arc shape. -* `box = Box(x1, y1, z1, x2, y2, z2)` + +* `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([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(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([prefix,] xw, yw, zw)` + + Creates an `xw` by `yw` by `zw` box centred on the origin. +* `box = BoxCenteredXY([prefix,] xw, yw, zw)` + + Creates a box of width `xw` / `yw` and height `zw`. +* `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([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([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([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 + 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 +180,87 @@ 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, 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], [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], [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], [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], [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], [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. @@ -195,25 +287,26 @@ 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") base = Color([0.5,0.5,0.5,1],[base]) + # mount head on it base = Collection([head, base]) ---- @@ -242,27 +335,45 @@ 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], 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 + 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. -//// + 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. + `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. 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 @@ -274,7 +385,10 @@ Need to play around with this to see how it works. 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` + prefix. == Basic structure of a Vismach script. @@ -295,7 +409,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 @@ -304,4 +418,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 95648aefab6..be0d21fd76b 100644 --- a/lib/python/vismach.py +++ b/lib/python/vismach.py @@ -14,40 +14,767 @@ # 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 ctypes +import ctypes.util +import hal +import inspect +import linuxcnc +from math import * +import operator +import os +import signal +import struct +import sys import tkinter from OpenGL.GL import * -from OpenGL.GLU import * -from math import * -import glnav -import hal + +_registered_stats = [] +_stats_fresh = False +_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) + +# --------------------------------------------------------------------------- +# 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() + + +_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 (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:] + 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() + 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: + 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: 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 @@ -56,1494 +783,2236 @@ def volume(self): def set_volume(self,vol): self.vol = vol; -class Translate(Collection): - def __init__(self, parts, x, y, z): - self.parts = parts - self.where = x, y, z - def apply(self): - glPushMatrix() - glTranslatef(*self.where) +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 unapply(self): - glPopMatrix() +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 Scale(Collection): - def __init__(self, parts, x, y, z): - self.parts = parts - self.scaleby = x, y, z +class ArgsBase(object): + """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) - def apply(self): - glPushMatrix() - glScalef(*self.scaleby) + self.comp = comp + 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] - def unapply(self): - glPopMatrix() + def coords(self): + if self._static_vals is not None: + return self._static_vals + return [fn() for fn in self._resolvers] -class HalTranslate(Collection): - def __init__(self, parts, comp, var, x, y, z): - self.parts = parts - self.where = x, y, z - self.comp = comp - self.var = var + def cross(self, a, b): + return _cross3(a, b) - def apply(self): - x, y, z = self.where - v = self.comp[self.var] - - glPushMatrix() - glTranslatef(x*v, y*v, z*v) + def polar(self, v, stretch=1.0): + return _polar3(v, stretch) - def unapply(self): - glPopMatrix() +# legacy used in: /rotarydelta.py:61:class HexPrismZ(CoordsBase) +CoordsBase = ArgsBase -class HalRotate(Collection): - def __init__(self, parts, comp, var, th, x, y, z): +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 = th, x, y, z - self.comp = comp - self.var = var + 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): - th, x, y, z = self.where - glPushMatrix() - glRotatef(th * self.comp[self.var], x, y, z) + v, x, y, z = self.coords() + _push_matrix() + _translate(x * v, y * v, z * v) def unapply(self): - glPopMatrix() + _pop_matrix() -class Rotate(Collection): - def __init__(self, parts, th, 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.where = th, 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): - th, x, y, z = self.where - glPushMatrix() - glRotatef(th, x, y, z) + x, y, z, sc = self.coords() + _push_matrix() + _translate(sc * x, sc * y, sc * z) def unapply(self): - glPopMatrix() + _pop_matrix() -class HalRotateEuler(Collection): - def __init__(self, parts, comp, th1, th2, th3, order=123): +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.comp = comp - self.order = order - self.th1 = th1 - self.th2 = th2 - self.th3 = th3 + 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): - # 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] - else: - th3 = self.th3 - - 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) + x, y, z, factor = self.coords() + _push_matrix() + _scale(x * factor, y * factor, z * factor) def unapply(self): - glPopMatrix() + _pop_matrix() +HalScale = Scale -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): + +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.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 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): - # make sure we have something to work with first - if len(self.world2view.t) < 4: - glPushMatrix() - 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)] - glPushMatrix() - glTranslatef(px,py,pz) - glRotatef(az-90,0,0,1) - glRotatef(el-90,1,0,0) + 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() + _push_matrix() + _rotate(th * var, x, y, z) def unapply(self): - glPopMatrix() + _pop_matrix() + +HalRotate = Rotate +HalVectorRotate = Rotate -# scales an object by the value of a halpin -class HalScale(Collection): - def __init__(self, parts, comp, x, y, z, var): + +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.comp = comp - self.var = var - self.xyz = 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): - x, y, z = self.xyz - factor = self.comp[self.var] - glPushMatrix() - glScalef(x*factor,y*factor,z*factor) + order, th1, th2, th3 = self.coords() + order = int(order) + _push_matrix() + 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] + _rotate(th1, *a1) + _rotate(th2, *a2) + _rotate(th3, *a3) def unapply(self): - glPopMatrix() + _pop_matrix() + +HalRotateEuler = RotateEuler -# 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): +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 - self.comp = comp - self.const = const - self.var = var - self.scaleby_true = scaleby_true - self.scaleby_false = scaleby_false + 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: + 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): - 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) + const, var, scaleby_true, scaleby_false = self.coords() + _push_matrix() + if const == var: + _scale(scaleby_true, scaleby_true, scaleby_true) else: - glScalef(s_f,s_f,s_f) + _scale(scaleby_false, scaleby_false, scaleby_false) def unapply(self): - glPopMatrix() + _pop_matrix() +HalShow = Show -# 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 - 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 - glPushMatrix() - glTranslatef(sc*xvar, sc*yvar, sc*zvar) +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 unapply(self): - glPopMatrix() +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 + 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) -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 _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]] - def get_values(self): - return self.values + return x1, y1, z1, x2, y2, z2 def apply(self): - th, x, y, z = self.get_values() - glPushMatrix() - glRotatef(th * self.comp[self.var], x, y, z) + 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: + _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 + _push_matrix() + _translate(x1, y1, z1) + _rotate(angle, *axis) def unapply(self): - glPopMatrix() + _pop_matrix() + + +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): + """Sets RGBA color and optional emissive glow on parts.""" + def __init__(self, *args, **kwargs): + 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._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) -class CoordsBase(object): - def __init__(self, *args): - if args and isinstance(args[0], hal.component): - self.comp = args[0] - args = args[1:] - else: - self.comp = None - self._coords = args - self.q = gluNewQuadric() + 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]") - def coords(self): - return list(map(self._coord, self._coords)) + ArgsBase.__init__(self, prefix, c_vals[0], c_vals[1], c_vals[2], c_vals[3], glow) - def _coord(self, v): - if isinstance(v, str): return self.comp[v] - return v + def traverse(self): + global _has_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 + self.apply() + try: + super().traverse() + finally: + self.unapply() -# 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 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 - 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]] + 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))) - # 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) + if a < 1.0: + _has_transparent = True + if _render_pass == "opaque": + return + else: + if _render_pass == "transparent": + return - 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) + _gl33.color = [r, g, b, a] + _gl33.emission = [r * glow, g * glow, b * glow] def unapply(self): - glPopMatrix() - -# 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() - - 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_QUADS) - glNormal3f(n[0],n[1],n[2]) - glVertex3f( s, s, 0) - glVertex3f(-s, s, 0) - glVertex3f(-s, -s, 0) - glVertex3f( s, -s, 0) - glEnd() + _gl33.color = self._prev_color + _gl33.emission = self._prev_emission + + +HalColor = Color + + +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): + """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) + _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_col = [ + xx, xy, xz, 0.0, + yx, yy, yz, 0.0, + zx, zy, zz, 0.0, + ox, oy, oz, 1.0, + ] + _push_matrix() + _mult_matrix(m_col) + + +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): - # 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) + 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): - 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() - - - def draw_vector(self, color): - gluCylinder(self.q, self.r, self.r, 50*self.stretch, 32, 1) - 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]] + _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): - # 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]] - - 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]) + if self._mode == "xy": + (s,) = self.coords() + _push_matrix() + elif 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() + _apply_normal_or_basis((ox, oy, oz), (zx, zy, zz), (xx, xy, xz)) + _gl33.draw_flat(_get_grid_mesh(s)) def unapply(self): - glPopMatrix() + _pop_matrix() +HalGrid = Grid +HalGridFromNormal = Grid +HalGridFromNormalAndDirection = Grid -# 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() - - 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 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): - # 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) + 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() + _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): - glPopMatrix() + _pop_matrix() -# 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() +HalPlaneFromNormal = Plane +HalPlaneFromNormalAndDirection = Plane - 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() - 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) +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): + 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 unapply(self): - glPopMatrix() + def draw(self): + if self._mode == "origin": + stretch, r = self.coords() + _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)) + 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)) -# 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() + 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.0, 0.0, 1.0]) + _rotate(-90, 1, 0, 0) + self.draw_vector(r, stretch, [0.0, 1.0, 0.0, 1.0]) - def draw(self): - s = self.s - self.grid(s) + def unapply(self): + _pop_matrix() + +HalCoordsFromNormal = Coords +HalCoordsFromNormalAndDirection = Coords + + +_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) -# 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) - 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() + 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, 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 + 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 + 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): - 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() + h = abs(p1 - p2) + return pi * h / 3.0 * (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 CylinderZ(_CylinderAxis): + _axis_rotation = None - 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 CylinderX(_CylinderAxis): + _axis_rotation = (90, 0, 1, 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 CylinderY(_CylinderAxis): + _axis_rotation = (-90, 1, 0, 0) - 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): + def __init__(self, *args): + prefix, vals = _split_prefix_and_args(args, (4,)) + super().__init__(prefix, *vals) + 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 - gluSphere(self.q, r, 32, 16) - glPopMatrix() + _push_matrix() + _translate(x, y, z) + _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 - #print "Sphere.volume", vol - return vol + return 4.0 / 3.0 * pi * r * r * r + + +_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: + 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 -# triangular plate in XY plane -# specify the corners Z values for each side class TriangleXY(CoordsBase): + def __init__(self, *args): + prefix, vals = _split_prefix_and_args(args, (8,)) + super().__init__(prefix, *vals) + def draw(self): - 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 - 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() + _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 - #print "TriangleXY.volume = area * thickness)",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): - glPushMatrix() - glRotatef(90,1,0,0) - # create the triangle in XY plane - TriangleXY.draw(self) - # bottom cap - glPopMatrix() + _push_matrix() + _rotate(90, 1, 0, 0) + super().draw() + _pop_matrix() - def volume(self): - vol = TriangleXY.volume(self) - #print " TriangleXZ.volume",vol - 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): - glPushMatrix() - glRotatef(90,0,-1,0) - # create the triangle in XY plane - TriangleXY.draw(self) - # bottom cap - glPopMatrix() + _push_matrix() + _rotate(-90, 0, 1, 0) + super().draw() + _pop_matrix() - def volume(self): - vol = TriangleXY.volume(self) - #print " TriangleYZ.volume",vol - return vol +_arc_mesh_cache = {} -class ArcX(CoordsBase): - def draw(self): - 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 - #print "Arc.volume = angle * area * height",vol, angle, 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) -# six coordinate version - specify each side of the box class Box(CoordsBase): + def __init__(self, *args): + prefix, vals = _split_prefix_and_args(args, (6,)) + super().__init__(prefix, *vals) + def draw(self): 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)) - #print "Box.volume", vol - return vol + return abs((x2 - x1) * (y2 - y1) * (z2 - z1)) + + +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] -# 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): + 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, + ) + -# 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): + 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 (OpenGL 3.3 VBO/VAO).""" + def __init__(self, filename=None, data=None): + self._filename = filename + self._data = data + self._source_stamp = None + self._vbo_mesh = None + self._stale_mesh = None + self._pending_floats = [] + self.reload(filename, data, force=True) + + 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._pending_floats = self._build_floats(self._filename, self._data) + self._source_stamp = new_stamp + if self._vbo_mesh is not None: + self._stale_mesh = self._vbo_mesh + self._vbo_mesh = None + return True + + def draw(self): + 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 _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: + raw_bytes = f.read() + elif isinstance(data, bytes): + raw_bytes = data + + floats = [] + if raw_bytes is not None and len(raw_bytes) >= 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): + return None if i == "" else 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:]] + + +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 class Capture(object): def __init__(self): - self.t = [] + 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: + 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]] + 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 - -# 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 _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 -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 + 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. +_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, optionally a tag or list of tags can be assigned - def add_txt(self, string, tag=None): - self.hud_lines += [[str(string), None, tag]] - - # displays a formatted pin value (can be embedded in a string) - def add_pin(self, string, pin=None, tag=None): - self.hud_lines += [[str(string), pin, tag]] - - # shows all lines with the specified tag if the pin value = val - def show_tag_if_same(self, tag, pin, val=True): - self.show_tags += [[tag, pin, val]] - - # shows all lines with a tag equal to the pin value + offset - def show_tags_in_pin(self, pin, offs=0): - self.show_tags += [[pin, None, offs]] - - # hides the complete hud if the pin value is equal to val - def hide_all(self, pin, val=True): - self.hide_alls += [[pin, 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: - if hal.get_value(a[0]) == 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]) - else: # _show_tag_if_same - if hal.get_value(b[1]) == 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]] - else: # _pin - messages += [c[0].format(hal.get_value(c[1]))] - drawtext = self.strs + messages - - # draw head-up-display - # see axis.py for more font/color configurability - if len(drawtext) == 0: - return + """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 + + def _ensure_gl_resources(self): + if self._tex is not None: + return + + 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)) - 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) - - -class O(rs274.OpenGLTk.Opengl): + 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) + + 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())) + + 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) + +# --------------------------------------------------------------------------- +# 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 _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.q1 = gluNewQuadric() - #self.q2 = gluNewQuadric() - #self.q3 = gluNewQuadric() 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)) + _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) - 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 _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): - if self.winfo_width() == 1: return + global _stats_fresh, _render_pass, _has_transparent + if self.winfo_width() <= 1: + return + poll_all_stats() + proj, view = self._compute_camera_matrices() + _proj_matrix[:] = proj + _load_matrix(view) + + # 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() - # 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 + + # 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) + 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 + 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 ] + 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) - # 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() - # "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) - - #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) + _push_matrix() + _mult_matrix(_rows_to_mat4(view2world)) + _mult_matrix(_rows_to_mat4(self.work2view.t)) - glBegin(GL_LINE_STRIP) - for p in self.plotdata: - glVertex3f(*p) - glEnd() + if hasattr(self.hud, "draw"): + self.hud.draw() - glEnable(GL_LIGHTING) - glColor3f(1,1,1) - glLineWidth(1) - glDisable(GL_BLEND) - glDepthFunc(GL_LESS) + self._draw_backplot() - # back to world again - glPopMatrix() + _pop_matrix() 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): - 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) + self._bp_uploaded = 0 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() + 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 @@ -1566,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() @@ -1580,21 +3050,49 @@ 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 def update(): - global old_plotclear - t.tkRedraw() - new_plotclear = vcomp["plotclear"] - if new_plotclear and not old_plotclear: - t.plotclear() - old_plotclear=new_plotclear - t.after(100, update) + global old_plotclear, _stats_fresh + 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