rushabhcodes/wireless-split-keyboard

Wireless Split Keyboard — custom routed nRF52840 split PCBs with a printable enclosure

Version
0.4.5
License
unset
Stars
0

Use with the tscircuit CLI

tsci is the tscircuit CLI. Install it with npm install -g tscircuit.

tsci clone rushabhcodes/wireless-split-keyboard  # download the package files into ./wireless-split-keyboard
tsci add rushabhcodes/wireless-split-keyboard    # add it to your project as @tsci/rushabhcodes.wireless-split-keyboard

In a cloned or new (tsci init) project: tsci dev starts a local preview, tsci build outputs Circuit JSON, and tsci push publishes to tscircuit.com.

scripts/glb_geometry.py

"""Read exported glTF vertices in the native PCB coordinate system (mm)."""
import json, struct
from pathlib import Path
import numpy as np

class GlbGeometry:
    def __init__(self, path):
        self.raw = Path(path).read_bytes()
        length = struct.unpack_from('<I', self.raw, 12)[0]
        self.document = json.loads(self.raw[20:20 + length])
        self.binary_offset = 28 + length
        self.world = {}
        for node in self.document['scenes'][self.document.get('scene', 0)]['nodes']:
            self._walk(node, np.eye(4))

    def _walk(self, index, parent):
        node = self.document['nodes'][index]
        if 'matrix' in node:
            local = np.array(node['matrix']).reshape((4, 4)).T
        else:
            x, y, z, w = node.get('rotation', [0, 0, 0, 1])
            local = np.eye(4)
            local[:3, :3] = [[1-2*(y*y+z*z), 2*(x*y-z*w), 2*(x*z+y*w)],
                             [2*(x*y+z*w), 1-2*(x*x+z*z), 2*(y*z-x*w)],
                             [2*(x*z-y*w), 2*(y*z+x*w), 1-2*(x*x+y*y)]]
            local[:3, :3] @= np.diag(node.get('scale', [1, 1, 1]))
            local[:3, 3] = node.get('translation', [0, 0, 0])
        self.world[index] = parent @ local
        for child in node.get('children', []):
            self._walk(child, self.world[index])

    def vertices(self, name):
        arrays = []
        for index, node in enumerate(self.document['nodes']):
            if node.get('name') != name or index not in self.world:
                continue
            for primitive in self.document['meshes'][node['mesh']]['primitives']:
                accessor = self.document['accessors'][primitive['attributes']['POSITION']]
                view = self.document['bufferViews'][accessor['bufferView']]
                start = self.binary_offset + view.get('byteOffset', 0) + accessor.get('byteOffset', 0)
                vertices = np.ndarray((accessor['count'], 3), dtype='<f4', buffer=self.raw,
                                      offset=start, strides=(view.get('byteStride', 12), 4))
                vertices = (np.c_[vertices, np.ones(len(vertices))] @ self.world[index].T)[:, :3]
                arrays.append(vertices[:, [0, 2, 1]] * [-1, 1, 1])
        if not arrays:
            raise ValueError(f'Missing native model: {name}')
        return np.concatenate(arrays)

    def mesh(self, name, material_filter=None):
        """Triangle mesh, preserving world placement and disconnected surfaces."""
        import trimesh
        meshes=[]
        for index,node in enumerate(self.document['nodes']):
            if node.get('name')!=name or index not in self.world or 'mesh' not in node:continue
            for primitive in self.document['meshes'][node['mesh']]['primitives']:
                if material_filter is not None and not material_filter(self.document['materials'][primitive['material']]):
                    continue
                def values(accessor_index,columns):
                    a=self.document['accessors'][accessor_index];v=self.document['bufferViews'][a['bufferView']]
                    dtype={5121:'<u1',5123:'<u2',5125:'<u4',5126:'<f4'}[a['componentType']]
                    size=np.dtype(dtype).itemsize
                    return np.ndarray((a['count'],columns),dtype=dtype,buffer=self.raw,
                        offset=self.binary_offset+v.get('byteOffset',0)+a.get('byteOffset',0),
                        strides=(v.get('byteStride',columns*size),size))
                verts=values(primitive['attributes']['POSITION'],3)
                verts=(np.c_[verts,np.ones(len(verts))]@self.world[index].T)[:,:3]
                verts=verts[:,[0,2,1]]*[-1,1,1]
                indices=values(primitive['indices'],1).reshape(-1) if 'indices' in primitive else np.arange(len(verts))
                meshes.append(trimesh.Trimesh(vertices=verts,faces=indices.reshape((-1,3)),process=True))
        if not meshes:raise ValueError(f'Missing native mesh: {name}')
        return trimesh.util.concatenate(meshes)