Initial commit: import VibeMake PCB Studio
CI / typecheck + test + build (push) Has been cancelled

This commit is contained in:
2026-11-03 11:20:08 +08:00
commit 7e01147566
7694 changed files with 6921531 additions and 0 deletions
+34
View File
@@ -0,0 +1,34 @@
# Credentials for the offline content pipelines under tools/ (symbol and
# footprint libraries, demo projects, 3D models). Nothing in the app reads this
# file: the browser app's own settings live in designer/.env.example.
#
# Copy it, fill it in, and it stays out of git:
#
# cp .env.example .env
# pnpm libraries:upload
#
# .env is gitignored. This repository is public, so never put real values in
# this example file, and never commit a filled-in copy.
# --- Cloudflare R2 -----------------------------------------------------------
# These are *R2 API tokens*, an S3-style key pair, not the Cloudflare API token
# that `wrangler login` or the dashboard's "API tokens" page gives you. The
# uploaders talk to R2's S3-compatible endpoint and sign with SigV4, which a
# Cloudflare API token cannot do.
#
# Create one at:
# Cloudflare dashboard -> R2 -> API -> Manage API tokens -> Create API token
# Permission: Object Read & Write, scoped to the bucket below.
#
# The Secret Access Key is shown once, at creation.
# Dashboard -> R2 -> Overview, in the sidebar under "Account details".
R2_ACCOUNT_ID=
# Shown when the token is created.
R2_ACCESS_KEY_ID=
R2_SECRET_ACCESS_KEY=
# The bucket the pipelines write to. Defaults to ziro-3dmodels when unset, which
# is where the symbol, footprint, 3D-model and demo objects all live today.
R2_BUCKET=ziro-3dmodels
+35
View File
@@ -0,0 +1,35 @@
name: CI
on:
push:
branches: [main]
pull_request:
jobs:
checks:
name: typecheck + test + build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
- name: Install
run: pnpm install --frozen-lockfile
- name: Lint & format check
run: pnpm biome ci .
- name: Typecheck
run: pnpm -r typecheck
- name: Test
run: pnpm -r test
- name: Build
run: pnpm -C designer build
+24
View File
@@ -0,0 +1,24 @@
node_modules
dist/
dist-calc/
*.tsbuildinfo
.DS_Store
coverage/
# Local env files (Supabase keys etc.), never commit
.env
.env.local
.env.*.local
# Local KiCad source/symbol clones used only as porting references
kicad-src/
kicad-symbols-src/
kicad-footprints-src/
# R2 upload staging built from kicad-src (never committed)
tools/demos/out/
tools/libraries/out/
# Supabase CLI scratch (project ref, pooler url, gotrue version)
supabase/.temp/
tools/demos/index.json*.bak
+8
View File
@@ -0,0 +1,8 @@
{
"files.exclude": {
"**/node_modules": true
},
"search.exclude": {
"**/node_modules": true
}
}
+118
View File
@@ -0,0 +1,118 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `S3D_CACHE`'s side of `3d-viewer/3d_cache/3d_cache.cpp` that finds model files: `load()`
* resolves a model name through FILENAME_RESOLVER onto the stock 3D directory, here the hosted
* library mounted there and listed by its catalogue, or onto the project's files mounted at its
* directory. No renderer in this file, so the migration and the editors can resolve model paths
* without loading three.js.
*/
import { PATHS } from '@ziroeda/common/paths.js';
import { type wxFileSystemMount, wxMountFileSystem } from '@ziroeda/wx/filefn.js';
/** The model extensions KiCad's 3D plugins register (plugins/3d/vrml, oce). */
export const MODEL_FILE = /\.(wrl|wrz|x3d|step|stp|stpz|step\.gz|stp\.gz|iges|igs)$/i;
/**
* The hosted 3D library's catalogue (tools/models3d/catalog.mjs): library folder -> its model
* files. Null until LoadHosted3DCatalog has fetched it.
*/
let s_hostedCatalog: ReadonlyMap<string, readonly string[]> | null = null;
let s_hostedCatalogLoad: Promise<void> | null = null;
/**
* Fetch the catalogue once. The library is a bucket that cannot be listed from a page, so this
* is the walk of the stock 3D directory KiCad's STEP_CATALOG makes, done when the library was
* built. A failed fetch leaves the library unlisted, as an unreadable directory is upstream.
*/
export function LoadHosted3DCatalog(aUrl: string): Promise<void> {
s_hostedCatalogLoad ??= fetch(aUrl)
.then((r) => (r.ok ? (r.json() as Promise<Record<string, string[]>>) : {}))
.then((json) => {
s_hostedCatalog = new Map(Object.entries(json));
})
.catch(() => {});
return s_hostedCatalogLoad;
}
/** The catalogue, set directly: for a caller that already holds it. */
export function SetHosted3DCatalog(aCatalog: Record<string, readonly string[]> | null): void {
s_hostedCatalog = aCatalog ? new Map(Object.entries(aCatalog)) : null;
s_hostedCatalogLoad = aCatalog ? Promise.resolve() : null;
}
/**
* The hosted 3D library, mounted where the Linux build installs it -
* `${KICAD10_3DMODEL_DIR}` (`PATHS::GetStock3dmodelsPath`) - so a model path
* resolves as it does on that machine. Until the catalogue is loaded any
* STEP-shaped name is taken to exist: a model that is not there fails its
* fetch, as a missing file fails its load upstream. A `.wrl` never exists:
* KiCad 10's packages3D ships STEP only, which is why DIALOG_MIGRATE_3D_MODELS
* exists.
*/
class HOSTED_3D_LIBRARY implements wxFileSystemMount {
FileExists(aRelPath: string): boolean {
if (!MODEL_FILE.test(aRelPath) || /\.(wrl|wrz)$/i.test(aRelPath)) return false;
if (!s_hostedCatalog) return true;
const slash = aRelPath.indexOf('/');
return (
s_hostedCatalog.get(aRelPath.slice(0, slash))?.includes(aRelPath.slice(slash + 1)) ?? false
);
}
DirExists(aRelPath: string): boolean {
if (aRelPath === '') return true;
if (s_hostedCatalog) return s_hostedCatalog.has(aRelPath);
return /^[^/]+\.3dshapes$/i.test(aRelPath);
}
List(aRelDir: string): { name: string; isDir: boolean }[] | null {
if (!s_hostedCatalog) return null;
if (aRelDir === '') return [...s_hostedCatalog.keys()].map((name) => ({ name, isDir: true }));
const models = s_hostedCatalog.get(aRelDir);
return models ? models.map((name) => ({ name, isDir: false })) : null;
}
}
const s_hostedLibrary = new HOSTED_3D_LIBRARY();
let s_libraryMounted = false;
/** The mount itself, so a caller can tell a hosted path from a project one. */
export function HostedLibraryMount(): wxFileSystemMount {
return s_hostedLibrary;
}
export function mountHostedLibrary(): void {
if (s_libraryMounted) return;
wxMountFileSystem(PATHS.GetStock3dmodelsPath(), s_hostedLibrary);
s_libraryMounted = true;
}
/** The open project's files, mounted at its directory (`Prj().GetProjectPath()`). */
export class PROJECT_FILES_MOUNT implements wxFileSystemMount {
constructor(private readonly m_names: ReadonlySet<string>) {}
FileExists(aRelPath: string): boolean {
return this.m_names.has(aRelPath);
}
DirExists(aRelPath: string): boolean {
const dir = `${aRelPath}/`;
for (const n of this.m_names) if (n.startsWith(dir)) return true;
return false;
}
List(aRelDir: string): { name: string; isDir: boolean }[] | null {
const dir = aRelDir === '' ? '' : `${aRelDir}/`;
const seen = new Map<string, boolean>();
for (const n of this.m_names) {
if (!n.startsWith(dir)) continue;
const rest = n.slice(dir.length);
const slash = rest.indexOf('/');
seen.set(slash < 0 ? rest : rest.slice(0, slash), slash >= 0);
}
if (seen.size === 0 && aRelDir !== '') return null;
return [...seen].map(([name, isDir]) => ({ name, isDir }));
}
}
@@ -0,0 +1,173 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `MODEL_SUBSTITUTION` (3d-viewer/3d_cache/model_substitution_helpers.cpp): finding the STEP
* model that replaced a `.wrl` reference KiCad 10's library no longer ships.
*/
import type { FILENAME_RESOLVER } from '@ziroeda/common/filename_resolver.js';
import { CollectFilesLoopSafe } from '@ziroeda/common/gestfich.js';
import { wxDirExists, wxNormalizePath } from '@ziroeda/wx/filefn.js';
/** `stepExtensions()`: the STEP-family extensions, without the dot. */
export const STEP_EXTENSIONS: readonly string[] = [
'step',
'stp',
'stpz',
'step.gz',
'stp.gz',
'iges',
'igs',
];
/** `hasStepExtension`. */
export function HasStepExtension(aPath: string): boolean {
const lower = aPath.toLowerCase();
return STEP_EXTENSIONS.some((ext) => lower.length > ext.length + 1 && lower.endsWith(`.${ext}`));
}
/** `IsWrlExtension`: true iff the name ends in `.wrl` or `.wrz` (case-insensitive). */
export function IsWrlExtension(aFilename: string): boolean {
const ext = aFilename.slice(aFilename.lastIndexOf('.') + 1).toLowerCase();
return aFilename.includes('.') && (ext === 'wrl' || ext === 'wrz');
}
/** `wxFileName( aPath ).GetFullName()`. */
export function FullName(aPath: string): string {
return aPath.slice(Math.max(aPath.lastIndexOf('/'), aPath.lastIndexOf('\\')) + 1);
}
/**
* `normalizeStem`: the name without a known model extension, lower case, with `-` and ` ` read
* as `_`, so "R_0603_1608Metric" and "R-0603-1608Metric" collide.
*/
export function NormalizeStem(aName: string): string {
let stem = aName;
// Strip known extensions (case-insensitive), including doubled-up .gz
// forms that don't round-trip through wxFileName::GetName.
for (const ext of [
'.step.gz',
'.stp.gz',
'.wrl',
'.wrz',
'.step',
'.stp',
'.stpz',
'.iges',
'.igs',
]) {
if (stem.length > ext.length && stem.slice(-ext.length).toLowerCase() === ext) {
stem = stem.slice(0, -ext.length);
break;
}
}
return stem.toLowerCase().replaceAll('-', '_').replaceAll(' ', '_');
}
/**
* `parentDirName`: the basename of the path's directory, e.g.
* "/foo/Resistor_SMD.3dshapes/R_0603.wrl" -> "Resistor_SMD.3dshapes".
*/
export function ParentDirName(aPath: string): string {
const dirs = aPath
.split(/[/\\]/)
.slice(0, -1)
.filter((d) => d !== '');
return dirs[dirs.length - 1] ?? '';
}
/**
* `gatherScanDirs`: the resolver's search paths, the project's `3dshapes/`, and the extra
* directories, each once and only if it exists.
*/
export function GatherScanDirs(
aProjectPath: string,
aResolver: FILENAME_RESOLVER | null,
aExtraDirs: readonly string[] = [],
): string[] {
const result: string[] = [];
const seen = new Set<string>();
const addDir = (aDir: string): void => {
if (aDir === '') return;
const norm = wxNormalizePath(aDir).replace(/\/+$/, '');
if (seen.has(norm.toLowerCase())) return;
seen.add(norm.toLowerCase());
if (wxDirExists(norm)) result.push(norm);
};
for (const sp of aResolver?.GetPaths() ?? []) addDir(sp.m_Pathexp);
if (aProjectPath !== '') addDir(`${aProjectPath.replace(/\/+$/, '')}/3dshapes`);
for (const dir of aExtraDirs) addDir(dir);
return result;
}
/** `MODEL_SUBSTITUTION::STEP_CATALOG`. */
export class STEP_CATALOG {
/** Normalised stem -> list of absolute STEP-family paths sharing that stem. */
private m_byStem = new Map<string, string[]>();
/**
* `Build`: every STEP-family file under the resolver's search paths, the project's
* `3dshapes/`, and the extra search directories, indexed by normalised stem.
*/
Build(
aProjectPath: string,
aResolver: FILENAME_RESOLVER | null,
aExtraDirs: readonly string[] = [],
): void {
this.m_byStem.clear();
for (const dir of GatherScanDirs(aProjectPath, aResolver, aExtraDirs)) {
const files: string[] = [];
CollectFilesLoopSafe(dir, files);
for (const file of files) {
if (!HasStepExtension(file)) continue;
const stem = NormalizeStem(FullName(file));
if (stem === '') continue;
const list = this.m_byStem.get(stem);
if (list) list.push(file);
else this.m_byStem.set(stem, [file]);
}
}
}
/**
* `FindMatchFor`: the best STEP replacement for a missing `.wrl`, preferring one in a folder
* of the same name; empty when there is none or the name is not a `.wrl`.
*/
FindMatchFor(aMissingWrl: string): string {
if (!IsWrlExtension(aMissingWrl)) return '';
const stem = NormalizeStem(FullName(aMissingWrl));
if (stem === '') return '';
const list = this.m_byStem.get(stem);
if (!list || list.length === 0) return '';
const wrlParent = ParentDirName(aMissingWrl);
if (wrlParent !== '') {
for (const candidate of list) {
if (ParentDirName(candidate).toLowerCase() === wrlParent.toLowerCase()) return candidate;
}
}
return list[0]!;
}
Empty(): boolean {
return this.m_byStem.size === 0;
}
}
+60
View File
@@ -0,0 +1,60 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/** `3d-viewer/3d_cache/sg/ifsg_api.cpp`: the S3D:: functions the exporters call. */
import { SGVECTOR, type SGPOINT } from './sg_base.js';
import { degenerate } from './sg_helpers.js';
import type { SGNODE } from './sg_node.js';
import { SGTYPES } from './sg_types.js';
/**
* `S3D::WriteVRML( filename, overwrite, aTopNode, reuse, renameNodes )`: the file's text, or
* null when aTopNode is not a transform. The caller writes it.
*/
export function WriteVRML(
aTopNode: SGNODE | null,
reuse: boolean,
renameNodes: boolean,
): string | null {
if (!aTopNode || aTopNode.GetNodeType() !== SGTYPES.SGTYPE_TRANSFORM) return null;
const op: string[] = ['#VRML V2.0 utf8\n'];
if (renameNodes) {
aTopNode.ResetNodeIndex();
aTopNode.ReNameNodes();
}
aTopNode.WriteVRML(op, reuse);
return op.join('');
}
export function GetSGNodeParent(aNode: SGNODE | null): SGNODE | null {
return aNode?.GetParent() ?? null;
}
/**
* `S3D::CalcTriNorm`: the triangle's normal; (0, 0, 1) for a degenerate one. glm::normalize's
* result is discarded upstream, so the SGVECTOR constructor is what normalises.
*/
export function CalcTriNorm(p1: SGPOINT, p2: SGPOINT, p3: SGPOINT): SGVECTOR {
const pts: [number, number, number][] = [
[p1.x, p1.y, p1.z],
[p2.x, p2.y, p2.z],
[p3.x, p3.y, p3.z],
];
// degenerate points are given a default 0, 0, 1 normal
if (degenerate(pts)) return new SGVECTOR(0.0, 0.0, 1.0);
// normal
const a = [pts[1]![0] - pts[0]![0], pts[1]![1] - pts[0]![1], pts[1]![2] - pts[0]![2]] as const;
const b = [pts[2]![0] - pts[0]![0], pts[2]![1] - pts[0]![1], pts[2]![2] - pts[0]![2]] as const;
return new SGVECTOR(
a[1] * b[2] - b[1] * a[2],
a[2] * b[0] - b[2] * a[0],
a[0] * b[1] - b[0] * a[1],
);
}
+59
View File
@@ -0,0 +1,59 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/** `3d-viewer/3d_cache/sg/ifsg_appearance.cpp`: IFSG_APPEARANCE, a Material. */
import { IFSG_NODE, type IFSG_PARENT } from './ifsg_node.js';
import { SGAPPEARANCE } from './sg_appearance.js';
export class IFSG_APPEARANCE extends IFSG_NODE {
constructor(aParent: IFSG_PARENT | false = null) {
super();
if (aParent !== false) this.NewNode(aParent);
}
NewNode(aParent: IFSG_PARENT): boolean {
this.m_node = new SGAPPEARANCE(IFSG_NODE.raw(aParent));
return true;
}
private node(): SGAPPEARANCE {
return this.m_node as SGAPPEARANCE;
}
SetEmissive(aRVal: number, aGVal: number, aBVal: number): boolean {
return this.node().SetEmissive(aRVal, aGVal, aBVal);
}
SetDiffuse(aRVal: number, aGVal: number, aBVal: number): boolean {
return this.node().SetDiffuse(aRVal, aGVal, aBVal);
}
SetSpecular(aRVal: number, aGVal: number, aBVal: number): boolean {
return this.node().SetSpecular(aRVal, aGVal, aBVal);
}
SetAmbient(aRVal: number, aGVal: number, aBVal: number): boolean {
return this.node().SetAmbient(aRVal, aGVal, aBVal);
}
/** Refused outside [0, 1]; stored as a C float. */
SetShininess(aShininess: number): boolean {
const v = Math.fround(aShininess);
if (v < 0 || v > 1.0) return false;
this.node().shininess = v;
return true;
}
/** Refused outside [0, 1]; stored as a C float. */
SetTransparency(aTransparency: number): boolean {
const v = Math.fround(aTransparency);
if (v < 0 || v > 1.0) return false;
this.node().transparency = v;
return true;
}
}
+33
View File
@@ -0,0 +1,33 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/** `3d-viewer/3d_cache/sg/ifsg_coordindex.cpp`: IFSG_COORDINDEX, a coordIndex node. */
import { IFSG_NODE, type IFSG_PARENT } from './ifsg_node.js';
import { SGCOORDINDEX } from './sg_coordindex.js';
export class IFSG_COORDINDEX extends IFSG_NODE {
constructor(aParent: IFSG_PARENT | false = null) {
super();
if (aParent !== false) this.NewNode(aParent);
}
NewNode(aParent: IFSG_PARENT): boolean {
this.m_node = new SGCOORDINDEX(IFSG_NODE.raw(aParent));
return true;
}
private node(): SGCOORDINDEX {
return this.m_node as SGCOORDINDEX;
}
SetIndices(aIndexList: readonly number[]): boolean {
this.node().SetIndices(aIndexList);
return true;
}
AddIndex(aIndex: number): boolean {
this.node().AddIndex(aIndex);
return true;
}
}
+34
View File
@@ -0,0 +1,34 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/** `3d-viewer/3d_cache/sg/ifsg_coords.cpp`: IFSG_COORDS, a Coordinate node. */
import { IFSG_NODE, type IFSG_PARENT } from './ifsg_node.js';
import type { SGPOINT } from './sg_base.js';
import { SGCOORDS } from './sg_coords.js';
export class IFSG_COORDS extends IFSG_NODE {
constructor(aParent: IFSG_PARENT | false = null) {
super();
if (aParent !== false) this.NewNode(aParent);
}
NewNode(aParent: IFSG_PARENT): boolean {
this.m_node = new SGCOORDS(IFSG_NODE.raw(aParent));
return true;
}
private node(): SGCOORDS {
return this.m_node as SGCOORDS;
}
SetCoordsList(aCoordsList: readonly SGPOINT[]): boolean {
this.node().SetCoordsList(aCoordsList);
return true;
}
AddCoord(aPoint: SGPOINT): boolean {
this.node().AddCoord(aPoint);
return true;
}
}
+23
View File
@@ -0,0 +1,23 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/** `3d-viewer/3d_cache/sg/ifsg_faceset.cpp`: IFSG_FACESET, an IndexedFaceSet node. */
import { IFSG_NODE, type IFSG_PARENT } from './ifsg_node.js';
import { SGFACESET } from './sg_faceset.js';
export class IFSG_FACESET extends IFSG_NODE {
constructor(aParent: IFSG_PARENT | false = null) {
super();
if (aParent !== false) this.NewNode(aParent);
}
NewNode(aParent: IFSG_PARENT): boolean {
this.m_node = new SGFACESET(IFSG_NODE.raw(aParent));
return true;
}
private node(): SGFACESET {
return this.m_node as SGFACESET;
}
}
+40
View File
@@ -0,0 +1,40 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `3d-viewer/3d_cache/sg/ifsg_node.cpp`: IFSG_NODE, the wrapper a plugin or exporter holds; each
* subclass makes its kind of node under a parent (NewNode) and forwards to it.
*/
import type { SGNODE } from './sg_node.js';
export type IFSG_PARENT = SGNODE | IFSG_NODE | null;
export abstract class IFSG_NODE {
protected m_node: SGNODE | null = null;
protected static raw(aParent: IFSG_PARENT): SGNODE | null {
return aParent instanceof IFSG_NODE ? aParent.GetRawPtr() : aParent;
}
GetRawPtr(): SGNODE | null {
return this.m_node;
}
/** `Attach( aNode )`. */
Attach(aNode: SGNODE | null): boolean {
this.m_node = aNode;
return true;
}
AddRefNode(aNode: SGNODE | IFSG_NODE | null): boolean {
const n = IFSG_NODE.raw(aNode);
return !!(this.m_node && n && this.m_node.AddRefNode(n));
}
AddChildNode(aNode: SGNODE | IFSG_NODE | null): boolean {
const n = IFSG_NODE.raw(aNode);
return !!(this.m_node && n && this.m_node.AddChildNode(n));
}
abstract NewNode(aParent: IFSG_PARENT): boolean;
}
+29
View File
@@ -0,0 +1,29 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/** `3d-viewer/3d_cache/sg/ifsg_normals.cpp`: IFSG_NORMALS, a Normal node. */
import { IFSG_NODE, type IFSG_PARENT } from './ifsg_node.js';
import type { SGVECTOR } from './sg_base.js';
import { SGNORMALS } from './sg_normals.js';
export class IFSG_NORMALS extends IFSG_NODE {
constructor(aParent: IFSG_PARENT | false = null) {
super();
if (aParent !== false) this.NewNode(aParent);
}
NewNode(aParent: IFSG_PARENT): boolean {
this.m_node = new SGNORMALS(IFSG_NODE.raw(aParent));
return true;
}
private node(): SGNORMALS {
return this.m_node as SGNORMALS;
}
AddNormal(aX: number | SGVECTOR, aY?: number, aZ?: number): boolean {
this.node().AddNormal(aX, aY, aZ);
return true;
}
}
+23
View File
@@ -0,0 +1,23 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/** `3d-viewer/3d_cache/sg/ifsg_shape.cpp`: IFSG_SHAPE, a Shape node. */
import { IFSG_NODE, type IFSG_PARENT } from './ifsg_node.js';
import { SGSHAPE } from './sg_shape.js';
export class IFSG_SHAPE extends IFSG_NODE {
constructor(aParent: IFSG_PARENT | false = null) {
super();
if (aParent !== false) this.NewNode(aParent);
}
NewNode(aParent: IFSG_PARENT): boolean {
this.m_node = new SGSHAPE(IFSG_NODE.raw(aParent));
return true;
}
private node(): SGSHAPE {
return this.m_node as SGSHAPE;
}
}
+48
View File
@@ -0,0 +1,48 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/** `3d-viewer/3d_cache/sg/ifsg_transform.cpp`: IFSG_TRANSFORM, a Transform node. */
import { IFSG_NODE, type IFSG_PARENT } from './ifsg_node.js';
import { SGPOINT, type SGVECTOR } from './sg_base.js';
import { SCENEGRAPH } from './scenegraph.js';
export class IFSG_TRANSFORM extends IFSG_NODE {
constructor(aParent: IFSG_PARENT | false = null) {
super();
if (aParent !== false) this.NewNode(aParent);
}
NewNode(aParent: IFSG_PARENT): boolean {
this.m_node = new SCENEGRAPH(IFSG_NODE.raw(aParent));
return true;
}
private node(): SCENEGRAPH {
return this.m_node as SCENEGRAPH;
}
SetRotation(aRotationAxis: SGVECTOR, aAngle: number): boolean {
this.node().rotation_axis.SetVector(aRotationAxis);
this.node().rotation_angle = aAngle;
return true;
}
/** `SetScale( const SGPOINT& )` / `SetScale( double )`, which refuses a scale within 1e-8 of 0. */
SetScale(aScale: SGPOINT | number): boolean {
if (typeof aScale === 'number') {
if (aScale < 1e-8 && aScale > -1e-8) return false;
this.node().scale = new SGPOINT(aScale, aScale, aScale);
return true;
}
this.node().scale = new SGPOINT(aScale.x, aScale.y, aScale.z);
return true;
}
SetTranslation(aTranslation: SGPOINT): boolean {
this.node().translation = new SGPOINT(aTranslation.x, aTranslation.y, aTranslation.z);
return true;
}
}
+136
View File
@@ -0,0 +1,136 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/** `3d-viewer/3d_cache/sg/scenegraph.{h,cpp}`: SCENEGRAPH, the Transform node. */
import { SGPOINT, SGVECTOR } from './sg_base.js';
import { FormatOrientation, FormatPoint } from './sg_helpers.js';
import { SGNODE } from './sg_node.js';
import type { SGSHAPE } from './sg_shape.js';
import { SGTYPES } from './sg_types.js';
export class SCENEGRAPH extends SGNODE {
// note: order of transformation is Translate, Rotate, Offset
center = new SGPOINT();
translation = new SGPOINT();
rotation_axis = new SGVECTOR();
rotation_angle = 0.0; // radians
scale = new SGPOINT(1.0, 1.0, 1.0);
scale_axis = new SGVECTOR();
scale_angle = 0.0; // radians
private m_Transforms: SCENEGRAPH[] = [];
private m_Shape: SGSHAPE[] = [];
private m_RTransforms: SCENEGRAPH[] = [];
private m_RShape: SGSHAPE[] = [];
constructor(aParent: SGNODE | null) {
super(aParent);
this.m_SGtype = SGTYPES.SGTYPE_TRANSFORM;
if (aParent !== null && aParent.GetNodeType() !== SGTYPES.SGTYPE_TRANSFORM)
this.m_Parent = null;
else if (aParent !== null) aParent.AddChildNode(this);
}
private addNode(aNode: SGNODE, isChild: boolean): boolean {
const t = aNode.GetNodeType();
const [owned, refs]: [SGNODE[], SGNODE[]] | [null, null] =
t === SGTYPES.SGTYPE_TRANSFORM
? [this.m_Transforms, this.m_RTransforms]
: t === SGTYPES.SGTYPE_SHAPE
? [this.m_Shape, this.m_RShape]
: [null, null];
if (!owned) return false;
if (owned.includes(aNode) || refs!.includes(aNode)) return true;
if (isChild) {
const ppn = aNode.GetParent();
if (ppn !== null && ppn !== this) return false;
owned.push(aNode);
aNode.SetParent(this);
} else {
refs!.push(aNode);
}
return true;
}
AddRefNode(aNode: SGNODE): boolean {
return this.addNode(aNode, false);
}
AddChildNode(aNode: SGNODE): boolean {
return this.addNode(aNode, true);
}
ReNameNodes(): void {
this.m_written = false;
// rename this node
this.m_Name = '';
this.GetName();
// rename all shapes
for (const s of this.m_Shape) s.ReNameNodes();
// rename all transforms
for (const t of this.m_Transforms) t.ReNameNodes();
}
WriteVRML(aFile: string[], aReuseFlag: boolean): boolean {
if (
this.m_Transforms.length === 0 &&
this.m_RTransforms.length === 0 &&
this.m_Shape.length === 0 &&
this.m_RShape.length === 0
) {
return false;
}
if (aReuseFlag) {
if (!this.m_written) {
aFile.push(`DEF ${this.GetName()} Transform {\n`);
this.m_written = true;
} else {
aFile.push(`USE ${this.GetName()}\n`);
return true;
}
} else {
aFile.push(' Transform {\n');
}
// convert center to 1VRML unit = 0.1 inch
let pt = new SGPOINT(this.center.x / 2.54, this.center.y / 2.54, this.center.z / 2.54);
aFile.push(` center ${FormatPoint(pt)}\n`);
aFile.push(` rotation ${FormatOrientation(this.rotation_axis, this.rotation_angle)}\n`);
aFile.push(` scale ${FormatPoint(this.scale)}\n`);
aFile.push(` scaleOrientation ${FormatOrientation(this.scale_axis, this.scale_angle)}\n`);
// convert translation to 1VRML unit = 0.1 inch
pt = new SGPOINT(
this.translation.x / 2.54,
this.translation.y / 2.54,
this.translation.z / 2.54,
);
aFile.push(` translation ${FormatPoint(pt)}\n`);
aFile.push(' children [\n');
for (const t of this.m_Transforms) t.WriteVRML(aFile, aReuseFlag);
for (const t of this.m_RTransforms) t.WriteVRML(aFile, aReuseFlag);
for (const s of this.m_Shape) s.WriteVRML(aFile, aReuseFlag);
for (const s of this.m_RShape) s.WriteVRML(aFile, aReuseFlag);
aFile.push('] }\n');
return true;
}
}
+109
View File
@@ -0,0 +1,109 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `3d-viewer/3d_cache/sg/sg_appearance.{h,cpp}`: SGAPPEARANCE, a VRML Material. Every channel is a
* C float, and the ambient intensity is computed in float, so the arithmetic is fround'ed where
* the C++ narrows.
*/
import { SGCOLOR } from './sg_base.js';
import { FormatFloat } from './sg_helpers.js';
import { SGNODE } from './sg_node.js';
import { SGTYPES } from './sg_types.js';
const f32 = Math.fround;
export class SGAPPEARANCE extends SGNODE {
shininess = f32(0.2); // default 0.2
transparency = 0.0; // default 0.0
ambient = new SGCOLOR(0.05317, 0.17879, 0.01804); // default 0.05317 0.17879 0.01804
diffuse = new SGCOLOR(0.8, 0.8, 0.8); // default 0.8 0.8 0.8
emissive = new SGCOLOR(); // default 0.0 0.0 0.0
specular = new SGCOLOR(); // default 0.0 0.0 0.0
constructor(aParent: SGNODE | null) {
super(aParent);
this.m_SGtype = SGTYPES.SGTYPE_APPEARANCE;
if (aParent !== null && aParent.GetNodeType() !== SGTYPES.SGTYPE_SHAPE) this.m_Parent = null;
else if (aParent !== null) aParent.AddChildNode(this);
}
SetEmissive(aRVal: number, aGVal: number, aBVal: number): boolean {
return this.emissive.SetColor(aRVal, aGVal, aBVal);
}
SetDiffuse(aRVal: number, aGVal: number, aBVal: number): boolean {
return this.diffuse.SetColor(aRVal, aGVal, aBVal);
}
SetSpecular(aRVal: number, aGVal: number, aBVal: number): boolean {
return this.specular.SetColor(aRVal, aGVal, aBVal);
}
SetAmbient(aRVal: number, aGVal: number, aBVal: number): boolean {
return this.ambient.SetColor(aRVal, aGVal, aBVal);
}
AddRefNode(_aNode: SGNODE): boolean {
return false;
}
AddChildNode(_aNode: SGNODE): boolean {
return false;
}
ReNameNodes(): void {
this.m_written = false;
// rename this node
this.m_Name = '';
this.GetName();
}
WriteVRML(aFile: string[], aReuseFlag: boolean): boolean {
if (aReuseFlag) {
if (!this.m_written) {
aFile.push(` appearance DEF ${this.GetName()} Appearance {\n`);
this.m_written = true;
} else {
aFile.push(` appearance USE ${this.GetName()}\n`);
return true;
}
} else {
aFile.push(' appearance Appearance {\n');
}
aFile.push(' material Material {\n');
let [ambr, ambg, ambb] = this.ambient.GetColor();
let amb = f32(0.212671 * ambr + 0.71516 * ambg + 0.072169 * ambb);
[ambr, ambg, ambb] = this.diffuse.GetColor();
let den = f32(0.212671 * ambr + 0.71516 * ambg + 0.072169 * ambb);
if (den < f32(0.004)) den = f32(0.004);
amb = f32(amb / den);
if (amb > 1.0) amb = 1.0;
aFile.push(` ambientIntensity ${FormatFloat(amb)}\n`);
let [red, green, blue] = this.diffuse.GetColor();
aFile.push(` diffuseColor ${FormatFloat(red)} ${FormatFloat(green)} ${FormatFloat(blue)}\n`);
[red, green, blue] = this.emissive.GetColor();
aFile.push(` emissiveColor ${FormatFloat(red)} ${FormatFloat(green)} ${FormatFloat(blue)}\n`);
aFile.push(` shininess ${FormatFloat(this.shininess)}\n`);
[red, green, blue] = this.specular.GetColor();
aFile.push(` specularColor ${FormatFloat(red)} ${FormatFloat(green)} ${FormatFloat(blue)}\n`);
aFile.push(` transparency ${FormatFloat(this.transparency)}\n`);
aFile.push('} }\n');
return true;
}
}
+110
View File
@@ -0,0 +1,110 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `include/plugins/3dapi/sg_base.h` + `3d-viewer/3d_cache/sg/sg_base.cpp`: SGCOLOR (three C
* floats in [0, 1]), SGPOINT and SGVECTOR (always normalised).
*/
export class SGCOLOR {
red = 0.0;
green = 0.0;
blue = 0.0;
constructor(aRVal?: number, aGVal?: number, aBVal?: number) {
if (aRVal !== undefined) this.SetColor(aRVal, aGVal!, aBVal!);
}
GetColor(): [number, number, number] {
return [this.red, this.green, this.blue];
}
/** `SetColor( float, float, float )`: refused (and left as it was) outside [0, 1]. */
SetColor(aRedVal: number, aGreenVal: number, aBlueVal: number): boolean {
const r = Math.fround(aRedVal);
const g = Math.fround(aGreenVal);
const b = Math.fround(aBlueVal);
if (!this.checkRange(r, g, b)) return false;
this.red = r;
this.green = g;
this.blue = b;
return true;
}
private checkRange(aRedVal: number, aGreenVal: number, aBlueVal: number): boolean {
let ok = true;
if (aRedVal < 0.0 || aRedVal > 1.0) ok = false;
if (aGreenVal < 0.0 || aGreenVal > 1.0) ok = false;
if (aBlueVal < 0.0 || aBlueVal > 1.0) ok = false;
return ok;
}
}
export class SGPOINT {
constructor(
public x = 0.0,
public y = 0.0,
public z = 0.0,
) {}
GetPoint(): [number, number, number] {
return [this.x, this.y, this.z];
}
SetPoint(aXPos: number, aYPos: number, aZPos: number): void {
this.x = aXPos;
this.y = aYPos;
this.z = aZPos;
}
}
export class SGVECTOR {
private vx = 0.0;
private vy = 0.0;
private vz = 1.0;
constructor(aXVal?: number, aYVal?: number, aZVal?: number) {
if (aXVal !== undefined) this.SetVector(aXVal, aYVal!, aZVal!);
}
GetVector(): [number, number, number] {
return [this.vx, this.vy, this.vz];
}
SetVector(aXVal: number | SGVECTOR, aYVal?: number, aZVal?: number): void {
if (aXVal instanceof SGVECTOR) {
[this.vx, this.vy, this.vz] = aXVal.GetVector();
return;
}
this.vx = aXVal;
this.vy = aYVal!;
this.vz = aZVal!;
this.normalize();
}
private normalize(): void {
const dx = this.vx * this.vx;
const dy = this.vy * this.vy;
const dz = this.vz * this.vz;
const dv2 = Math.sqrt(dx + dy + dz);
if (dx + dy + dz < 1e-8) {
// use the default; the numbers are too small to be believable
this.vx = 0.0;
this.vy = 0.0;
this.vz = 1.0;
return;
}
this.vx /= dv2;
this.vy /= dv2;
this.vz /= dv2;
}
}
+17
View File
@@ -0,0 +1,17 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/** `3d-viewer/3d_cache/sg/sg_coordindex.{h,cpp}`: SGCOORDINDEX, a face set's triangle list. */
import type { SGNODE } from './sg_node.js';
import { SGINDEX } from './sg_index.js';
import { SGTYPES } from './sg_types.js';
export class SGCOORDINDEX extends SGINDEX {
constructor(aParent: SGNODE | null) {
super(aParent);
this.m_SGtype = SGTYPES.SGTYPE_COORDINDEX;
if (aParent !== null && aParent.GetNodeType() !== SGTYPES.SGTYPE_FACESET) this.m_Parent = null;
else if (aParent !== null) aParent.AddChildNode(this);
}
}
+85
View File
@@ -0,0 +1,85 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/** `3d-viewer/3d_cache/sg/sg_coords.{h,cpp}`: SGCOORDS, a Coordinate list. */
import { SGPOINT } from './sg_base.js';
import { FormatPoint } from './sg_helpers.js';
import { SGNODE } from './sg_node.js';
import { SGTYPES } from './sg_types.js';
export class SGCOORDS extends SGNODE {
coords: SGPOINT[] = [];
constructor(aParent: SGNODE | null) {
super(aParent);
this.m_SGtype = SGTYPES.SGTYPE_COORDS;
if (aParent !== null && aParent.GetNodeType() !== SGTYPES.SGTYPE_FACESET) this.m_Parent = null;
else if (aParent !== null) aParent.AddChildNode(this);
}
SetCoordsList(aCoordsList: readonly SGPOINT[]): void {
this.coords = [...aCoordsList];
}
AddCoord(aPoint: SGPOINT): void {
this.coords.push(new SGPOINT(aPoint.x, aPoint.y, aPoint.z));
}
AddRefNode(_aNode: SGNODE): boolean {
return false;
}
AddChildNode(_aNode: SGNODE): boolean {
return false;
}
ReNameNodes(): void {
this.m_written = false;
// rename this node
this.m_Name = '';
this.GetName();
}
WriteVRML(aFile: string[], aReuseFlag: boolean): boolean {
if (this.coords.length === 0) return false;
if (aReuseFlag) {
if (!this.m_written) {
aFile.push(` coord DEF ${this.GetName()} Coordinate { point [\n `);
this.m_written = true;
} else {
aFile.push(` coord USE ${this.GetName()}\n`);
return true;
}
} else {
aFile.push(' coord Coordinate { point [\n ');
}
const n = this.coords.length;
let nline = false;
for (let i = 0; i < n; ) {
// ensure VRML output has 1U = 0.1 inch as per legacy kicad expectations
const c = this.coords[i]!;
aFile.push(FormatPoint(new SGPOINT(c.x / 2.54, c.y / 2.54, c.z / 2.54)));
++i;
if (i < n) {
aFile.push(',');
if (nline) {
aFile.push('\n ');
nline = false;
} else {
nline = true;
}
}
}
aFile.push('] }\n');
return true;
}
}
+122
View File
@@ -0,0 +1,122 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/** `3d-viewer/3d_cache/sg/sg_faceset.{h,cpp}`: SGFACESET, an IndexedFaceSet. */
import { SGNODE } from './sg_node.js';
import { SGTYPES } from './sg_types.js';
export class SGFACESET extends SGNODE {
// owned objects
m_Colors: SGNODE | null = null;
m_Coords: SGNODE | null = null;
m_CoordIndices: SGNODE | null = null;
m_Normals: SGNODE | null = null;
// referenced objects
m_RColors: SGNODE | null = null;
m_RCoords: SGNODE | null = null;
m_RNormals: SGNODE | null = null;
constructor(aParent: SGNODE | null) {
super(aParent);
this.m_SGtype = SGTYPES.SGTYPE_FACESET;
if (aParent !== null && aParent.GetNodeType() !== SGTYPES.SGTYPE_SHAPE) this.m_Parent = null;
else if (aParent !== null) aParent.AddChildNode(this);
}
private addNode(aNode: SGNODE, isChild: boolean): boolean {
const slot = (
own: 'm_Colors' | 'm_Coords' | 'm_Normals',
ref: 'm_RColors' | 'm_RCoords' | 'm_RNormals',
): boolean => {
if (this[own] || this[ref]) return aNode === this[own] || aNode === this[ref];
if (isChild) {
this[own] = aNode;
aNode.SetParent(this);
} else {
this[ref] = aNode;
}
return true;
};
switch (aNode.GetNodeType()) {
case SGTYPES.SGTYPE_COLORS:
return slot('m_Colors', 'm_RColors');
case SGTYPES.SGTYPE_COORDS:
return slot('m_Coords', 'm_RCoords');
case SGTYPES.SGTYPE_NORMALS:
return slot('m_Normals', 'm_RNormals');
case SGTYPES.SGTYPE_COORDINDEX:
if (this.m_CoordIndices) return aNode === this.m_CoordIndices;
// a coordinate index is only ever owned
if (!isChild) return false;
this.m_CoordIndices = aNode;
aNode.SetParent(this);
return true;
default:
return false;
}
}
AddRefNode(aNode: SGNODE): boolean {
return this.addNode(aNode, false);
}
AddChildNode(aNode: SGNODE): boolean {
return this.addNode(aNode, true);
}
ReNameNodes(): void {
this.m_written = false;
// rename this node
this.m_Name = '';
this.GetName();
// rename all Colors and Indices
this.m_Colors?.ReNameNodes();
// rename all Coordinates and Indices
this.m_Coords?.ReNameNodes();
this.m_CoordIndices?.ReNameNodes();
// rename all Normals and Indices
this.m_Normals?.ReNameNodes();
}
WriteVRML(aFile: string[], aReuseFlag: boolean): boolean {
if ((this.m_Coords === null && this.m_RCoords === null) || this.m_CoordIndices === null)
return false;
if (aReuseFlag) {
if (!this.m_written) {
aFile.push(` geometry DEF ${this.GetName()} IndexedFaceSet {\n`);
this.m_written = true;
} else {
aFile.push(`USE ${this.GetName()}\n`);
return true;
}
} else {
aFile.push(' geometry IndexedFaceSet {\n');
}
this.m_Coords?.WriteVRML(aFile, aReuseFlag);
this.m_RCoords?.WriteVRML(aFile, aReuseFlag);
this.m_CoordIndices.WriteVRML(aFile, aReuseFlag);
if (this.m_Normals || this.m_RNormals) aFile.push(' normalPerVertex TRUE\n');
this.m_Normals?.WriteVRML(aFile, aReuseFlag);
this.m_RNormals?.WriteVRML(aFile, aReuseFlag);
this.m_Colors?.WriteVRML(aFile, aReuseFlag);
this.m_RColors?.WriteVRML(aFile, aReuseFlag);
aFile.push('}\n');
return true;
}
}
+62
View File
@@ -0,0 +1,62 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/** `3d-viewer/3d_cache/sg/sg_helpers.{h,cpp}`: the VRML number formats. */
import { formatG } from '@ziroeda/common/plotters/fmt.js';
import type { SGPOINT, SGVECTOR } from './sg_base.js';
/**
* `S3D::FormatFloat`: `std::setprecision( 8 ) << value` (C's %.8g), trailing zeros of the
* fraction trimmed, and anything within 1e-8 of zero written as "0".
*/
export function FormatFloat(value: number): string {
if (value < 1e-8 && value > -1e-8) return '0';
// note: many VRML implementations use float so we use the max.
// precision here of 8 digits.
let result = formatG(value, 8);
// trim trailing 0 if appropriate
if (!result.includes('.')) return result;
const p = result.search(/[eE]/);
if (p < 0) return result.replace(/0+$/, '');
if (result[p - 1] !== '0') return result;
// trim all 0 to the left of 'p'
return result.substring(0, p).replace(/0+$/, '') + result.substring(p);
}
export function FormatOrientation(axis: SGVECTOR, rotation: number): string {
const [aX, aY, aZ] = axis.GetVector();
return `${FormatFloat(aX)} ${FormatFloat(aY)} ${FormatFloat(aZ)} ${FormatFloat(rotation)}`;
}
export function FormatPoint(point: SGPOINT): string {
return `${FormatFloat(point.x)} ${FormatFloat(point.y)} ${FormatFloat(point.z)}`;
}
export function FormatVector(aVector: SGVECTOR): string {
const [X, Y, Z] = aVector.GetVector();
return `${FormatFloat(X)} ${FormatFloat(Y)} ${FormatFloat(Z)}`;
}
/** `S3D::degenerate`: two of the three points (nearly) coincide. */
export function degenerate(pts: readonly [number, number, number][]): boolean {
const d2 = (a: [number, number, number], b: [number, number, number]): number => {
const dx = b[0] - a[0];
const dy = b[1] - a[1];
const dz = b[2] - a[2];
return dx * dx + dy * dy + dz * dz;
};
if (d2(pts[0]!, pts[1]!) < 1e-15) return true;
if (d2(pts[0]!, pts[2]!) < 1e-15) return true;
if (d2(pts[1]!, pts[2]!) < 1e-15) return true;
return false;
}
+108
View File
@@ -0,0 +1,108 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/** `3d-viewer/3d_cache/sg/sg_index.{h,cpp}`: SGINDEX, the base of the coordinate and color indices. */
import { SGNODE } from './sg_node.js';
import { SGTYPES } from './sg_types.js';
export abstract class SGINDEX extends SGNODE {
index: number[] = [];
SetIndices(aIndexList: readonly number[]): void {
this.index = [...aIndexList];
}
AddIndex(aIndex: number): void {
this.index.push(aIndex);
}
AddRefNode(_aNode: SGNODE): boolean {
return false;
}
AddChildNode(_aNode: SGNODE): boolean {
return false;
}
ReNameNodes(): void {
this.m_written = false;
// rename this node
this.m_Name = '';
this.GetName();
}
WriteVRML(aFile: string[], _aReuseFlag: boolean): boolean {
if (this.index.length === 0) return false;
if (this.m_SGtype === SGTYPES.SGTYPE_COORDINDEX) return this.writeCoordIndex(aFile);
return this.writeColorIndex(aFile);
}
private writeCoordIndex(aFile: string[]): boolean {
const n = this.index.length;
// Coordinate index is not divisible by three (violates triangle constraint)
if (n % 3 !== 0) return false;
aFile.push(' coordIndex [\n ');
// indices to control formatting
let nv0 = 0;
let nv1 = 0;
for (let i = 0; i < n; ) {
aFile.push(String(this.index[i]));
++i;
if (++nv0 === 3) {
aFile.push(',-1');
++nv1;
nv0 = 0;
}
if (i < n) {
aFile.push(',');
if (nv1 === 8) {
nv1 = 0;
aFile.push('\n ');
}
}
}
aFile.push(']\n');
return true;
}
private writeColorIndex(aFile: string[]): boolean {
aFile.push(' colorIndex [\n ');
return this.writeIndexList(aFile);
}
private writeIndexList(aFile: string[]): boolean {
// index to control formatting
let nv = 0;
const n = this.index.length;
for (let i = 0; i < n; ) {
aFile.push(String(this.index[i]));
++i;
if (i < n) {
aFile.push(',');
if (++nv === 20) {
aFile.push('\n ');
nv = 0;
}
}
}
aFile.push(']\n');
return true;
}
}
+87
View File
@@ -0,0 +1,87 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `3d-viewer/3d_cache/sg/sg_node.{h,cpp}`: SGNODE, the scene graph's base. A node is owned by one
* parent and may be referenced (written as USE) by others; names come from one counter per node
* type, shared by every graph, which ResetNodeIndex rewinds.
*/
import { SGTYPES } from './sg_types.js';
const node_names = [
'TXFM',
'APP',
'COL',
'COLIDX',
'FACE',
'COORD',
'COORDIDX',
'NORM',
'SHAPE',
'INVALID',
];
const node_counts: number[] = new Array(SGTYPES.SGTYPE_END).fill(1);
export function GetNodeTypeName(aType: SGTYPES): string {
return node_names[aType]!;
}
function getNodeName(nodeType: SGTYPES): string {
if (nodeType < 0 || nodeType >= SGTYPES.SGTYPE_END) return node_names[SGTYPES.SGTYPE_END]!;
const seqNum = node_counts[nodeType]!;
++node_counts[nodeType]!;
return `${node_names[nodeType]}_${seqNum}`;
}
export abstract class SGNODE {
protected m_Parent: SGNODE | null;
protected m_SGtype: SGTYPES = SGTYPES.SGTYPE_END;
protected m_Name = '';
/** Set to true when the object has been written after a ReNameNodes(). */
protected m_written = false;
constructor(aParent: SGNODE | null) {
this.m_Parent = aParent;
}
GetNodeType(): SGTYPES {
return this.m_SGtype;
}
GetParent(): SGNODE | null {
return this.m_Parent;
}
/** `SetParent( aParent, notify )`, without the unlinking the exporter never needs. */
SetParent(aParent: SGNODE | null): boolean {
this.m_Parent = aParent;
return true;
}
GetName(): string {
if (this.m_Name === '') this.m_Name = getNodeName(this.m_SGtype);
return this.m_Name;
}
SetName(aName: string | null): void {
if (!aName) this.m_Name = getNodeName(this.m_SGtype);
else this.m_Name = aName;
}
ResetNodeIndex(): void {
for (let i = 0; i < SGTYPES.SGTYPE_END; ++i) node_counts[i] = 1;
}
isWritten(): boolean {
return this.m_written;
}
abstract AddRefNode(aNode: SGNODE): boolean;
abstract AddChildNode(aNode: SGNODE): boolean;
abstract ReNameNodes(): void;
abstract WriteVRML(aFile: string[], aReuseFlag: boolean): boolean;
}
+85
View File
@@ -0,0 +1,85 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/** `3d-viewer/3d_cache/sg/sg_normals.{h,cpp}`: SGNORMALS, per-vertex normals. */
import { SGVECTOR } from './sg_base.js';
import { FormatVector } from './sg_helpers.js';
import { SGNODE } from './sg_node.js';
import { SGTYPES } from './sg_types.js';
export class SGNORMALS extends SGNODE {
norms: SGVECTOR[] = [];
constructor(aParent: SGNODE | null) {
super(aParent);
this.m_SGtype = SGTYPES.SGTYPE_NORMALS;
if (aParent !== null && aParent.GetNodeType() !== SGTYPES.SGTYPE_FACESET) this.m_Parent = null;
else if (aParent !== null) aParent.AddChildNode(this);
}
AddNormal(aX: number | SGVECTOR, aY?: number, aZ?: number): void {
if (aX instanceof SGVECTOR) {
const v = new SGVECTOR();
v.SetVector(aX);
this.norms.push(v);
} else {
this.norms.push(new SGVECTOR(aX, aY!, aZ!));
}
}
AddRefNode(_aNode: SGNODE): boolean {
return false;
}
AddChildNode(_aNode: SGNODE): boolean {
return false;
}
ReNameNodes(): void {
this.m_written = false;
// rename this node
this.m_Name = '';
this.GetName();
}
WriteVRML(aFile: string[], aReuseFlag: boolean): boolean {
if (this.norms.length === 0) return false;
if (aReuseFlag) {
if (!this.m_written) {
aFile.push(` normal DEF ${this.GetName()} Normal { vector [\n `);
this.m_written = true;
} else {
aFile.push(` normal USE ${this.GetName()}\n`);
return true;
}
} else {
aFile.push(' normal Normal { vector [\n ');
}
const n = this.norms.length;
let nline = false;
for (let i = 0; i < n; ) {
aFile.push(FormatVector(this.norms[i]!));
++i;
if (i < n) {
aFile.push(',');
if (nline) {
aFile.push('\n ');
nline = false;
} else {
nline = true;
}
}
}
aFile.push('] }\n');
return true;
}
}
+106
View File
@@ -0,0 +1,106 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/** `3d-viewer/3d_cache/sg/sg_shape.{h,cpp}`: SGSHAPE, an appearance and a face set. */
import { SGNODE } from './sg_node.js';
import { SGTYPES } from './sg_types.js';
export class SGSHAPE extends SGNODE {
// owned node
m_Appearance: SGNODE | null = null;
m_FaceSet: SGNODE | null = null;
// referenced nodes
m_RAppearance: SGNODE | null = null;
m_RFaceSet: SGNODE | null = null;
constructor(aParent: SGNODE | null) {
super(aParent);
this.m_SGtype = SGTYPES.SGTYPE_SHAPE;
if (aParent !== null && aParent.GetNodeType() !== SGTYPES.SGTYPE_TRANSFORM)
this.m_Parent = null;
else if (aParent !== null) aParent.AddChildNode(this);
}
private addNode(aNode: SGNODE, isChild: boolean): boolean {
const t = aNode.GetNodeType();
if (t === SGTYPES.SGTYPE_APPEARANCE) {
if (this.m_Appearance || this.m_RAppearance)
return aNode === this.m_Appearance || aNode === this.m_RAppearance;
if (isChild) {
this.m_Appearance = aNode;
aNode.SetParent(this);
} else {
this.m_RAppearance = aNode;
}
return true;
}
if (t === SGTYPES.SGTYPE_FACESET) {
if (this.m_FaceSet || this.m_RFaceSet)
return aNode === this.m_FaceSet || aNode === this.m_RFaceSet;
if (isChild) {
this.m_FaceSet = aNode;
aNode.SetParent(this);
} else {
this.m_RFaceSet = aNode;
}
return true;
}
return false;
}
AddRefNode(aNode: SGNODE): boolean {
return this.addNode(aNode, false);
}
AddChildNode(aNode: SGNODE): boolean {
return this.addNode(aNode, true);
}
ReNameNodes(): void {
this.m_written = false;
// rename this node
this.m_Name = '';
this.GetName();
// rename Appearance
this.m_Appearance?.ReNameNodes();
// rename FaceSet
this.m_FaceSet?.ReNameNodes();
}
WriteVRML(aFile: string[], aReuseFlag: boolean): boolean {
if (!this.m_Appearance && !this.m_RAppearance && !this.m_FaceSet && !this.m_RFaceSet)
return false;
if (aReuseFlag) {
if (!this.m_written) {
aFile.push(`DEF ${this.GetName()} Shape {\n`);
this.m_written = true;
} else {
aFile.push(` USE ${this.GetName()}\n`);
return true;
}
} else {
aFile.push(' Shape {\n');
}
this.m_Appearance?.WriteVRML(aFile, aReuseFlag);
this.m_RAppearance?.WriteVRML(aFile, aReuseFlag);
this.m_FaceSet?.WriteVRML(aFile, aReuseFlag);
this.m_RFaceSet?.WriteVRML(aFile, aReuseFlag);
aFile.push('}\n');
return true;
}
}
+16
View File
@@ -0,0 +1,16 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/** `include/plugins/3dapi/sg_types.h`: the scene graph's node types. */
export enum SGTYPES {
SGTYPE_TRANSFORM = 0,
SGTYPE_APPEARANCE,
SGTYPE_COLORS,
SGTYPE_COLORINDEX,
SGTYPE_FACESET,
SGTYPE_COORDS,
SGTYPE_COORDINDEX,
SGTYPE_NORMALS,
SGTYPE_SHAPE,
SGTYPE_END,
}
+183
View File
@@ -0,0 +1,183 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* 3D viewer menu bar, transcribed from KiCad's
* `3d-viewer/3d_viewer/3d_menubar.cpp` (EDA_3D_VIEWER_FRAME::doReCreateMenuBar).
*
* Order, separators, submenus and check items follow that function exactly;
* labels are each action's `.FriendlyName()` and shortcuts its
* `.DefaultHotkey()` from `3d-viewer/3d_viewer/tools/eda_3d_actions.cpp` and
* `common/tool/actions.cpp`.
*
* Built as a function rather than a constant because half the entries are
* check items whose state is the viewer's, and every entry needs a handler.
*/
import type { Menu, MenuItem } from '@ziroeda/wx/menu.js';
import { standardHelpMenu } from '@ziroeda/common/eda_base_frame_help_menu.js';
import { setLanguageMenuItem } from '@ziroeda/common/eda_base_frame_language_menu.js';
import { addClose } from '@ziroeda/common/tool/action_menu.js';
import type { Grid3D } from './viewer3d_types.js';
export interface Viewer3DMenuState {
grid: Grid3D;
ortho: boolean;
raytracing: boolean;
showAppearanceManager: boolean;
/** `PGM_BASE::GetLanguageTag`'s row, for `AddMenuLanguageList`. */
language: string;
}
export interface Viewer3DMenuActions {
exportImage: () => void;
close: () => void;
copyToClipboard: () => void;
zoomIn: () => void;
zoomOut: () => void;
zoomFit: () => void;
redraw: () => void;
setGrid: (g: Grid3D) => void;
setView: (d: 'top' | 'bottom' | 'left' | 'right' | 'front' | 'back') => void;
rotate: (axis: 'x' | 'y' | 'z', cw: boolean) => void;
flip: () => void;
move: (d: 'left' | 'right' | 'up' | 'down') => void;
/** `EDA_3D_ACTIONS::showLayersManager` → `ToggleLayersManager()`. */
toggleLayersManager: () => void;
/** `ACTIONS::openPreferences`. */
openPreferences: () => void;
/** `ID_MENU3D_RESET_DEFAULTS` (eda_3d_viewer_frame.cpp:487-500). */
resetToDefaults: () => void;
/** `AddMenuLanguageList`'s pick. */
selectLanguage: (label: string) => void;
/** `AddStandardHelpMenu`'s two frame-side handlers. */
showHotkeys: () => void;
showAbout: () => void;
}
/** Feature not ported yet, greyed in its upstream slot (repo convention). */
const todo = { disabled: true } as const;
export function buildViewer3DMenus(state: Viewer3DMenuState, on: Viewer3DMenuActions): Menu[] {
//-- File menu -----------------------------------------------------------
const fileMenu: MenuItem[] = [
{ label: 'Export Image...', icon: 'exportImage3d', action: on.exportImage },
{ sep: true },
addClose('3D Viewer', on.close),
];
//-- Edit menu -----------------------------------------------------------
const editMenu: MenuItem[] = [
{ label: 'Copy 3D Image to Clipboard', icon: 'copyToClipboard3d', action: on.copyToClipboard },
];
//-- View menu -----------------------------------------------------------
const gridSubmenu: MenuItem[] = [
{ label: 'No 3D Grid', checked: state.grid === 'none', action: () => on.setGrid('none') },
{ label: '3D Grid 10mm', checked: state.grid === '10mm', action: () => on.setGrid('10mm') },
{ label: '3D Grid 5mm', checked: state.grid === '5mm', action: () => on.setGrid('5mm') },
{ label: '3D Grid 2.5mm', checked: state.grid === '2.5mm', action: () => on.setGrid('2.5mm') },
{ label: '3D Grid 1mm', checked: state.grid === '1mm', action: () => on.setGrid('1mm') },
];
const rotateSubmenu: MenuItem[] = [
{ label: 'Rotate X Clockwise', icon: 'rotateXCW', action: () => on.rotate('x', true) },
{ label: 'Rotate X Counterclockwise', icon: 'rotateXCCW', action: () => on.rotate('x', false) },
{ sep: true },
{ label: 'Rotate Y Clockwise', icon: 'rotateYCW', action: () => on.rotate('y', true) },
{ label: 'Rotate Y Counterclockwise', icon: 'rotateYCCW', action: () => on.rotate('y', false) },
{ sep: true },
{
label: 'Rotate Z Clockwise',
icon: 'rotateZCW',
shortcut: 'Shift+R',
action: () => on.rotate('z', true),
}, // prettier-ignore
{
label: 'Rotate Z Counterclockwise',
icon: 'rotateZCCW',
shortcut: 'R',
action: () => on.rotate('z', false),
}, // prettier-ignore
];
const moveSubmenu: MenuItem[] = [
{
label: 'Move Board Left',
icon: 'moveLeft3d',
shortcut: 'Left',
action: () => on.move('left'),
},
{
label: 'Move Board Right',
icon: 'moveRight3d',
shortcut: 'Right',
action: () => on.move('right'),
}, // prettier-ignore
{ label: 'Move Board Up', icon: 'moveUp3d', shortcut: 'Up', action: () => on.move('up') },
{
label: 'Move Board Down',
icon: 'moveDown3d',
shortcut: 'Down',
action: () => on.move('down'),
},
];
const viewMenu: MenuItem[] = [
{ label: 'Zoom In', icon: 'zoomIn', action: on.zoomIn },
{ label: 'Zoom Out', icon: 'zoomOut', action: on.zoomOut },
{ label: 'Zoom to Fit', icon: 'zoomFit', shortcut: 'Home', action: on.zoomFit },
{ label: 'Refresh', icon: 'zoomRedraw', shortcut: 'F5', action: on.redraw },
{ sep: true },
{ label: '3D Grid', icon: 'grid', submenu: gridSubmenu },
{ sep: true },
{ label: 'View Top', icon: 'viewTop', shortcut: 'Z', action: () => on.setView('top') },
{
label: 'View Bottom',
icon: 'viewBottom',
shortcut: 'Shift+Z',
action: () => on.setView('bottom'),
}, // prettier-ignore
{ label: 'View Right', icon: 'viewRight', shortcut: 'X', action: () => on.setView('right') },
{ label: 'View Left', icon: 'viewLeft', shortcut: 'Shift+X', action: () => on.setView('left') },
{ label: 'View Front', icon: 'viewFront', shortcut: 'Y', action: () => on.setView('front') },
{ label: 'View Back', icon: 'viewBack', shortcut: 'Shift+Y', action: () => on.setView('back') },
{ sep: true },
{ label: 'Rotate Board', icon: 'rotateCW', submenu: rotateSubmenu },
{ label: 'Flip Board', icon: 'flipView3d', shortcut: 'F', action: on.flip },
{ label: 'Move Board', icon: 'move', submenu: moveSubmenu },
{ sep: true },
{
label: 'Show Appearance Manager',
icon: 'showLayersManager',
checked: state.showAppearanceManager,
action: on.toggleLayersManager,
},
];
//-- Preferences menu ----------------------------------------------------
// 3d_menubar.cpp:128-136: toggleRaytacing (CHECK), openPreferences,
// "Reset to Default Settings", a separator, AddMenuLanguageList.
const prefsMenu: MenuItem[] = [
// Raytracing is the second renderer (render_3d_raytrace_*.cpp), deferred.
{ label: 'Use raytracing', icon: 'toggleRaytracing', checked: state.raytracing, ...todo },
{
label: 'Preferences...',
icon: 'preferences',
shortcut: 'Ctrl+,',
action: on.openPreferences,
},
{ label: 'Reset to Default Settings', icon: 'tools', action: on.resetToDefaults },
{ sep: true },
setLanguageMenuItem({ current: state.language, onSelect: on.selectLanguage }),
];
return [
{ label: 'File', items: fileMenu },
{ label: 'Edit', items: editMenu },
{ label: 'View', items: viewMenu },
{ label: 'Preferences', items: prefsMenu },
// AddStandardHelpMenu( menuBar ): the same Help every frame gets.
standardHelpMenu({ showHotkeys: on.showHotkeys, showAbout: on.showAbout }),
];
}
+76
View File
@@ -0,0 +1,76 @@
# 3d-viewer — divergences from KiCad
Reference: `/home/akshay/kicad-reference/3d-viewer` (10.0.5). Layout rule:
every module sits at the path KiCad keeps its counterpart at, the way
`pcbnew/` and `cvpcb/` do; no `src/`.
Only *divergences* are listed. Anything not mentioned matches.
## What moved here 09-28
Everything below lived under `designer/src/editors/pcb/` until this pass
(the same history `cvpcb/` and `pagelayout_editor/` have). `Viewer3DFrame.tsx`
— `EDA_3D_VIEWER_FRAME` itself — has **not** moved yet; see "Still in
designer/" below.
| KiCad | here |
|---|---|
| `3d_viewer/3d_menubar.cpp` | `3d_menubar.ts` |
| `3d_viewer/toolbars_3d.cpp` | `toolbars_3d.ts` |
| `dialogs/appearance_controls_3D.cpp` | `dialogs/appearance_controls_3d.tsx` — the panel only; the frame docks it |
| `3d_canvas/board_adapter.cpp` | `board_adapter_colors.ts` — `GetLayerColors()`'s stackup-colour block only, whole; the rest of `BOARD_ADAPTER` is split across `pcb3d.ts` / `board_3d_layers.ts` / `viewer3d_appearance.ts` |
| `plugins/3d/occ/loadmodel.cpp` | `loadmodel.ts` — KiCad's OpenCascade kernel, WASM-compiled (`occt-import-js`), plus `occt_tessellate.ts` / `occt_types.ts` / `occt_worker.ts`. KiCad keeps this plugin *outside* `3d-viewer/`, under a sibling `plugins/` top-level directory; there is no `plugins/` package here, so it stays inside this one rather than invent a package for one plugin. |
No exact counterpart, extra (the same shape `pcbnew/board_types.ts` etc. are
for `pcbnew/`): `pcb3d.ts` (the scene builder — `create_3Dgraphic_brd_items.cpp`
+ `create_layer_items.cpp`, fused because the split gains nothing on a scene
graph that is one `THREE.Scene`), `board_3d_layers.ts`, `camera3d.ts`,
`component3d.ts`, `pick3d.ts`, `gl_fixed_function.ts` (the shader/material
half `common_ogl` and `3d_rendering/opengl` split between them upstream),
`viewer3d_types.ts` (the data types, split out for the reason its own header
says — a menu inventory that imports `pcb3d.js` for one type drags three.js
and the STEP loader into every typecheck that touches it), `board_outline.ts`
(board-polygon-with-holes tessellation for the scene; shared with the 2D PCB
editor's Board Area Shadow layer, which imports it from here).
## Never imports `designer/`
Like `cvpcb/` and `pcbnew/`, nothing here reaches into the app. Three seams,
all app-level data a frame or the account's storage supplies, none of it
resolvable by this package on its own:
- **`mount3DViewer`'s `modelsBase` parameter** (`pcb3d.ts`) — where the hosted
`packages3D` bucket serves `<Library>.3dshapes/<Model>.glb` from
(`designer/src/libraryHosts.ts`'s `MODELS3D_HOST`). A plain parameter: the
two designer callers (`Viewer3DFrame.tsx`, `widgets/footprint_preview_3d.tsx`)
pass it in, exactly as `PCBNEW_APP` would.
- **`loadmodel.ts`'s `setModelCache`** — the tessellation cache is KiCad's
`.3dc` cache in IndexedDB (`designer/src/editors/pcb/model_cache.ts`), which
itself needs `home/idb_open.ts`'s IndexedDB handle and `home/local_vault.ts`'s
sealing layer: real app-storage plumbing, not a value a frame can just pass
down. `loadmodel.ts` exports a settable `ModelCache` seam instead
(`modelKey`/`cacheGet`/`cachePut`), defaulting to "never cache" so the
package works unconfigured (a test, or this package used with no app around
it). `designer/src/editors/pcb/viewer3d_cache_shim.ts` wires the real one in,
imported for its side effect by every designer module that can trigger a
model load.
- **`PhysicalStackup` / `BoardFinish`** (`viewer3d_types.ts`) — narrowed,
local stand-ins for the real types in `designer/src/editors/pcb/board_settings.ts`
(the Board Setup dialog's data model, 946 lines, no reason for this package
to see any of the rest of it). Every field `stackupColors` reads is on both,
so passing the real object in through `Viewer3DFrame`'s `stackup` /
`boardFinish` props type-checks on both sides without an import.
## Still in `designer/`
`Viewer3DFrame.tsx` (`EDA_3D_VIEWER_FRAME`) has not moved. Unlike the pieces
above, it is not data or a pure function — it calls `settings.updateViewer3d`
/ `settings.updateCommon` (the persisted Preferences store) directly at
several dozen call sites, and reads `useViewer3dSettings()` /
`useToolbarEntries()`, two live hooks into that same store. Giving it a
`VIEWER3D_APP` the way `CVPCB_APP` / `PL_EDITOR_APP` give their frames one —
`GetViewer3dSettings()` / `UpdateViewer3dSettings()`, a `toolbars` prop, and
the rest — is a real design task on a 945-line file, not a file move, and is
left for its own pass. Everything the frame imports that could move without
that redesign already has (this whole package); the frame keeps importing all
of it from `@ziroeda/3d-viewer` rather than `./`.
+982
View File
@@ -0,0 +1,982 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `BOARD_ADAPTER::createLayers` (3d-viewer/3d_canvas/create_layer_items.cpp)
* and the board/hole polygons `RENDER_3D_OPENGL::reload` derives from it
* (3d_rendering/opengl/create_scene.cpp:688) — every layer of the 3D board
* as a `SHAPE_POLY_SET`, in board IU.
*
* Upstream builds each layer twice: a BVH of 2D objects for the ray tracer
* and for the OpenGL top/bottom faces, and a `SHAPE_POLY_SET` (the union of
* the same items, `Simplify()`'d) for the vertical walls. The renderer then
* subtracts the holes and clips to the board at draw time with the stencil
* buffer (`OPENGL_RENDER_LIST::DrawCulled`). The pixels are the union minus
* the holes, inside the board; that is what this module computes ONCE as
* polygons, on the same `TransformShapeToPolygon` ports and the same Clipper
* the rest of pcbnew runs on. The ray tracer's per-object list is not needed
* for a rasteriser.
*
* Coordinates stay in KiCad's frame (IU, y down). `pcb3d.ts` scales into
* 3D units and flips y, as `BiuTo3dUnits()` / `-pos.y` do upstream.
*/
import { ARC_HIGH_DEF } from '@ziroeda/common/eda_units.js';
import earcut from 'earcut';
import {
type Polygon,
booleanAdd,
booleanSubtract,
booleanIntersection,
simplify,
} from '@ziroeda/kimath/src/geometry/shape_poly_set_algorithms.js';
import type { Vec2 } from '@ziroeda/kimath/src/math/vector2.js';
import { SHAPE_POLY_SET } from '@ziroeda/kimath/src/geometry/shape_poly_set.js';
/** A SHAPE_POLY_SET as outline-plus-holes polygons, in the same IU. */
function polySetToPolygons(set: SHAPE_POLY_SET): Polygon[] {
const out: Polygon[] = [];
for (let i = 0; i < set.OutlineCount(); i++) {
const poly: Vec2[][] = [
set
.COutline(i)
.CPoints()
.map((p) => ({ x: p.x, y: p.y })),
];
for (let h = 0; h < set.HoleCount(i); h++)
poly.push(
set
.CHole(i, h)
.CPoints()
.map((p) => ({ x: p.x, y: p.y })),
);
out.push(poly);
}
return out;
}
import {
TransformCircleToPolygon,
TransformOvalToPolygon,
TransformRingToPolygon,
} from '@ziroeda/kimath/src/geometry/shape_poly_set.js';
import { ERROR_LOC } from '@ziroeda/kimath/src/convert_basic_shapes_to_polygon.js';
import { KICAD_T } from '@ziroeda/core/typeinfo.js';
import { LSET } from '@ziroeda/common/lset.js';
import { IsSolderMaskLayer, PCB_LAYER_ID } from '@ziroeda/common/layer_id.js';
import type { BOARD } from '@ziroeda/pcbnew/board.js';
import type { BOARD_ITEM } from '@ziroeda/pcbnew/board_item.js';
import { LAYER_CLASS } from '@ziroeda/pcbnew/board_design_settings.js';
import type { FOOTPRINT } from '@ziroeda/pcbnew/footprint.js';
import type { PAD } from '@ziroeda/pcbnew/pad.js';
import { PAD_ATTRIB, PAD_SHAPE } from '@ziroeda/pcbnew/padstack.js';
import { PCB_SHAPE } from '@ziroeda/pcbnew/pcb_shape.js';
import type { PCB_TABLE } from '@ziroeda/pcbnew/pcb_table.js';
import type { PCB_TEXT } from '@ziroeda/pcbnew/pcb_text.js';
import type { PCB_TEXTBOX } from '@ziroeda/pcbnew/pcb_textbox.js';
import { type PCB_VIA, VIATYPE } from '@ziroeda/pcbnew/pcb_track.js';
import {
B_Adhes,
B_Cu,
B_Mask,
B_Paste,
B_SilkS,
Cmts_User,
Dwgs_User,
Eco1_User,
Eco2_User,
B_CrtYd,
B_Fab,
Edge_Cuts,
F_Adhes,
F_CrtYd,
F_Cu,
F_Fab,
F_Mask,
F_Paste,
F_SilkS,
In_Cu,
IsCopperLayer,
Margin,
PCB_LAYER_ID_COUNT,
Rescue,
User_1,
} from '@ziroeda/common/layer_ids.js';
/** An axis-aligned box in board IU. */
interface Box {
minX: number;
minY: number;
maxX: number;
maxY: number;
}
/** The PCB_LAYER_IDs the 3D viewer builds (`techLayerList`). */
export type Layer3d =
| `User.${number}`
| 'F.Cu'
| 'B.Cu'
| 'F.Mask'
| 'B.Mask'
| 'F.SilkS'
| 'B.SilkS'
| 'F.Paste'
| 'B.Paste'
| 'F.Adhes'
| 'B.Adhes'
| 'Dwgs.User'
| 'Cmts.User'
| 'Eco1.User'
| 'Eco2.User';
export const LAYERS_3D: readonly Layer3d[] = [
'F.Cu',
'B.Cu',
'F.Mask',
'B.Mask',
'F.SilkS',
'B.SilkS',
'F.Paste',
'B.Paste',
'F.Adhes',
'B.Adhes',
'Dwgs.User',
'Cmts.User',
'Eco1.User',
'Eco2.User',
// User_1 .. User_45 (LAYER_3D_USER_1 .. LAYER_3D_USER_45)
...Array.from({ length: 45 }, (_, i) => `User.${i + 1}` as const),
];
/** `User.N`'s index, 1..45, or 0 for any other layer. */
export const userLayerIndex = (l: string): number => {
const m = /^User\.(\d+)$/.exec(l);
return m ? Number(m[1]) : 0;
};
/** The PCB_LAYER_ID of each 3D layer (layer_ids.h). */
const NAMED_LAYER_ID: Record<string, number> = {
'F.Cu': F_Cu,
'B.Cu': B_Cu,
'F.Mask': F_Mask,
'B.Mask': B_Mask,
'F.SilkS': F_SilkS,
'B.SilkS': B_SilkS,
'F.Paste': F_Paste,
'B.Paste': B_Paste,
'F.Adhes': F_Adhes,
'B.Adhes': B_Adhes,
'Dwgs.User': Dwgs_User,
'Cmts.User': Cmts_User,
'Eco1.User': Eco1_User,
'Eco2.User': Eco2_User,
};
/** `Map3DLayerToPCBLayer`: User_N is `User_1 + 2(N − 1)` — the odd ids after Rescue. */
const layerId = (l: Layer3d): number => {
const u = userLayerIndex(l);
return u ? User_1 + 2 * (u - 1) : NAMED_LAYER_ID[l]!;
};
/** The PCB_LAYER_ID of a canonical layer name the 3D viewer knows, or -1. */
export function pcbLayerIdOf(name: string): number {
const u = userLayerIndex(name);
if (u) return User_1 + 2 * (u - 1);
return NAMED_LAYER_ID[name] ?? -1;
}
/**
* `PCB_PLOT_PARAMS` as the 3D viewer's FOLLOW_PLOT_SETTINGS preset reads it
* (`BOARD_ADAPTER::GetVisibleLayers`, board_adapter.cpp:907-935): the
* `layerselection` set plus the plot-on-all-layers set, and the three
* footprint text flags.
*/
export interface PlotLayerSelection {
/** PCB_LAYER_IDs in `(layerselection …)` ∪ `(plotonalllayersselection …)`. */
layers: Set<number>;
plotReference: boolean;
plotValue: boolean;
plotFPText: boolean;
}
/**
* `BASE_SET::ParseHex` (base_set.h:362): the string is read from its END,
* one nibble = four layer ids, `_` separators skipped.
*/
export function parseLayerSetHex(hex: string): Set<number> {
const out = new Set<number>();
let nibbleNdx = 0;
for (let i = hex.length - 1; i >= 0; i--) {
const cc = hex[i]!;
if (cc === '_') continue;
const nibble = parseInt(cc, 16);
if (Number.isNaN(nibble)) break;
let bit = nibbleNdx * 4;
for (let ndx = 0; bit < PCB_LAYER_ID_COUNT && ndx < 4; ++bit, ++ndx)
if (nibble & (1 << ndx)) out.add(bit);
if (bit >= PCB_LAYER_ID_COUNT) break;
++nibbleNdx;
}
return out;
}
/**
* `s_legacyLayerIdMap` (pcb_plot_params.cpp:475): the file's layer NUMBERING
* changed in 5e0abadb without a version bump, so a `layerselection` written
* by a board older than 20240819 is in `LEGACY_PCB_LAYER_ID` order —
* F_Cu 0, In1..In30 1..30, B_Cu 31, then B/F Adhes, B/F Paste, B/F SilkS,
* B/F Mask (32..39), Dwgs, Cmts, Eco1, Eco2, Edge, Margin (40..45), B/F
* CrtYd, B/F Fab (46..49), User_1..9 (50..58), Rescue 59. Read unmapped, a
* KiCad 8 board's silk bit (36) lands on F_Fab and its silk vanishes.
*/
export function remapLegacyLayerSet(legacy: Set<number>): Set<number> {
const map = new Map<number, number>();
map.set(0, F_Cu);
for (let n = 1; n <= 30; n++) map.set(n, In_Cu(n));
map.set(31, B_Cu);
const tail = [B_Adhes, F_Adhes, B_Paste, F_Paste, B_SilkS, F_SilkS, B_Mask, F_Mask];
tail.forEach((id, i) => map.set(32 + i, id));
const users = [Dwgs_User, Cmts_User, Eco1_User, Eco2_User, Edge_Cuts, Margin];
users.forEach((id, i) => map.set(40 + i, id));
[B_CrtYd, F_CrtYd, B_Fab, F_Fab].forEach((id, i) => map.set(46 + i, id));
// User_n == User_1 + 2(n − 1) — the odd ids after Rescue
for (let n = 1; n <= 9; n++) map.set(49 + n, User_1 + 2 * (n - 1));
map.set(59, Rescue);
const out = new Set<number>();
for (const [legacyId, newId] of map) if (legacy.has(legacyId)) out.add(newId);
return out;
}
/** The board file version the new numbering arrived with (pcb_plot_params.cpp:622). */
export const LAYER_RENUMBER_VERSION = 20240819;
/** `PCB_PLOT_PARAMS::PCB_PLOT_PARAMS()`: the layer set a board without one plots. */
export function defaultPlotLayerSelection(): Set<number> {
const out = new Set<number>([F_SilkS, B_SilkS, F_Mask, B_Mask, F_Paste, B_Paste, Edge_Cuts]);
for (let id = 0; id < PCB_LAYER_ID_COUNT; id++) if (IsCopperLayer(id)) out.add(id);
return out;
}
export function plotLayerSelection(aBoard: BOARD): PlotLayerSelection {
const p = aBoard.GetPlotOptions();
const layers = new Set(p.GetLayerSelection().Seq());
for (const id of p.GetPlotOnAllLayersSequence()) layers.add(id);
// `m_plotReference` / `m_plotValue` / `m_plotFPText` are not board-file
// tokens in 10.0.5 (`PCB_PLOT_PARAMS::Parse` has no case for them), so a
// loaded board holds the constructor's `true` for all three.
return { layers, plotReference: true, plotValue: true, plotFPText: true };
}
export const isBackLayer = (l: string): boolean => l.startsWith('B.');
export const isCopperLayer3d = (l: string): boolean => l === 'F.Cu' || l === 'B.Cu';
export const isSilkLayer = (l: string): boolean => l === 'F.SilkS' || l === 'B.SilkS';
export const isMaskLayer = (l: string): boolean => l === 'F.Mask' || l === 'B.Mask';
export const isPasteLayer = (l: string): boolean => l === 'F.Paste' || l === 'B.Paste';
/** The `EDA_3D_VIEWER_SETTINGS::RENDER_SETTINGS` bits `createLayers` reads. */
export interface Layer3dOptions {
/**
* The board has NOTHING on it — `BOARD_ADAPTER::createBoardPolygon` on a
* footprint holder with no footprint returns false before any outline is
* tried (board_adapter.cpp:1003-1010), so `m_board_poly` stays empty and no
* board body is drawn. With this set the bbox fallback rectangle is NOT
* used; the rectangle is `buildBoardBoundingBoxPoly`'s answer for a board
* that HAS items and no closed outline.
*/
empty?: boolean;
/** `show_zones` (default true). */
showZones?: boolean;
/** `show_fp_references` / `show_fp_values` / `show_fp_text` (all default true). */
showFpReferences?: boolean;
showFpValues?: boolean;
showFpText?: boolean;
/** `opengl_show_off_board_silk` (default false): silk is clipped to the board. */
showOffBoardSilk?: boolean;
/** `subtract_mask_from_silk` (default false). */
subtractMaskFromSilk?: boolean;
/** `clip_silk_on_via_annulus` (default false): silk is clipped on the via annulus, not just the hole. */
clipSilkOnViaAnnuli?: boolean;
/**
* `plated_and_bare_copper` (`DifferentiatePlatedCopper()`, default false):
* the copper exposed through the mask is "plated" and drawn in the finish
* colour; the rest is raw copper.
*/
differentiatePlatedCopper?: boolean;
/** `show_plated_barrels` (default true). */
showPlatedBarrels?: boolean;
/** `ADVANCED_CFG::m_HoleWallThickness` (0.020 mm): the barrel's plating, IU. */
holePlatingThickness?: number;
/** `BOARD_DESIGN_SETTINGS::m_MaxError` (ARC_HIGH_DEF). */
maxError?: number;
/**
* `Is3dLayerEnabled( layer, visibilityFlags )`: the PCB_LAYER_IDs the
* preset shows. A layer not in the set is not built. Omitted = every layer.
*/
visibleLayers?: Set<number>;
/** `createLayers( REPORTER* aStatusReporter )`: the stage names it reports. */
report?: (text: string) => void;
}
export interface Board3dLayers {
/** Per layer, the union of every item on it, already minus the holes and clipped to the board. */
layers: Partial<Record<Layer3d, Polygon[]>>;
/** `GetBoardPoly()`: the Edge.Cuts outline with its cutouts. */
boardPoly: Polygon[];
/** `m_boardWithHoles`: the body, minus plated and non-plated drills. */
boardWithHoles: Polygon[];
/** `GetTH_ODPolys()`: plated drills grown by the plating (what the copper is cut by). */
thOD: Polygon[];
/** `GetTH_IDPolys()`: the plated drills themselves. */
thID: Polygon[];
/** `GetNPTH_ODPolys()`: the non-plated drills. */
npthOD: Polygon[];
/** `GetViaAnnuliPolys()`: the through-via annuli (`clip_silk_on_via_annulus`). */
viaAnnuli: Polygon[];
/** `generatePlatedHoleShells`: the copper ring between drill and drill+plating, inside the board. */
platedBarrels: Polygon[];
/** The mask the silk is subtracted by when `subtract_mask_from_silk` is on (the mask layer's OPENINGS). */
maskOpenings: { 'F.Mask': Polygon[]; 'B.Mask': Polygon[] };
/** `m_boardPos` / `m_boardSize`: the bbox the 3D units are derived from, IU. */
bbox: Box;
/**
* `generateViaBarrels`: every via that is not a plain through via — blind
* and micro vias — as the cylinder between its two end layers, drill/2
* inside and plating outside. Its hole is already cut from the copper of
* the layers it spans (`m_outerLayerHoles[layer]`).
*/
viaBarrels: { at: Vec2; drill: number; topLayer: string; bottomLayer: string }[];
/**
* `m_platedPadsFront/Back` when `DifferentiatePlatedCopper()`: the copper
* under the mask openings, already taken out of `layers['F.Cu'/'B.Cu']`.
* Empty otherwise.
*/
platedCopper: { 'F.Cu': Polygon[]; 'B.Cu': Polygon[] };
}
/** `ADVANCED_CFG::m_HoleWallThickness`, 0.020 mm, in IU. */
export const DEFAULT_HOLE_PLATING_THICKNESS = 20000;
/** A SHAPE_POLY_SET as the polygons the rest of this module unions and cuts. */
function polysOf(aSet: SHAPE_POLY_SET): Polygon[] {
return polySetToPolygons(aSet);
}
/** `textbox->PCB_SHAPE::TransformShapeToPolygon( … )`: the box, not the text's bounds. */
function textboxBorderToPolygon(
aTextbox: PCB_TEXTBOX,
aBuffer: SHAPE_POLY_SET,
aLayer: PCB_LAYER_ID,
aMaxError: number,
aErrorLoc: ERROR_LOC,
): void {
const base = PCB_SHAPE.prototype.TransformShapeToPolygon as (
this: PCB_SHAPE,
aBuffer: SHAPE_POLY_SET,
aLayer: PCB_LAYER_ID,
aClearance: number,
aError: number,
aErrorLoc: ERROR_LOC,
) => void;
base.call(aTextbox, aBuffer, aLayer, 0, aMaxError, aErrorLoc);
}
/** `transformFPShapesToPolySet` (create_layer_items.cpp:80-118). */
function transformFPShapesToPolySet(
aFootprint: FOOTPRINT,
aLayer: PCB_LAYER_ID,
aBuffer: SHAPE_POLY_SET,
aMaxError: number,
aErrorLoc: ERROR_LOC,
): void {
for (const item of aFootprint.GraphicalItems()) {
if (!item.IsOnLayer(aLayer)) continue;
switch (item.Type()) {
case KICAD_T.PCB_SHAPE_T: {
const shape = item as PCB_SHAPE;
let margin = 0;
if (IsSolderMaskLayer(aLayer) && shape.HasSolderMask())
margin = shape.GetSolderMaskExpansion();
item.TransformShapeToPolySet(aBuffer, aLayer, margin, aMaxError, aErrorLoc);
break;
}
case KICAD_T.PCB_BARCODE_T:
case KICAD_T.PCB_DIM_ALIGNED_T:
case KICAD_T.PCB_DIM_CENTER_T:
case KICAD_T.PCB_DIM_RADIAL_T:
case KICAD_T.PCB_DIM_ORTHOGONAL_T:
case KICAD_T.PCB_DIM_LEADER_T:
item.TransformShapeToPolySet(aBuffer, aLayer, 0, aMaxError, aErrorLoc);
break;
default:
break;
}
}
}
/** The `LAYER_FP_TEXT` / `LAYER_FP_REFERENCES` / `LAYER_FP_VALUES` flags. */
interface FP_TEXT_FLAGS {
fpText: boolean;
references: boolean;
values: boolean;
}
/** `transformFPTextToPolySet` (create_layer_items.cpp:121-176). */
function transformFPTextToPolySet(
aFootprint: FOOTPRINT,
aLayer: PCB_LAYER_ID,
aFlags: FP_TEXT_FLAGS,
aBuffer: SHAPE_POLY_SET,
aMaxError: number,
aErrorLoc: ERROR_LOC,
): void {
for (const item of aFootprint.GraphicalItems()) {
if (item.Type() === KICAD_T.PCB_TEXT_T) {
const text = item as PCB_TEXT;
if (!aFlags.fpText) continue;
if (text.GetText() === '${REFERENCE}' && !aFlags.references) continue;
if (text.GetText() === '${VALUE}' && !aFlags.values) continue;
if (text.IsOnLayer(aLayer)) text.TransformTextToPolySet(aBuffer, 0, aMaxError, aErrorLoc);
}
if (item.Type() === KICAD_T.PCB_TEXTBOX_T) {
const textbox = item as PCB_TEXTBOX;
if (textbox.IsOnLayer(aLayer)) {
// border
if (textbox.IsBorderEnabled())
textboxBorderToPolygon(textbox, aBuffer, aLayer, aMaxError, aErrorLoc);
// text
textbox.TransformTextToPolySet(aBuffer, 0, aMaxError, aErrorLoc);
}
}
}
for (const field of aFootprint.GetFields()) {
if (!aFlags.fpText) continue;
if (!field) continue;
if (field.IsReference() && !aFlags.references) continue;
if (field.IsValue() && !aFlags.values) continue;
if (field.IsOnLayer(aLayer) && field.IsVisible())
field.TransformTextToPolySet(aBuffer, 0, aMaxError, aErrorLoc);
}
}
/** `buildPadOutlineAsPolygon` (create_layer_items.cpp:56-77). */
function buildPadOutlineAsPolygon(
aPad: PAD,
aLayer: PCB_LAYER_ID,
aBuffer: SHAPE_POLY_SET,
aWidth: number,
aMaxError: number,
aErrorLoc: ERROR_LOC,
): void {
if (aPad.GetShape(aLayer) === PAD_SHAPE.CIRCLE) {
// Draw a ring
TransformRingToPolygon(
aBuffer,
aPad.ShapePos(aLayer),
Math.trunc(aPad.GetSize(aLayer).x / 2),
aWidth,
aMaxError,
aErrorLoc,
);
} else {
// For other shapes, add outlines as thick segments in polygon buffer
const path = aPad.GetEffectivePolygon(aLayer, ERROR_LOC.ERROR_INSIDE).COutline(0);
const n = path.PointCount();
for (let ii = 0; ii < n; ++ii)
TransformOvalToPolygon(
aBuffer,
path.CPoint(ii),
path.CPoint((ii + 1) % n),
aWidth,
aMaxError,
aErrorLoc,
);
}
}
/**
* A board drawing's polygons (create_layer_items.cpp:1525-1600, the same
* switch the copper pass runs at :1170-1250).
*/
function transformDrawingToPolySet(
aItem: BOARD_ITEM,
aLayer: PCB_LAYER_ID,
aBuffer: SHAPE_POLY_SET,
aMaxError: number,
): void {
switch (aItem.Type()) {
case KICAD_T.PCB_SHAPE_T: {
const shape = aItem as PCB_SHAPE;
let margin = 0;
if (IsSolderMaskLayer(aLayer) && shape.HasSolderMask())
margin = shape.GetSolderMaskExpansion();
aItem.TransformShapeToPolySet(aBuffer, aLayer, margin, aMaxError, ERROR_LOC.ERROR_INSIDE);
break;
}
case KICAD_T.PCB_TEXT_T:
(aItem as PCB_TEXT).TransformTextToPolySet(aBuffer, 0, aMaxError, ERROR_LOC.ERROR_INSIDE);
break;
case KICAD_T.PCB_TEXTBOX_T: {
const textbox = aItem as PCB_TEXTBOX;
if (textbox.IsBorderEnabled())
textboxBorderToPolygon(textbox, aBuffer, aLayer, aMaxError, ERROR_LOC.ERROR_INSIDE);
textbox.TransformTextToPolySet(aBuffer, 0, aMaxError, ERROR_LOC.ERROR_INSIDE);
break;
}
case KICAD_T.PCB_TABLE_T: {
const table = aItem as PCB_TABLE;
for (const cell of table.GetCells())
cell.TransformTextToPolySet(aBuffer, 0, aMaxError, ERROR_LOC.ERROR_INSIDE);
table.DrawBorders((ptA, ptB, stroke) => {
TransformOvalToPolygon(
aBuffer,
ptA,
ptB,
stroke.GetWidth(),
aMaxError,
ERROR_LOC.ERROR_INSIDE,
);
});
break;
}
case KICAD_T.PCB_BARCODE_T:
aItem.TransformShapeToPolySet(aBuffer, aLayer, 0, 0, ERROR_LOC.ERROR_INSIDE);
break;
case KICAD_T.PCB_DIM_ALIGNED_T:
case KICAD_T.PCB_DIM_CENTER_T:
case KICAD_T.PCB_DIM_RADIAL_T:
case KICAD_T.PCB_DIM_ORTHOGONAL_T:
case KICAD_T.PCB_DIM_LEADER_T:
aItem.TransformShapeToPolySet(aBuffer, aLayer, 0, aMaxError, ERROR_LOC.ERROR_INSIDE);
break;
default:
break;
}
}
/**
* `BOARD_ADAPTER::createLayers`, the polygon half, over the BOARD's items.
*/
export function buildBoard3dLayers(
aBoard: BOARD,
bbox: Box,
opts: Layer3dOptions = {},
): Board3dLayers {
const bds = aBoard.GetDesignSettings();
const maxError = opts.maxError ?? bds.m_MaxError ?? ARC_HIGH_DEF;
const plating = opts.holePlatingThickness ?? DEFAULT_HOLE_PLATING_THICKNESS;
const showZones = opts.showZones !== false;
const flags: FP_TEXT_FLAGS = {
fpText: opts.showFpText !== false,
references: opts.showFpReferences !== false,
values: opts.showFpValues !== false,
};
const report = opts.report ?? ((): void => {});
const vias = aBoard.Tracks().filter((t) => t.Type() === KICAD_T.PCB_VIA_T) as PCB_VIA[];
// ----- the board -----------------------------------------------------------
// BOARD_ADAPTER::createBoardPolygon (board_adapter.cpp:1029):
// `GetBoardPolygonOutlines( m_board_poly, true, nullptr, false, true )`.
let boardPoly: Polygon[] = [];
if (!opts.empty) {
const set = new SHAPE_POLY_SET();
aBoard.GetBoardPolygonOutlines(set, true, null, false, true);
boardPoly = polySetToPolygons(set);
}
// ----- the holes -----------------------------------------------------------
// create_layer_items.cpp:527-566 (vias) and :904-930 (pads).
const thODSet = new SHAPE_POLY_SET();
const thIDSet = new SHAPE_POLY_SET();
const npthSet = new SHAPE_POLY_SET();
const annuliSet = new SHAPE_POLY_SET();
for (const via of vias) {
if (via.GetViaType() !== VIATYPE.THROUGH) continue;
const holeRadius = Math.trunc(via.GetDrillValue() / 2);
const holeOuterRadius = holeRadius + plating;
const holeOuterRingRadius = Math.trunc(via.GetWidth(PCB_LAYER_ID.F_Cu) / 2);
TransformCircleToPolygon(
thODSet,
via.GetStart(),
holeOuterRadius,
maxError,
ERROR_LOC.ERROR_INSIDE,
);
TransformCircleToPolygon(thIDSet, via.GetStart(), holeRadius, maxError, ERROR_LOC.ERROR_INSIDE);
TransformCircleToPolygon(
annuliSet,
via.GetStart(),
holeOuterRingRadius,
maxError,
ERROR_LOC.ERROR_INSIDE,
);
}
for (const fp of aBoard.Footprints()) {
for (const pad of fp.Pads()) {
const drill = pad.GetDrillSize();
if (drill.x === 0 || drill.y === 0) continue;
// The hole in the body is inflated by copper thickness.
if (pad.GetAttribute() === PAD_ATTRIB.NPTH) {
pad.TransformHoleToPolygon(npthSet, 0, maxError, ERROR_LOC.ERROR_INSIDE);
} else {
pad.TransformHoleToPolygon(thODSet, plating, maxError, ERROR_LOC.ERROR_INSIDE);
pad.TransformHoleToPolygon(thIDSet, 0, maxError, ERROR_LOC.ERROR_INSIDE);
pad.TransformHoleToPolygon(annuliSet, plating, maxError, ERROR_LOC.ERROR_INSIDE);
}
}
}
// This will make a union of all added contours
const thOD = simplify(polysOf(thODSet));
const thID = simplify(polysOf(thIDSet));
const npthOD = simplify(polysOf(npthSet));
const viaAnnuli = simplify(polysOf(annuliSet));
// Blind/micro vias (create_layer_items.cpp:536-546): their hole is per
// layer, not through the board.
const layerViaHoles: Partial<Record<Layer3d, Polygon[]>> = {};
const viaBarrels: Board3dLayers['viaBarrels'] = [];
for (const via of vias) {
if (via.GetViaType() === VIATYPE.THROUGH) continue;
const [top, bottom] = via.LayerPair();
viaBarrels.push({
at: { ...via.GetStart() },
drill: via.GetDrillValue(),
topLayer: LSET.Name(top),
bottomLayer: LSET.Name(bottom),
});
const holeOuterRadius = Math.trunc(via.GetDrillValue() / 2) + plating;
for (const layer of ['F.Cu', 'B.Cu'] as const) {
if (LSET.Name(top) !== layer && LSET.Name(bottom) !== layer) continue;
const set = new SHAPE_POLY_SET();
TransformCircleToPolygon(
set,
via.GetStart(),
holeOuterRadius,
maxError,
ERROR_LOC.ERROR_INSIDE,
);
const holes = layerViaHoles[layer] ?? [];
holes.push(...polysOf(set));
layerViaHoles[layer] = holes;
}
}
// `board_poly_with_holes` (create_scene.cpp:720-744).
let boardWithHoles = booleanSubtract(boardPoly, thOD);
boardWithHoles = booleanSubtract(boardWithHoles, npthOD);
// `generatePlatedHoleShells`: (drill + plating) − drill, inside the board.
let platedBarrels: Polygon[] = [];
if (opts.showPlatedBarrels !== false)
platedBarrels = booleanIntersection(booleanSubtract(thOD, thID), boardPoly);
// `m_outerThroughHoles` is the plated AND non-plated drills together
// (create_scene.cpp:757-765), which is what every layer is cut by.
const allHoles = booleanAdd(thOD, npthOD);
// ----- per-layer item polygons ----------------------------------------------
report('Create tracks and vias'); // create_layer_items.cpp:315
const items: Partial<Record<Layer3d, SHAPE_POLY_SET>> = {};
const bufferOf = (aLayer: Layer3d): SHAPE_POLY_SET => {
const existing = items[aLayer];
if (existing) return existing;
const created = new SHAPE_POLY_SET();
items[aLayer] = created;
return created;
};
// Copper layers (create_layer_items.cpp:737-1305).
for (const name of ['F.Cu', 'B.Cu'] as const) {
const layer = pcbLayerIdOf(name);
const buf = bufferOf(name);
// ADD TRACKS: the track/via contour, skipping a via annulus not flashed here.
for (const track of aBoard.Tracks()) {
if (!track.IsOnLayer(layer)) continue;
if (track.Type() === KICAD_T.PCB_VIA_T && !(track as PCB_VIA).FlashLayer(layer)) continue;
track.TransformShapeToPolygon(buf, layer, 0, maxError, ERROR_LOC.ERROR_INSIDE);
}
for (const fp of aBoard.Footprints()) {
fp.TransformPadsToPolySet(buf, layer, 0, maxError, ERROR_LOC.ERROR_INSIDE);
transformFPTextToPolySet(fp, layer, flags, buf, maxError, ERROR_LOC.ERROR_INSIDE);
transformFPShapesToPolySet(fp, layer, buf, maxError, ERROR_LOC.ERROR_INSIDE);
}
for (const item of aBoard.Drawings()) {
if (item.IsOnLayer(layer)) transformDrawingToPolySet(item, layer, buf, maxError);
}
if (showZones) {
for (const zone of aBoard.Zones())
if (zone.IsOnLayer(layer)) zone.TransformSolidAreasShapesToPolygon(layer, buf);
}
}
// Tech layers (create_layer_items.cpp:1340-1670).
report('Build Tech layers');
const maskOpenings = { 'F.Mask': [] as Polygon[], 'B.Mask': [] as Polygon[] };
const silkLineWidth = bds.m_LineThickness[LAYER_CLASS.LAYER_CLASS_SILK]!;
for (const name of LAYERS_3D) {
if (isCopperLayer3d(name)) continue;
const layer = pcbLayerIdOf(name);
const buf = bufferOf(name);
// DRAWINGS
for (const item of aBoard.Drawings()) {
if (item.IsOnLayer(layer)) transformDrawingToPolySet(item, layer, buf, maxError);
}
// NON-TENTED VIAS
if (layer === PCB_LAYER_ID.F_Mask || layer === PCB_LAYER_ID.B_Mask) {
const maskExpansion = bds.m_SolderMaskExpansion;
for (const track of aBoard.Tracks()) {
if (track.Type() === KICAD_T.PCB_VIA_T) {
const via = track as PCB_VIA;
if (via.FlashLayer(layer) && !via.IsTented(layer))
track.TransformShapeToPolygon(
buf,
layer,
maskExpansion,
maxError,
ERROR_LOC.ERROR_INSIDE,
);
} else if (track.HasSolderMask()) {
track.TransformShapeToPolySet(
buf,
layer,
maskExpansion,
maxError,
ERROR_LOC.ERROR_INSIDE,
);
}
}
}
// FOOTPRINT CHILDREN
for (const fp of aBoard.Footprints()) {
if (layer === PCB_LAYER_ID.F_SilkS || layer === PCB_LAYER_ID.B_SilkS) {
for (const pad of fp.Pads()) {
if (pad.IsOnLayer(layer))
buildPadOutlineAsPolygon(
pad,
layer,
buf,
silkLineWidth,
maxError,
ERROR_LOC.ERROR_INSIDE,
);
}
} else {
fp.TransformPadsToPolySet(buf, layer, 0, maxError, ERROR_LOC.ERROR_INSIDE);
}
transformFPTextToPolySet(fp, layer, flags, buf, maxError, ERROR_LOC.ERROR_INSIDE);
transformFPShapesToPolySet(fp, layer, buf, maxError, ERROR_LOC.ERROR_INSIDE);
}
if (showZones || layer === PCB_LAYER_ID.F_Mask || layer === PCB_LAYER_ID.B_Mask) {
for (const zone of aBoard.Zones())
if (zone.IsOnLayer(layer)) zone.TransformSolidAreasShapesToPolygon(layer, buf);
}
}
// ----- union, cut the holes, clip to the board -----------------------------
report('Simplifying copper layer polygons'); // create_layer_items.cpp:1674
// `DrawCulled( showThickness, throughHolesOuter, anti_board )` for a tech
// layer, `( outerTH, viaHoles, m_antiBoard )` for copper. The mask is the
// odd one: its list is the OPENINGS, and the layer drawn is the BOARD minus
// them (`renderSolderMaskLayer`).
const layers: Partial<Record<Layer3d, Polygon[]>> = {};
// `Is3dLayerEnabled`: the board must have the layer enabled at all, and
// the preset must show it.
const visible = (layer: Layer3d): boolean =>
aBoard.IsLayerEnabled(layerId(layer)) &&
(!opts.visibleLayers || opts.visibleLayers.has(layerId(layer)));
for (const layer of LAYERS_3D) {
if (!visible(layer)) continue;
const raw = items[layer] ? polysOf(items[layer]!) : [];
if (raw.length === 0) {
if (isMaskLayer(layer)) layers[layer] = booleanSubtract(boardPoly, allHoles);
continue;
}
const unioned = simplify(raw);
if (isMaskLayer(layer)) {
maskOpenings[layer as 'F.Mask' | 'B.Mask'] = unioned;
layers[layer] = booleanSubtract(booleanSubtract(boardPoly, unioned), allHoles);
continue;
}
let poly = unioned;
if (isSilkLayer(layer)) {
// clip_silk_on_via_annuli: the silk is cut back to the via ring, not just the hole.
poly = booleanSubtract(poly, opts.clipSilkOnViaAnnuli ? viaAnnuli : allHoles);
if (!opts.showOffBoardSilk) poly = booleanIntersection(poly, boardPoly);
if (opts.subtractMaskFromSilk && !opts.showOffBoardSilk) {
const openings = maskOpenings[layer === 'F.SilkS' ? 'F.Mask' : 'B.Mask'];
// the silk is only where the MASK is, i.e. not in its openings
if (openings) poly = booleanSubtract(poly, openings);
}
} else {
poly = booleanSubtract(poly, allHoles);
// a copper layer is also cut by the blind/micro via holes that end on it
const viaHoles = layerViaHoles[layer];
if (viaHoles && viaHoles.length) poly = booleanSubtract(poly, simplify(viaHoles));
// `LSET::PhysicalLayersMask().test( layer )` — every layer here is physical.
poly = booleanIntersection(poly, boardPoly);
}
layers[layer] = poly;
}
// TRIM PLATED COPPER TO SOLDERMASK, then subtract it from the unplated
// (create_layer_items.cpp:1673-1697).
if (opts.differentiatePlatedCopper) report('Calculating plated copper');
const platedCopper = { 'F.Cu': [] as Polygon[], 'B.Cu': [] as Polygon[] };
if (opts.differentiatePlatedCopper) {
for (const [cu, mask] of [
['F.Cu', 'F.Mask'],
['B.Cu', 'B.Mask'],
] as const) {
const copper = layers[cu];
if (!copper) continue;
const plated = booleanIntersection(copper, maskOpenings[mask]);
platedCopper[cu] = plated;
layers[cu] = booleanSubtract(copper, plated);
}
}
// The mask layers were unioned before the silk asked for their openings;
// a silk layer visited before its mask would have missed them, so do the
// subtraction again now that both exist.
if (opts.subtractMaskFromSilk && !opts.showOffBoardSilk) {
for (const silk of ['F.SilkS', 'B.SilkS'] as const) {
const openings = maskOpenings[silk === 'F.SilkS' ? 'F.Mask' : 'B.Mask'];
if (layers[silk] && openings.length) layers[silk] = booleanSubtract(layers[silk]!, openings);
}
}
return {
layers,
boardPoly,
boardWithHoles,
thOD,
thID,
npthOD,
viaAnnuli,
platedBarrels,
maskOpenings,
bbox,
viaBarrels,
platedCopper,
};
}
/**
* Every polygon list of \a aLayers, in one fixed order. Not KiCad's: the 3D layer job
* (board_3d_layers_job.ts) triangulates in this order and the scene reads the triangles back in
* the same one.
*/
export function forEachPolygonList(
aLayers: Board3dLayers,
aVisit: (aList: Polygon[]) => void,
): void {
for (const k of Object.keys(aLayers.layers).sort()) {
const list = aLayers.layers[k as Layer3d];
if (list) aVisit(list);
}
aVisit(aLayers.boardPoly);
aVisit(aLayers.boardWithHoles);
aVisit(aLayers.thOD);
aVisit(aLayers.thID);
aVisit(aLayers.npthOD);
aVisit(aLayers.viaAnnuli);
aVisit(aLayers.platedBarrels);
aVisit(aLayers.maskOpenings['F.Mask']);
aVisit(aLayers.maskOpenings['B.Mask']);
aVisit(aLayers.platedCopper['F.Cu']);
aVisit(aLayers.platedCopper['B.Cu']);
}
/**
* The faces of \a aPoly as triangles, indices into its points ring after ring - what the
* scene's addTopAndBottom draws them from. Null for a polygon too small to have a face.
*/
export function TriangulatePolygon(aPoly: Polygon): Uint32Array | null {
const flat: number[] = [];
const holes: number[] = [];
aPoly.forEach((ring, ri) => {
if (ri > 0) holes.push(flat.length / 2);
for (const p of ring) flat.push(p.x, p.y);
});
if (flat.length < 6) return null;
return Uint32Array.from(earcut(flat, holes.length ? holes : undefined));
}
+212
View File
@@ -0,0 +1,212 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* The 3D viewer's layer build on a worker (not KiCad's).
*
* `RENDER_3D_OPENGL::reload` rebuilds every layer of the board on each `NewDisplay( true )` -
* a layer shown or hidden in the appearance pane, a board edit, a preference. KiCad does that in
* C++ on its GUI thread; here the same `BOARD_ADAPTER::createLayers` (board_3d_layers.ts) and
* the triangulation of its faces take seconds on a large board, and on the window's thread they
* freeze the whole app for them. So they run here, on a copy of the board parsed from its text
* (as the DRC and fill jobs do), and the scene on screen stays up until the new one is ready -
* which is what upstream's reload already does with the previous frame.
*
* The board's text is the transport; the answer is the layers' polygons and, in
* forEachPolygonList's order, each polygon's triangles.
*/
import { EMBEDDED_FILES } from '@ziroeda/common/embedded_files.js';
import type { BOARD } from '@ziroeda/pcbnew/board.js';
import {
CTL_ENUMERATE_LAYERS,
CTL_FOR_BOARD,
FormatBoardAsync,
ParseBoard,
} from '@ziroeda/pcbnew/pcb_io/kicad_sexpr/pcb_io_kicad_sexpr.js';
import {
type Board3dLayers,
buildBoard3dLayers,
forEachPolygonList,
type Layer3dOptions,
TriangulatePolygon,
} from './board_3d_layers.js';
type Box = Parameters<typeof buildBoard3dLayers>[1];
/** What the job builds from: the board's text and createLayers' inputs. */
interface BOARD_3D_LAYERS_REQUEST {
id: number;
boardText: string;
bbox: Box;
opts: Omit<Layer3dOptions, 'report'>;
}
type BOARD_3D_LAYERS_MESSAGE =
| { id: number; t: 'report'; text: string }
| { id: number; t: 'done'; built: Board3dLayers; tris: (Uint32Array | null)[] }
| { id: number; t: 'error'; message: string };
/** The layers, and each polygon's triangles in forEachPolygonList's order. */
export interface BOARD_3D_LAYERS_RESULT {
built: Board3dLayers;
tris: (Uint32Array | null)[];
}
// ---------------------------------------------------------------------------------------------
// The window's half.
// ---------------------------------------------------------------------------------------------
let s_worker: Worker | null = null;
/** Set once a worker could not be made or died: the scene builds on the window's thread. */
let s_broken = false;
let s_nextId = 1;
let s_inFlight: {
id: number;
resolve: (aResult: BOARD_3D_LAYERS_RESULT | null) => void;
report: (aText: string) => void;
} | null = null;
/** Whether the layers can be built off the window's thread here (not under test, say). */
export function Board3dLayersJobAvailable(): boolean {
return !s_broken && typeof Worker !== 'undefined';
}
function startWorker(): Worker | null {
try {
const worker = new Worker(new URL('./board_3d_layers_job.ts', import.meta.url), {
type: 'module',
});
worker.onmessage = (e: MessageEvent<BOARD_3D_LAYERS_MESSAGE>): void => {
const job = s_inFlight;
if (!job || job.id !== e.data.id) return;
if (e.data.t === 'report') {
job.report(e.data.text);
return;
}
s_inFlight = null;
if (e.data.t === 'done') {
job.resolve({ built: e.data.built, tris: e.data.tris });
} else {
console.error('3D layer job:', e.data.message);
job.resolve(null);
}
};
// A worker that dies answers its job as a failure, and the scene builds here from now on.
worker.onerror = (e: ErrorEvent): void => {
console.error('3D layer job failed:', e.message || 'could not load');
s_broken = true;
s_worker = null;
s_inFlight?.resolve(null);
s_inFlight = null;
};
return worker;
} catch {
s_broken = true;
return null;
}
}
/**
* Build \a aBoard's 3D layers on the worker. A job still running when another is asked for is
* dropped with its worker - only the newest reload is ever shown - and answers null, as does a
* job that failed; null also when \a aAbort turns true while the board's text is written.
*/
export async function RunBoard3dLayersJob(
aBoard: BOARD,
aBbox: Box,
aOpts: Omit<Layer3dOptions, 'report'>,
aReport: (aText: string) => void,
aAbort: () => boolean,
): Promise<BOARD_3D_LAYERS_RESULT | null> {
const boardText = await FormatBoardAsync(
aBoard,
() => new Promise((r) => setTimeout(r, 0)),
aAbort,
undefined,
undefined,
CTL_FOR_BOARD | CTL_ENUMERATE_LAYERS,
);
if (boardText === null || aAbort()) return null;
if (s_inFlight) {
s_inFlight.resolve(null);
s_inFlight = null;
s_worker?.terminate();
s_worker = null;
}
s_worker ??= startWorker();
const worker = s_worker;
if (!worker) return null;
const id = s_nextId++;
return new Promise((resolve) => {
s_inFlight = { id, resolve, report: aReport };
worker.postMessage({
id,
boardText,
bbox: aBbox,
opts: aOpts,
} satisfies BOARD_3D_LAYERS_REQUEST);
});
}
// ---------------------------------------------------------------------------------------------
// The worker's half.
// ---------------------------------------------------------------------------------------------
interface WorkerScope {
postMessage(aMessage: BOARD_3D_LAYERS_MESSAGE, aTransfer?: Transferable[]): void;
onmessage: ((e: MessageEvent<BOARD_3D_LAYERS_REQUEST>) => void) | null;
}
const g = globalThis as unknown as { WorkerGlobalScope?: unknown };
if (g.WorkerGlobalScope !== undefined) {
const scope = globalThis as unknown as WorkerScope;
const codec = EMBEDDED_FILES.InitCodec();
/** The last board parsed, by its text: a reload that only shows or hides a layer reuses it. */
let last: { text: string; board: BOARD } | null = null;
scope.onmessage = async (e: MessageEvent<BOARD_3D_LAYERS_REQUEST>): Promise<void> => {
const { id, boardText, bbox, opts } = e.data;
try {
await codec;
if (last?.text !== boardText) last = { text: boardText, board: ParseBoard(boardText) };
const built = buildBoard3dLayers(last.board, bbox, {
...opts,
report: (text) => scope.postMessage({ id, t: 'report', text }),
});
const tris: (Uint32Array | null)[] = [];
forEachPolygonList(built, (list) => {
for (const poly of list) tris.push(TriangulatePolygon(poly));
});
scope.postMessage(
{ id, t: 'done', built, tris },
tris.filter((t): t is Uint32Array => t !== null).map((t) => t.buffer),
);
} catch (err) {
scope.postMessage({
id,
t: 'error',
message: err instanceof Error ? (err.stack ?? err.message) : String(err),
});
}
};
}
+242
View File
@@ -0,0 +1,242 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `BOARD_ADAPTER`'s stackup colours (`3d-viewer/3d_canvas/board_adapter.cpp`)
* — the bridge between the Physical Stackup page's Color column and what the
* 3D view actually paints.
*
* Two halves, both upstream's:
*
* - the five static `CUSTOM_COLORS_LIST`s built in the constructor
* (`:160-208`), name to RGBA. They are **data**: the names are the strings
* the Board Setup Color combo stores into the `.kicad_pcb`, so they are not
* ours to rename, and the alpha carries real meaning (a solder mask is 0.83,
* a silkscreen 1.0);
* - `GetLayerColors()`'s `if( m_Cfg->m_UseStackupColors && m_board )` block
* (`:654-745`), which walks the stackup and overrides silkscreen, mask,
* board body and surface finish.
*
* Note these are NOT the tables the Board Setup page's Color dropdown lists:
* that combo uses `GetStandardColors()` from `stackup_predefined_prms.cpp`,
* whose job is the `.gbrjob` name set. The two overlap by name and differ in
* value, which is exactly why the mapping has to be done by name, here, once —
* `pcb3d.ts` previously hardcoded a single mask green, a single silk white and
* a single FR4 brown, so the Color column changed nothing in 3D.
*/
import type { Color4d } from '@ziroeda/common/gal/color4d.js';
import { parseColor4d, COLOR4D_UNSPECIFIED } from '@ziroeda/common/gal/color4d.js';
import { PCB_LAYER_ID } from '@ziroeda/common/layer_id.js';
import {
type BOARD_STACKUP,
BOARD_STACKUP_ITEM_TYPE,
} from '@ziroeda/pcbnew/board_stackup_manager/board_stackup.js';
/** `ADD_COLOR( list, r, g, b, a, name )` — 0-255 channels, 0-1 alpha. */
const rgba = (r: number, g: number, b: number, a: number): Color4d => ({
r: r / 255,
g: g / 255,
b: b / 255,
a,
});
/**
* `COLOR4D::Mix( aColor, aFactor )` (`include/gal/color4d.h:296-304`) — note
* the alpha is **this** colour's, not the mix's, which is what makes the
* dielectric body accumulation below behave.
*/
export function mix(self: Color4d, other: Color4d, factor: number): Color4d {
return {
r: other.r * (1 - factor) + self.r * factor,
g: other.g * (1 - factor) + self.g * factor,
b: other.b * (1 - factor) + self.b * factor,
a: self.a,
};
}
// [data] `g_SilkColors` (`board_adapter.cpp:164-171`). The first entry is
// `NotSpecifiedPrm()`, i.e. the "Not specified" name, and it is White.
export const SILK_COLORS: Readonly<Record<string, Color4d>> = {
'Not specified': rgba(245, 245, 245, 1.0), // [data] board_adapter.cpp:164-171
Green: rgba(20, 51, 36, 1.0), // [data] board_adapter.cpp:164-171
Red: rgba(181, 19, 21, 1.0), // [data] board_adapter.cpp:164-171
Blue: rgba(2, 59, 162, 1.0), // [data] board_adapter.cpp:164-171
Black: rgba(11, 11, 11, 1.0), // [data] board_adapter.cpp:164-171
White: rgba(245, 245, 245, 1.0), // [data] board_adapter.cpp:164-171
Purple: rgba(32, 2, 53, 1.0), // [data] board_adapter.cpp:164-171
Yellow: rgba(194, 195, 0, 1.0), // [data] board_adapter.cpp:164-171
};
// [data] `g_MaskColors` (`:173-188`). "Not specified" is Green here, not White.
export const MASK_COLORS: Readonly<Record<string, Color4d>> = {
'Not specified': rgba(20, 51, 36, 0.83), // [data] board_adapter.cpp:173-188
Green: rgba(20, 51, 36, 0.83), // [data] board_adapter.cpp:173-188
'Light Green': rgba(91, 168, 12, 0.83), // [data] board_adapter.cpp:173-188
'Saturated Green': rgba(13, 104, 11, 0.83), // [data] board_adapter.cpp:173-188
Red: rgba(181, 19, 21, 0.83), // [data] board_adapter.cpp:173-188
'Light Red': rgba(210, 40, 14, 0.83), // [data] board_adapter.cpp:173-188
'Red/Orange': rgba(239, 53, 41, 0.83), // [data] board_adapter.cpp:173-188
Blue: rgba(2, 59, 162, 0.83), // [data] board_adapter.cpp:173-188
'Light Blue 1': rgba(54, 79, 116, 0.83), // [data] board_adapter.cpp:173-188
'Light Blue 2': rgba(61, 85, 130, 0.83), // [data] board_adapter.cpp:173-188
'Green/Blue': rgba(21, 70, 80, 0.83), // [data] board_adapter.cpp:173-188
Black: rgba(11, 11, 11, 0.83), // [data] board_adapter.cpp:173-188
White: rgba(245, 245, 245, 0.83), // [data] board_adapter.cpp:173-188
Purple: rgba(32, 2, 53, 0.83), // [data] board_adapter.cpp:173-188
'Light Purple': rgba(119, 31, 91, 0.83), // [data] board_adapter.cpp:173-188
Yellow: rgba(194, 195, 0, 0.83), // [data] board_adapter.cpp:173-188
};
// [data] `g_PasteColors` (`:190-192`).
export const PASTE_COLORS: Readonly<Record<string, Color4d>> = {
Grey: rgba(128, 128, 128, 1.0), // [data] board_adapter.cpp:190-192
'Dark Grey': rgba(90, 90, 90, 1.0), // [data] board_adapter.cpp:190-192
Silver: rgba(213, 213, 213, 1.0), // [data] board_adapter.cpp:190-192
};
// [data] `g_FinishColors` (`:194-197`).
export const FINISH_COLORS: Readonly<Record<string, Color4d>> = {
Copper: rgba(184, 115, 50, 1.0), // [data] board_adapter.cpp:194-197
Gold: rgba(178, 156, 0, 1.0), // [data] board_adapter.cpp:194-197
Silver: rgba(213, 213, 213, 1.0), // [data] board_adapter.cpp:194-197
Tin: rgba(160, 160, 160, 1.0), // [data] board_adapter.cpp:194-197
};
// [data] `g_BoardColors` (`:199-207`).
export const BOARD_COLORS: Readonly<Record<string, Color4d>> = {
'FR4 natural, dark': rgba(51, 43, 22, 0.83), // [data] board_adapter.cpp:199-207
'FR4 natural': rgba(109, 116, 75, 0.83), // [data] board_adapter.cpp:199-207
'PTFE natural': rgba(252, 252, 250, 0.9), // [data] board_adapter.cpp:199-207
Polyimide: rgba(205, 130, 0, 0.68), // [data] board_adapter.cpp:199-207
'Phenolic natural': rgba(92, 17, 6, 0.9), // [data] board_adapter.cpp:199-207
'Brown 1': rgba(146, 99, 47, 0.83), // [data] board_adapter.cpp:199-207
'Brown 2': rgba(160, 123, 54, 0.83), // [data] board_adapter.cpp:199-207
'Brown 3': rgba(146, 99, 47, 0.83), // [data] board_adapter.cpp:199-207
Aluminum: rgba(213, 213, 213, 1.0), // [data] board_adapter.cpp:199-207
};
// [data] the `g_Default*` fallbacks (`:210-215`), used when the stackup says
// nothing — these are already 0-1 upstream, so they are transcribed as such.
export const DEFAULT_SILKSCREEN: Color4d = { r: 0.94, g: 0.94, b: 0.94, a: 1.0 };
export const DEFAULT_SOLDERMASK: Color4d = { r: 0.08, g: 0.2, b: 0.14, a: 0.83 };
export const DEFAULT_SOLDERPASTE: Color4d = { r: 0.5, g: 0.5, b: 0.5, a: 1.0 };
export const DEFAULT_SURFACE_FINISH: Color4d = { r: 0.75, g: 0.61, b: 0.23, a: 1.0 };
/** `g_DefaultBoardBody` (board_adapter.cpp:152). */
export const DEFAULT_BOARD_BODY: Color4d = { r: 0.43, g: 0.45, b: 0.3, a: 0.9 };
/** `g_DefaultBackgroundTop` / `g_DefaultBackgroundBot` (board_adapter.cpp:146-147). */
export const DEFAULT_BACKGROUND_TOP: Color4d = { r: 0.8, g: 0.8, b: 0.9, a: 1.0 };
export const DEFAULT_BACKGROUND_BOT: Color4d = { r: 0.4, g: 0.4, b: 0.5, a: 1.0 };
/** `g_DefaultComments` — User.Drawings and User.Comments (board_adapter.cpp:153). */
export const DEFAULT_COMMENTS: Color4d = { r: 0.85, g: 0.85, b: 0.85, a: 1.0 };
/** `g_DefaultECOs` — Eco1.User and Eco2.User (board_adapter.cpp:154). */
export const DEFAULT_ECOS: Color4d = { r: 0.7, g: 0.1, b: 0.1, a: 1.0 };
/**
* `KIGFX::COLOR4D()`, default-constructed (`include/gal/color4d.h:108-114`):
* OPAQUE black. Its comment says "creates the Color 0,0,0,0", but the
* initialiser list sets `a( 1.0 )`, and that is what a miss below returns.
*/
const COLOR4D_DEFAULT: Color4d = { r: 0, g: 0, b: 0, a: 1.0 };
/**
* `findColor( aColorName, aColorSet )` (`board_adapter.cpp:661-679`): a name
* beginning `#` is a literal `COLOR4D( aColorName )`, otherwise it is looked up
* by name, and a miss returns a default-constructed COLOR4D - opaque black.
*
* Observable: a dielectric whose colour is "Not specified", which is what
* BOARD_STACKUP_ITEM's constructor gives one and what a file without `(color
* ...)` keeps, misses `g_BoardColors` and makes the board body black.
* `kicad-cli pcb render --use-board-stackup-colors` (10.0.6) draws such a
* board's edge at (15,13,10) where "FR4 natural" draws it at (89,95,61).
*/
export function findColor(aName: string, aSet: Readonly<Record<string, Color4d>>): Color4d {
if (aName.startsWith('#')) return parseColor4d(aName);
return aSet[aName] ?? COLOR4D_DEFAULT;
}
/** What the stackup has to say about the 3D view's materials. */
export interface StackupColors {
silkTop: Color4d;
silkBottom: Color4d;
maskTop: Color4d;
maskBottom: Color4d;
/** LAYER_3D_BOARD — the accumulated dielectric body, if any dielectric set one. */
body?: Color4d;
/** LAYER_3D_COPPER_TOP, when the finish names one. Bottom copies top. */
copper?: Color4d;
}
const isUnspecified = (c: Color4d): boolean => c.r === 0 && c.g === 0 && c.b === 0 && c.a === 0;
/**
* `GetLayerColors()`'s stackup block (`board_adapter.cpp:654-745`), whole,
* over the board's own `BOARD_STACKUP`.
*
* The dielectric accumulation is the subtle part and is transcribed rather than
* simplified: each dielectric layer is mixed into the running body colour by
* `1.0 - layerColor.a`, and then the body's own alpha grows by
* `( 1.0 - bodyColor.a ) * layerColor.a / 2`. A single dielectric therefore
* lands on its own colour, and a thick multi-dielectric stack darkens.
*/
export function stackupColors(aStackup: BOARD_STACKUP): StackupColors {
const out: StackupColors = {
silkTop: DEFAULT_SILKSCREEN,
silkBottom: DEFAULT_SILKSCREEN,
maskTop: DEFAULT_SOLDERMASK,
maskBottom: DEFAULT_SOLDERMASK,
};
let bodyColor: Color4d = COLOR4D_UNSPECIFIED;
for (const stackupItem of aStackup.GetList()) {
const colorName = stackupItem.GetColor();
switch (stackupItem.GetType()) {
case BOARD_STACKUP_ITEM_TYPE.BS_ITEM_TYPE_SILKSCREEN:
if (stackupItem.GetBrdLayerId() === PCB_LAYER_ID.F_SilkS)
out.silkTop = findColor(colorName, SILK_COLORS);
else out.silkBottom = findColor(colorName, SILK_COLORS);
break;
case BOARD_STACKUP_ITEM_TYPE.BS_ITEM_TYPE_SOLDERMASK:
if (stackupItem.GetBrdLayerId() === PCB_LAYER_ID.F_Mask)
out.maskTop = findColor(colorName, MASK_COLORS);
else out.maskBottom = findColor(colorName, MASK_COLORS);
break;
case BOARD_STACKUP_ITEM_TYPE.BS_ITEM_TYPE_DIELECTRIC: {
const layerColor = findColor(colorName, BOARD_COLORS);
if (isUnspecified(bodyColor)) bodyColor = layerColor;
else bodyColor = mix(bodyColor, layerColor, 1.0 - layerColor.a);
bodyColor = { ...bodyColor, a: bodyColor.a + ((1.0 - bodyColor.a) * layerColor.a) / 2 };
break;
}
default:
break;
}
}
if (!isUnspecified(bodyColor)) out.body = bodyColor;
const finishName = aStackup.m_FinishType;
if (finishName.endsWith('OSP')) out.copper = findColor('Copper', FINISH_COLORS);
else if (finishName.endsWith('IG') || finishName.endsWith('gold'))
out.copper = findColor('Gold', FINISH_COLORS);
else if (
finishName.startsWith('HAL') ||
finishName.startsWith('HASL') ||
finishName.endsWith('tin') ||
finishName.endsWith('nickel')
)
out.copper = findColor('Tin', FINISH_COLORS);
else if (finishName.endsWith('silver')) out.copper = findColor('Silver', FINISH_COLORS);
return out;
}
File diff suppressed because it is too large Load Diff
+442
View File
@@ -0,0 +1,442 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* Load and place footprint 3D models in the three.js scene, replicating KiCad's
* exact placement matrix (render_3d_opengl.cpp get3dModelsFromFootprint):
*
* footprint: translate(x·s, -y·s, GetFootprintZPos(flipped)) · rotateZ(orientation)
* · [if back: rotateY(π)·rotateZ(π)] · scale(BiuTo3dUnits · IU_PER_MM)
* per model: translate(offset) · rotateZ(-rz)·rotateY(-ry)·rotateX(-rx)
* · scale(scale)
*
* KiCad's model space is millimetres (modelunit_to_3d_units_factor =
* BiuTo3dUnits · IU_PER_MM), and `(offset …)` is millimetres applied in that
* space. Each loader normalises geometry into mm exactly as KiCad's plugins
* do:
* - `.glb` (our hosted library, converted from the KiCad 10 STEP set) and
* project STEP/IGES models are native mm, loaded raw;
* - `.wrl` is authored in 0.1-inch units, scaled ×2.54 at load, unless the
* file carries its own top-level scale transform (WRL2BASE's
* "ApplyUnitConversion" rule in plugins/3d/vrml).
*
* Materials: `MODEL_3D` draws every material group through `OglSetMaterial`
* under `glColorMaterial( GL_AMBIENT_AND_DIFFUSE )` (3d_model.cpp:479-528),
* so what a model brings is its diffuse (as ambient too), its specular, its
* shininess and its transparency — the `SMATERIAL` the loader filled. The
* three.js material each loader produced is read back into that struct and
* replaced by the fixed-function material the caller hands out; an opaque
* group goes in the opaque pass, a transparent one (or any group of a model
* with `(opacity …)` below 1) in the back-to-front pass after the mask.
*
* Models load async and are cached per source; a part used many times is
* fetched once and cloned.
*/
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { VRMLLoader } from 'three/addons/loaders/VRMLLoader.js';
import type { BOARD } from '@ziroeda/pcbnew/board.js';
import type { FOOTPRINT, FP_3DMODEL } from '@ziroeda/pcbnew/footprint.js';
import { PROJECT_PCB } from '@ziroeda/pcbnew/project_pcb.js';
import { PgmOrNull } from '@ziroeda/common/pgm_base.js';
import { wxFindMount, wxMountFileSystem, wxReadFileSync } from '@ziroeda/wx/filefn.js';
import { loadCadModel } from './loadmodel.js';
import {
HostedLibraryMount,
mountHostedLibrary,
PROJECT_FILES_MOUNT,
} from './3d_cache/3d_cache.js';
export {
LoadHosted3DCatalog,
mountHostedLibrary,
PROJECT_FILES_MOUNT,
SetHosted3DCatalog,
} from './3d_cache/3d_cache.js';
import { stepFaceMaterial, type SMaterial, type Vec3 } from './gl_fixed_function.js';
const VRML_UNIT_MM = 2.54; // legacy VRML model unit = 0.1 inch (WRL2BASE)
/** The placement frame `get3dModelsFromFootprint` builds in, 3D units. */
export interface ModelFrame {
/** `BiuTo3dUnits()`. */
scale: number;
/** `GetFootprintZPos( false )` — the F.Paste top. */
zTopFront: number;
/** `GetFootprintZPos( true )` — the B.Paste bottom. */
zTopBack: number;
/** `modelunit_to_3d_units_factor = BiuTo3dUnits() · UNITS3D_TO_UNITSPCB`. */
modelUnitToWorld: number;
}
/** A file bundled with the uploaded project (VRML/STEP sources are ASCII). */
export interface ProjectFile {
name: string;
text: string;
}
const rotZ = (r: number): THREE.Matrix4 => new THREE.Matrix4().makeRotationZ(r);
const rotY = (r: number): THREE.Matrix4 => new THREE.Matrix4().makeRotationY(r);
const rotX = (r: number): THREE.Matrix4 => new THREE.Matrix4().makeRotationX(r);
const deg = (d: number): number => (d * Math.PI) / 180;
/** KiCad placement matrix for one footprint model, in 3D units. */
export function modelMatrix(fp: FOOTPRINT, model: FP_3DMODEL, frame: ModelFrame): THREE.Matrix4 {
const flipped = fp.IsFlipped();
const pos = fp.GetPosition();
const m = new THREE.Matrix4().makeTranslation(
pos.x * frame.scale,
-pos.y * frame.scale, // KiCad flips Y into the 3D frame
flipped ? frame.zTopBack : frame.zTopFront,
);
m.multiply(rotZ(deg(fp.GetOrientation().AsDegrees())));
if (flipped) {
m.multiply(rotY(Math.PI));
m.multiply(rotZ(Math.PI));
}
m.multiply(
new THREE.Matrix4().makeScale(
frame.modelUnitToWorld,
frame.modelUnitToWorld,
frame.modelUnitToWorld,
),
);
m.multiply(
new THREE.Matrix4().makeTranslation(model.m_Offset.x, model.m_Offset.y, model.m_Offset.z),
);
m.multiply(rotZ(deg(-model.m_Rotation.z)));
m.multiply(rotY(deg(-model.m_Rotation.y)));
m.multiply(rotX(deg(-model.m_Rotation.x)));
m.multiply(new THREE.Matrix4().makeScale(model.m_Scale.x, model.m_Scale.y, model.m_Scale.z));
return m;
}
/**
* VRML unit conversion (WRL2BASE::SetApplyUnitConversion): legacy `.wrl`
* models are 0.1-inch units → ×2.54 into mm, but a file that already carries a
* top-level scale transform is self-converting and is left alone.
*/
function vrmlIntoMm(o: THREE.Object3D): THREE.Object3D {
const selfScaled = [o, ...o.children].some(
(c) => c.scale.x !== 1 || c.scale.y !== 1 || c.scale.z !== 1,
);
const wrapper = new THREE.Group();
wrapper.add(o);
if (!selfScaled) o.scale.setScalar(VRML_UNIT_MM);
return wrapper;
}
const extOf = (name: string): string => name.split('.').pop()?.toLowerCase() ?? '';
/** Library files are hosted as `.glb`; the path keeps its KiCad name. */
const hostedExt = (rel: string): string =>
rel.replace(/\.(wrl|wrz|step|stp|stpz|x3d|iges|igs)$/i, '.glb');
/** Join base URL + relative path, percent-encoding each segment (library
* models legitimately contain spaces, e.g. "M.2 M Key socket"). */
const joinUrl = (base: string, rel: string): string =>
`${base.replace(/\/+$/, '')}/${rel
.replace(/^\/+/, '')
.split('/')
.map(encodeURIComponent)
.join('/')}`;
/**
* The `SMATERIAL` a loader's three.js material stands for.
*
* Colours come back sRGB-ENCODED: KiCad's OCE loader reads a STEP colour with
* `Quantity_TOC_sRGB` and its VRML parser takes the file's numbers as they
* are, and both light those numbers raw. three.js's loaders converted them
* into its linear working space, so `getRGB( …, SRGBColorSpace )` is the
* exact inverse — it hands back the file's numbers.
*/
export function smaterialOf(m: THREE.Material): SMaterial {
const srgb = (c: THREE.Color): Vec3 => {
const t = { r: 0, g: 0, b: 0 };
c.getRGB(t, THREE.SRGBColorSpace);
return [t.r, t.g, t.b];
};
const opacity = m.transparent ? m.opacity : 1;
if (m instanceof THREE.MeshPhongMaterial) {
// VRML: `Material { diffuseColor specularColor emissiveColor shininess transparency }`
// (plugins/3d/vrml/v2/vrml2_material.cpp:285-300), shininess in VRML's 0..1.
return {
ambient: srgb(m.color),
diffuse: srgb(m.color),
specular: srgb(m.specular),
emissive: srgb(m.emissive),
shininess: m.shininess,
transparency: 1 - opacity,
};
}
// STEP (a hosted .glb, or a project file through OCCT): one colour per
// BREP face, the OCE loader's fixed specular/shininess around it.
const color =
'color' in m && m.color instanceof THREE.Color ? m.color : new THREE.Color(0.6, 0.6, 0.6);
return stepFaceMaterial(srgb(color), opacity, true);
}
export interface ComponentRenderHooks {
/**
* `OglSetMaterial( mat, opacity, aUseSelectedMaterial )` in the current
* `MATERIAL_MODE`. Both materials are built up front and parked on the
* mesh (`userData.normalMat` / `userData.selectedMat`) so a rollover or a
* cross-probed selection is a swap, not a rebuild.
*/
material: (
m: SMaterial,
opacity: number,
transparentPass: boolean,
selected: boolean,
) => THREE.Material;
/** `renderOpaqueModels` / `renderTransparentModels` slots. */
opaqueOrder: number;
transparentOrder: number;
/** `BOARD_ADAPTER::IsFootprintShown`. */
showFootprint: (fp: FOOTPRINT) => boolean;
}
/**
* Load every footprint's 3D models and add them to `parent`. `libBase` is
* where the hosted library lives (a `.glb` URL prefix); `projectFiles` carries
* the uploaded project's own files so ${KIPRJMOD}/relative references load
* exactly as KiCad loads them from the project directory.
*/
/**
* `S3D_CACHE`: a loaded model outlives the scene it was loaded for.
* `RENDER_3D_OPENGL::reload` calls `load3dModels`, which asks the cache and
* only reads files it has not seen — so a reload (an appearance toggle, a
* board edit) never re-fetches or re-tessellates. Keyed by URL for the
* hosted library and by name + size for a project file.
*/
const modelCache = new Map<string, Promise<THREE.Object3D | null>>();
export interface MountedComponents {
dispose: () => void;
/** Every model settled (loaded or failed) — `load3dModels` has returned. */
ready: Promise<void>;
}
export function mountComponents(
parent: THREE.Object3D,
board: BOARD,
frame: ModelFrame,
libBase: string,
projectFiles?: ProjectFile[],
onChange?: () => void,
/**
* `EDA_3D_VIEWER_SETTINGS::m_Render.show_model_bbox` — Preferences >
* 3D Viewer > Realtime Renderer's "Show model bounding boxes".
*
* `RENDER_3D_OPENGL::renderModel` draws each model's outer bounding box in
* green (`MakeBbox( m_model_bbox, …, { 0, 1, 0, 1 } )`, 3d_model.cpp:247).
*/
showModelBbox?: boolean,
/**
* `load3dModels( REPORTER* aStatusReporter )`: "Loading %s..." with the
* short file name of each model as it is fetched (create_scene.cpp:1656-
* 1662). Upstream loads one file at a time, so the field names the one in
* hand; here the fetches overlap, so the field names one still in flight
* and moves on as each lands.
*/
report?: (text: string) => void,
hooks?: ComponentRenderHooks,
): MountedComponents {
const vrmlLoader = new VRMLLoader();
const gltfLoader = new GLTFLoader();
const cache = modelCache;
const added: THREE.Object3D[] = [];
const pendingLoads: Promise<unknown>[] = [];
const disposables: { dispose(): void }[] = [];
let cancelled = false;
const enc = new TextEncoder();
// The project's files where KiCad would find them, for as long as this scene
// lives; the library where the install puts it.
mountHostedLibrary();
const prj = PgmOrNull()?.GetSettingsManager().Prj();
const projectDir = prj?.GetProjectPath() ?? '';
const projectMount = new PROJECT_FILES_MOUNT(new Set(projectFiles?.map((f) => f.name) ?? []));
const unmountProject =
projectFiles && projectDir.startsWith('/') ? wxMountFileSystem(projectDir, projectMount) : null;
const resolver = PROJECT_PCB.Get3DFilenameResolver();
// wxFileName( fp_model.m_Filename ).GetFullName(): the name and extension
const inFlight = new Set<string>();
const reportInFlight = (): void => {
const next = inFlight.values().next();
if (!next.done) report?.(`Loading ${next.value}...`);
};
const loadUrl = (url: string): Promise<THREE.Object3D | null> =>
/\.glb$/i.test(url)
? gltfLoader
.loadAsync(url)
.then((g) => g.scene as THREE.Object3D)
.catch(() => null)
: vrmlLoader
.loadAsync(url)
.then((o) => vrmlIntoMm(o))
.catch(() => null);
// Dispatch a project file by extension, mirroring KiCad's 3d plugin registry
// (vrml plugin for .wrl, the OCC kernel for STEP/IGES). Compressed variants
// (.wrz/.stpz) and .x3d are not loadable from text-ingested projects yet.
const loadProjectFile = (name: string): Promise<THREE.Object3D | null> => {
const file = projectFiles?.find((f) => f.name === name);
if (!file) return Promise.resolve(null);
switch (extOf(name)) {
case 'wrl':
return Promise.resolve().then(() => {
try {
return vrmlIntoMm(vrmlLoader.parse(file.text, name) as THREE.Object3D);
} catch {
return null;
}
});
case 'step':
case 'stp':
return loadCadModel(enc.encode(file.text), 'step');
case 'iges':
case 'igs':
return loadCadModel(enc.encode(file.text), 'iges');
default:
return Promise.resolve(null);
}
};
// A file read by path (an embedded model in the temp directory): the same
// plugin dispatch, from bytes.
const loadBytes = (path: string, bytes: Uint8Array): Promise<THREE.Object3D | null> => {
switch (extOf(path)) {
case 'wrl':
return Promise.resolve().then(() => {
try {
const text = new TextDecoder().decode(bytes);
return vrmlIntoMm(vrmlLoader.parse(text, path) as THREE.Object3D);
} catch {
return null;
}
});
case 'step':
case 'stp':
return loadCadModel(bytes, 'step');
case 'iges':
case 'igs':
return loadCadModel(bytes, 'iges');
default:
return Promise.resolve(null);
}
};
board.Footprints().forEach((fp, fpIndex) => {
if (hooks && !hooks.showFootprint(fp)) return;
for (const model of fp.Models()) {
if (!model.m_Show || !model.m_Filename) continue;
// "Loading %s..." for every shown model, before it is resolved (create_scene.cpp:1663-
// 1670): one that is not found is named too.
const fullName = model.m_Filename.slice(model.m_Filename.lastIndexOf('/') + 1);
report?.(`Loading ${fullName}...`);
// S3D_CACHE::load -> ResolvePath( aModelFile, aBasePath, aEmbeddedFilesStack ).
// The footprint's library path is not known here; nor are embedded files
// (the plain board view does not carry them).
const full = resolver.ResolvePath(model.m_Filename, '', []);
if (full === '') continue;
const where = wxFindMount(full);
if (!where) continue;
let key: string;
let load: () => Promise<THREE.Object3D | null>;
if (where.mount === HostedLibraryMount()) {
const url = joinUrl(libBase, hostedExt(where.rel));
key = url;
load = () => loadUrl(url);
} else if (where.mount === projectMount) {
const name = where.rel;
key = `project:${name}:${projectFiles?.find((f) => f.name === name)?.text.length ?? 0}`;
load = () => loadProjectFile(name);
} else {
// An embedded file written to the temp directory (GetTemporaryFileName).
const bytes = wxReadFileSync(full);
if (!bytes) continue;
key = `file:${full}`;
load = () => loadBytes(full, bytes);
}
let p = cache.get(key);
if (!p) {
p = load();
cache.set(key, p);
inFlight.add(fullName);
void p.finally(() => {
inFlight.delete(fullName);
reportInFlight();
});
}
pendingLoads.push(p);
const matrix = modelMatrix(fp, model, frame);
// `sM.m_Opacity`: 1 keeps the model in the opaque pass
const opacity = model.m_Opacity;
const opaque = opacity >= 1;
void p.then((obj) => {
if (cancelled || !obj) return;
const inst = obj.clone();
inst.matrixAutoUpdate = false;
inst.matrix.copy(matrix);
inst.matrixWorldNeedsUpdate = true;
// the BOARD_ITEM a ray-hit on this model reports (addModels' aBoardItem)
inst.userData.footprint = fpIndex;
if (hooks) {
inst.traverse((child) => {
if (!(child instanceof THREE.Mesh)) return;
const src = child.material as THREE.Material;
const sm = smaterialOf(src);
// MODEL_3D::Draw: a material with transparency goes to the
// transparent pass; a model with opacity < 1 goes there whole.
const transparentPass = !opaque || sm.transparency > 1.1920929e-7;
const op = transparentPass ? opacity : 1;
const mat = hooks.material(sm, op, transparentPass, false);
const sel = hooks.material(sm, op, transparentPass, true);
// glEnable( GL_CULL_FACE ) throughout — but a VRML file's winding
// is its own affair (`solid`/`ccw`), and three.js's loader keeps
// it two-sided; STEP faces come oriented.
if (src.side === THREE.DoubleSide) {
mat.side = THREE.DoubleSide;
sel.side = THREE.DoubleSide;
}
child.material = mat;
child.userData.normalMat = mat;
child.userData.selectedMat = sel;
child.renderOrder = transparentPass ? hooks.transparentOrder : hooks.opaqueOrder;
disposables.push(mat, sel);
});
} else if (opacity < 1) {
inst.traverse((child) => {
if (child instanceof THREE.Mesh) {
const m = (child.material as THREE.Material).clone();
m.transparent = true;
m.opacity *= opacity;
child.material = m;
}
});
}
parent.add(inst);
added.push(inst);
if (showModelBbox) {
const helper = new THREE.Box3Helper(new THREE.Box3().setFromObject(inst), 0x00ff00);
parent.add(helper);
added.push(helper);
}
onChange?.();
});
}
});
return {
dispose: () => {
cancelled = true;
unmountProject?.();
for (const o of added) parent.remove(o);
for (const d of disposables) d.dispose();
},
ready: Promise.allSettled(pendingLoads).then(() => undefined),
};
}
@@ -0,0 +1,189 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `APPEARANCE_CONTROLS_3D` (3d-viewer/dialogs/appearance_controls_3D_base.cpp
* and appearance_controls_3D.cpp) — the 3D viewer's right-hand pane.
*
* The sizer tree, top to bottom (`_base.cpp:12-52`):
*
* m_panelLayers
* m_windowLayers (wxScrolledCanvas, wxLEFT|wxRIGHT|wxTOP 5) the rows
* "Use board stackup colors" (wxEXPAND|wxTOP|wxLEFT|wxRIGHT, 5)
* "Use PCB editor copper colors" (wxEXPAND|wxALL, 5)
* bBottomMargin (wxTOP|wxBOTTOM 2)
* wxStaticLine (wxBOTTOM|wxLEFT|wxRIGHT, 3)
* Presets label + wxChoice (wxTOP|wxRIGHT|wxLEFT 5; choice wxTOP 5)
* 2px spacer
* Viewports label + wxChoice (wxBOTTOM|wxRIGHT|wxLEFT 5; label wxTOP 5; choice wxTOP 5)
*
* A row (`rebuildLayers`, `.cpp:468-522`) is `[COLOR_SWATCH | swatch-width
* spacer] 5 [BITMAP_TOGGLE eye | spacer] 5 [label]`, the row itself
* `wxEXPAND|wxLEFT|wxRIGHT 5` with a 2px spacer after it; an `RR()` spacer
* is `m_pointSize` tall. The labels for the board layers are the BOARD's
* layer names, `GetBoard()->GetLayerName( boardLayer )`.
*
* Every widget here is the shared one the PCB editor's pane already draws
* — the row rules, the eye, the swatch, the choice — so this file states no
* colour, font or size of its own; what it states is which rows exist and
* what each control does, and that comes from `viewer3d_appearance.ts`.
*
* Not ported: the swatch's read-only callback, which upstream shows an
* infobar ("Uncheck 'Use board stackup colors' to allow color editing.") —
* `ColorSwatch` has no read-only mode, so a locked swatch is disabled and
* says so in its tooltip; and the Ctrl+Tab / Shift+Tab cycling popups.
*/
import type { JSX } from 'react';
import type { Color4d } from '@ziroeda/common/gal/color4d.js';
import type { BOARD } from '@ziroeda/pcbnew/board.js';
import { LSET } from '@ziroeda/common/lset.js';
import { Check } from '@ziroeda/common/dialogs/pref_controls.js';
import { ColorSwatch } from '@ziroeda/common/widgets/color_swatch.js';
import { Combo } from '@ziroeda/wx/combobox.js';
import { BitmapToggle } from '@ziroeda/common/widgets/bitmap_toggle.js';
import { BITMAPS } from '@ziroeda/include/bitmaps/bitmaps_list.js';
import {
APPEARANCE_ROWS_3D,
COLORED_FLAGS,
IN_STACKUP_COLORS,
type Layer3dColors,
type Layer3dFlag,
pcbLayerOfFlag,
userFlagIndex,
} from '../viewer3d_appearance.js';
/** `COLOR4D::WHITE`, the `aBackground` every swatch of this pane is built with (`.cpp:475`). */
const SWATCH_BACKGROUND: Color4d = { r: 1, g: 1, b: 1, a: 1 };
export interface Appearance3DPanelProps {
board: BOARD;
/** `GetVisibleLayers()`. */
visible: ReadonlySet<Layer3dFlag>;
/** `GetLayerColors()`. */
colors: Layer3dColors;
/** `GetDefaultColors()` — the swatch dialog's "Reset to Default". */
defaultColors: Layer3dColors;
useStackupColors: boolean;
useBoardEditorCopperColors: boolean;
onToggleLayer: (layer: Layer3dFlag, visible: boolean) => void;
onColor: (layer: Layer3dFlag, color: Color4d) => void;
onUseStackupColors: (on: boolean) => void;
onUseBoardEditorCopperColors: (on: boolean) => void;
/** `m_cbLayerPresets`: its entries and the selected one. */
presetItems: readonly string[];
preset: string;
onPreset: (value: string) => void;
deletePresetDisabled: boolean;
/** `m_cbViewports`. */
viewportItems: readonly string[];
viewport: string;
onViewport: (value: string) => void;
deleteViewportDisabled: boolean;
}
export function Appearance3DPanel(p: Appearance3DPanelProps): JSX.Element {
// m_board->IsLayerEnabled( layer ), by name for the rows below.
const enabled = {
has: (aName: string): boolean => p.board.IsLayerEnabled(LSET.NameToLayer(aName)),
};
const layerLabel = (row: { label: string; id: Layer3dFlag }): string => {
const pcbLayer = pcbLayerOfFlag(row.id);
// m_frame->GetBoard()->GetLayerName( layer ): the board's name for it.
return pcbLayer ? p.board.GetLayerName(LSET.NameToLayer(pcbLayer)) : row.label;
};
return (
<div className="ze-appearance ze-appearance-3d">
{/* m_panelLayers: the scrolled rows on the lighter list ground
(`m_layerPanelColour`), then the two checkboxes below the scroll. */}
<div className="ze-appearance-3d-layers">
<div className="ze-panel-body ze-appearance-page page-layers ze-appearance-3d-rows">
{APPEARANCE_ROWS_3D.map((row, i) => {
// RR(): m_layersOuterSizer->AddSpacer( m_pointSize )
if (row === null) return <div key={`sp${i}`} className="ze-appearance-3d-sep" />;
// a User_N row only for a layer the board enables (`.cpp:534-538`)
const u = userFlagIndex(row.id);
if (u && !enabled.has(`User.${u}`)) return null;
const color = p.colors.get(row.id);
const hasColor = COLORED_FLAGS.includes(row.id) && color !== undefined;
const locked = p.useStackupColors && IN_STACKUP_COLORS.includes(row.id);
const isBackground =
row.id === 'LAYER_3D_BACKGROUND_TOP' || row.id === 'LAYER_3D_BACKGROUND_BOTTOM';
const on = p.visible.has(row.id);
const label = layerLabel(row);
return (
<div key={row.id} className="ze-layer-row" title={row.tooltip}>
{hasColor ? (
// COLOR_SWATCH( …, COLOR4D::WHITE, defaultColors[ layer ], SWATCH_SMALL )
<ColorSwatch
size="small"
color={color}
background={SWATCH_BACKGROUND}
defaultColor={p.defaultColors.get(row.id)}
label={`Set color for ${label}`}
disabled={locked}
onChange={(c) => p.onColor(row.id, c)}
/>
) : (
// sizer->AddSpacer( swatchWidth )
<span className="ze-layer-swatch ze-appearance-3d-swatch-gap" />
)}
{isBackground ? (
<span className="ze-layer-swatch ze-appearance-3d-swatch-gap" />
) : (
<BitmapToggle
checked={on}
checkedBitmap={BITMAPS.visibility}
uncheckedBitmap={BITMAPS.visibility_off}
tooltip={`Show or hide ${row.label.toLowerCase()}`}
onToggle={(checked) => p.onToggleLayer(row.id, checked)}
/>
)}
<span className="ze-ellipsis">{label}</span>
</div>
);
})}
</div>
<Check
label="Use board stackup colors"
checked={p.useStackupColors}
onChange={p.onUseStackupColors}
borders={['top']}
/>
<Check
label="Use PCB editor copper colors"
checked={p.useBoardEditorCopperColors}
onChange={p.onUseBoardEditorCopperColors}
title="Use the board editor layer colors for copper layers (realtime renderer only)"
borders={['top', 'bottom']}
/>
</div>
{/* bBottomMargin: the static line, then presets and viewports — the
same block the PCB pane draws, so its rules apply as they are. */}
<div className="ze-appearance-bottom ze-appearance-3d-bottom">
<div className="ze-info ze-inset">Presets (Ctrl+Tab):</div>
<Combo
ariaLabel="Presets"
value={p.preset}
options={p.presetItems.map((name) => ({
value: name,
label: name,
disabled: name === 'Delete preset...' && p.deletePresetDisabled,
}))}
onChange={p.onPreset}
/>
<div className="ze-info ze-inset ze-viewports-label">Viewports (Shift+Tab):</div>
<Combo
ariaLabel="Viewports"
value={p.viewport}
options={p.viewportItems.map((name) => ({
value: name,
label: name,
disabled: name === 'Delete viewport...' && p.deleteViewportDisabled,
}))}
onChange={p.onViewport}
/>
</div>
</div>
);
}
+506
View File
@@ -0,0 +1,506 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `RENDER_3D_OPENGL`'s lighting model, which is OpenGL 1.x fixed-function
* Gouraud shading and nothing more: three lights set up once in
* `init_lights()` (render_3d_opengl.cpp:400), an `SMATERIAL` per layer from
* `setupMaterials()` / `setLayerMaterial()`, `glColorMaterial(
* GL_AMBIENT_AND_DIFFUSE )` for the 3D models, and `OglSetMaterial()`
* (common_ogl/ogl_utils.cpp) pushing the five `glMaterial*` calls.
*
* There is no tone mapping, no environment, no sRGB conversion on the way
* out: the material numbers go through the GL 1.x lighting equation, are
* clamped to 0..1 per VERTEX, interpolated, and land in the framebuffer as
* they are. The shader below is that equation, so the same numbers give the
* same pixels. The pure parts (the material table, the clamp, the encode) are
* free of three.js so qa can pin them; `makeFixedFunctionMaterial` is the one
* three.js binding.
*
* What the equation is (OpenGL 1.5 §2.14.1, `GL_LIGHT_MODEL_LOCAL_VIEWER`
* off, no attenuation, no spot):
*
* c = E_m + A_lm·A_m + Σ_i [ A_li·A_m + max(N·L_i,0)·D_li·D_m
* + (N·L_i > 0 ? max(N·H_i,0)^s : 0)·S_li·S_m ]
* H_i = normalize( L_i + (0,0,1) ) — the non-local viewer
* alpha = D_m.a
*
* `A_lm` (GL_LIGHT_MODEL_AMBIENT) is set to zero in `init_lights`.
*/
import * as THREE from 'three';
import type { Color4d } from '@ziroeda/common/gal/color4d.js';
export type Vec3 = [number, number, number];
/** `SMATERIAL` (plugins/3dapi/c3dmodel.h). Transparency: 1 is fully transparent. */
export interface SMaterial {
ambient: Vec3;
diffuse: Vec3;
specular: Vec3;
emissive: Vec3;
shininess: number;
transparency: number;
}
const rgb = (c: Color4d): Vec3 => [c.r, c.g, c.b];
const scale = (v: Vec3, s: number): Vec3 => [v[0] * s, v[1] * s, v[2] * s];
const mul = (a: Vec3, b: Vec3): Vec3 => [a[0] * b[0], a[1] * b[1], a[2] * b[2]];
const addS = (v: Vec3, s: number): Vec3 => [v[0] + s, v[1] + s, v[2] + s];
const ZERO: Vec3 = [0, 0, 0];
/** `mapf` (3d_math.h). */
export function mapf(
x: number,
inMin: number,
inMax: number,
outMin: number,
outMax: number,
): number {
x = Math.min(Math.max(x, inMin), inMax);
return ((x - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;
}
/** `RGBtoGray` (3d_math.h). */
export const rgbToGray = (c: Vec3): number => c[0] * 0.2126 + c[1] * 0.7152 + c[2] * 0.0722;
/** `MaterialDiffuseToColorCAD` (3d_math.h): the CAD colours preset's grey ramp. */
export function materialDiffuseToColorCAD(c: Vec3): Vec3 {
// convert to a discrete scale of grays
const luminance = Math.min((Math.trunc(4 * rgbToGray(c)) + 0.5) / 4, 1);
const maxValue = Math.max(c[0], c[1], c[2], 1.1920929e-7);
return [
(c[0] / maxValue) * 0.125 + luminance * 0.875,
(c[1] / maxValue) * 0.125 + luminance * 0.875,
(c[2] / maxValue) * 0.125 + luminance * 0.875,
];
}
/**
* The GL shininess `OglSetMaterial` actually sets:
* `128 * ( m_Shininess > 1 ? 1 : m_Shininess )`.
*
* Every board material in `setupMaterials` stores `factor * 128`, which is
* always above 1, so every board layer is lit with exponent 128 whatever the
* factor says. A model's shininess comes from its file in 0..1 (VRML's
* range, and the OCE loader's 0.1 / 0.05) and is the only place the scale
* matters. Reproduced, not corrected.
*/
export const glShininess = (m: SMaterial): number => 128 * (m.shininess > 1 ? 1 : m.shininess);
/** The `BOARD_ADAPTER` colours `setupMaterials` reads (all `SFVEC4F`). */
export interface AdapterColors {
copper: Color4d;
solderPaste: Color4d;
silkTop: Color4d;
silkBottom: Color4d;
maskTop: Color4d;
maskBottom: Color4d;
boardBody: Color4d;
}
export interface BoardMaterials {
copper: SMaterial;
nonPlatedCopper: SMaterial;
paste: SMaterial;
silkTop: SMaterial;
silkBottom: SMaterial;
maskTop: SMaterial;
maskBottom: SMaterial;
epoxyBoard: SMaterial;
}
/**
* `RENDER_3D_OPENGL::setupMaterials()` and the per-layer fill-ins of
* `setLayerMaterial()` / `renderBoardBody()`, as one table.
*/
export function boardMaterials(c: AdapterColors): BoardMaterials {
const copperColor = rgb(c.copper);
// This guess the material type(ex: copper vs gold) to determine the
// shininess factor between 0.1 and 0.4
const shininessfactor =
0.4 - mapf(Math.abs(copperColor[0] - copperColor[1]), 0.15, 1.0, 0.0, 0.3);
const copper: SMaterial = {
ambient: scale(copperColor, 0.1),
diffuse: copperColor,
specular: addS(scale(copperColor, 0.75), 0.25),
emissive: ZERO,
shininess: shininessfactor * 128,
transparency: 0,
};
// Non plated copper (raw copper)
const nonPlatedCopper: SMaterial = {
ambient: [0.191, 0.073, 0.022],
diffuse: [184 / 255, 115 / 255, 50 / 255],
specular: [0.256, 0.137, 0.086],
emissive: ZERO,
shininess: 0.1 * 128,
transparency: 0,
};
const pasteColor = rgb(c.solderPaste);
const paste: SMaterial = {
ambient: pasteColor,
diffuse: pasteColor,
specular: mul(pasteColor, pasteColor),
emissive: ZERO,
shininess: 0.1 * 128,
transparency: 0,
};
const silk = (col: Color4d): SMaterial => {
const d = rgb(col);
return {
ambient: d,
diffuse: d,
specular: addS(mul(d, d), 0.1),
emissive: ZERO,
shininess: 0.078125 * 128,
transparency: 0,
};
};
const mask = (col: Color4d): SMaterial => {
const d = rgb(col);
return {
diffuse: d,
// Convert Opacity to Transparency
transparency: 1 - col.a,
ambient: scale(d, 0.3),
specular: mul(d, d),
emissive: ZERO,
shininess: 0.8 * 128,
};
};
const epoxyBoard: SMaterial = {
ambient: [117 / 255, 97 / 255, 47 / 255],
diffuse: rgb(c.boardBody),
specular: [18 / 255, 3 / 255, 20 / 255],
emissive: ZERO,
shininess: 0.1 * 128,
transparency: 1 - c.boardBody.a,
};
return {
copper,
nonPlatedCopper,
paste,
silkTop: silk(c.silkTop),
silkBottom: silk(c.silkBottom),
maskTop: mask(c.maskTop),
maskBottom: mask(c.maskBottom),
epoxyBoard,
};
}
/** `m_Plastic` as `setLayerMaterial` fills it for a user/tech layer colour. */
export function plasticMaterial(diffuse: Vec3): SMaterial {
return {
diffuse,
ambient: scale(diffuse, 0.05),
specular: scale(diffuse, 0.7),
emissive: ZERO,
shininess: 0.078125 * 128,
transparency: 0,
};
}
/**
* `OglSetDiffuseMaterial`: the DIFFUSE_ONLY / CAD_MODE material — a flat
* 0.2 ambient, no specular, exponent 0.
*/
export function diffuseOnlyMaterial(diffuse: Vec3): SMaterial {
return {
ambient: [0.2, 0.2, 0.2],
diffuse,
specular: ZERO,
emissive: ZERO,
shininess: 0,
transparency: 0,
};
}
/**
* The OCE loader's material for a coloured STEP face
* (plugins/3d/oce/loadmodel.cpp:264-268), and the uncoloured default
* (:240-243). `formatMaterial` (3d_cache/sg/ifsg_api.cpp:44) then multiplies
* ambient by diffuse; `glColorMaterial( GL_AMBIENT_AND_DIFFUSE )` at draw
* time overrides both with the vertex colour anyway, so what survives of the
* loader's choice is the specular, the shininess, and the transparency.
*/
export function stepFaceMaterial(diffuse: Vec3, alpha = 1, coloured = true): SMaterial {
return coloured
? {
ambient: mul([0.1, 0.1, 0.1], diffuse),
diffuse,
specular: [0.12, 0.12, 0.12],
emissive: ZERO,
shininess: 0.1,
transparency: 1 - alpha,
}
: {
ambient: mul([0.1, 0.1, 0.1], [0.6, 0.6, 0.6]),
diffuse: [0.6, 0.6, 0.6],
specular: [0.04, 0.04, 0.04],
emissive: ZERO,
shininess: 0.05,
transparency: 0,
};
}
/**
* `Quantity_Color::Convert_LinearRGB_To_sRGB`. KiCad reads a STEP colour
* with `Values( r, g, b, Quantity_TOC_sRGB )` and lights those sRGB-encoded
* numbers directly; our `.glb`s (and `occt-import-js`) hand back the LINEAR
* values OCCT stores, so this is the encode that recovers KiCad's numbers.
*/
export function linearToSrgb(v: number): number {
return v <= 0.0031308 ? 12.92 * v : 1.055 * v ** (1 / 2.4) - 0.055;
}
// ---------------------------------------------------------------------------
// init_lights()
/** `SphericalToCartesian( inclination, azimuth )` (3d_math.h). */
export function sphericalToCartesian(inclination: number, azimuth: number): Vec3 {
const sinInc = Math.sin(inclination);
return [sinInc * Math.cos(azimuth), sinInc * Math.sin(azimuth), Math.cos(inclination)];
}
export const LIGHT_AMBIENT: Vec3 = [0.084, 0.084, 0.084];
export const LIGHT0_DIFFUSE: Vec3 = [0.3, 0.3, 0.3];
export const LIGHT0_SPECULAR: Vec3 = [0.5, 0.5, 0.5];
export const LIGHT12_DIFFUSE: Vec3 = [0.7, 0.7, 0.7];
export const LIGHT12_SPECULAR: Vec3 = [0.7, 0.7, 0.7];
/**
* GL_LIGHT1's direction, "slightly not perpendicular with the XZ plane".
* `init_lights` runs from `initializeOpenGL` with the modelview still the
* identity, so this is an EYE-space direction: the top light rides with the
* camera. GL_LIGHT2 is its mirror in z.
*/
export const LIGHT1_DIR: Vec3 = sphericalToCartesian(Math.PI * 0.03, Math.PI * 0.25);
export const LIGHT2_DIR: Vec3 = [LIGHT1_DIR[0], LIGHT1_DIR[1], -LIGHT1_DIR[2]];
/**
* The head-light's WORLD position for a camera at `cameraPos`
* (`RENDER_3D_OPENGL::Redraw`, "Position the headlight"): a point light
* pushed out along z so the diffuse term never collapses when the camera
* skims the board.
*/
export function headlightPosition(cameraPos: Vec3): Vec3 {
const z = cameraPos[2];
const zpos = z > 0 ? Math.max(z, 0.5) + z * z : Math.min(z, -0.5) - z * z;
return [cameraPos[0], cameraPos[1], zpos];
}
/**
* The lighting equation on the CPU, for one vertex in EYE space — the same
* arithmetic as the vertex shader, so a test can pin a pixel without a GPU.
*/
export function lightVertex(
m: SMaterial,
normalEye: Vec3,
positionEye: Vec3,
headlightEye: Vec3,
alpha: number,
colorMaterial?: Vec3,
): [number, number, number, number] {
const A = colorMaterial ?? m.ambient;
const D = colorMaterial ?? m.diffuse;
const s = glShininess(m);
const norm = (v: Vec3): Vec3 => {
const l = Math.hypot(v[0], v[1], v[2]) || 1;
return [v[0] / l, v[1] / l, v[2] / l];
};
const dot = (a: Vec3, b: Vec3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const N = norm(normalEye);
let c: Vec3 = [m.emissive[0], m.emissive[1], m.emissive[2]];
const light = (L: Vec3, amb: Vec3, dif: Vec3, spec: Vec3): void => {
const nDotL = Math.max(dot(N, L), 0);
const H = norm([L[0], L[1], L[2] + 1]);
const sp = nDotL > 0 ? Math.max(dot(N, H), 0) ** s : 0;
c = [
c[0] + amb[0] * A[0] + nDotL * dif[0] * D[0] + sp * spec[0] * m.specular[0],
c[1] + amb[1] * A[1] + nDotL * dif[1] * D[1] + sp * spec[1] * m.specular[1],
c[2] + amb[2] * A[2] + nDotL * dif[2] * D[2] + sp * spec[2] * m.specular[2],
];
};
light(
norm([
headlightEye[0] - positionEye[0],
headlightEye[1] - positionEye[1],
headlightEye[2] - positionEye[2],
]),
LIGHT_AMBIENT,
LIGHT0_DIFFUSE,
LIGHT0_SPECULAR,
);
light(LIGHT1_DIR, LIGHT_AMBIENT, LIGHT12_DIFFUSE, LIGHT12_SPECULAR);
light(LIGHT2_DIR, LIGHT_AMBIENT, LIGHT12_DIFFUSE, LIGHT12_SPECULAR);
const clamp01 = (v: number): number => Math.min(Math.max(v, 0), 1);
return [clamp01(c[0]), clamp01(c[1]), clamp01(c[2]), alpha];
}
// ---------------------------------------------------------------------------
// three.js binding
const VERTEX_SHADER = /* glsl */ `
uniform vec3 uAmbient;
uniform vec3 uDiffuse;
uniform vec3 uSpecular;
uniform vec3 uEmissive;
uniform float uShininess;
uniform float uAlpha;
uniform vec3 uHeadlightEye;
uniform vec3 uLight1Dir;
uniform vec3 uLight2Dir;
uniform vec3 uLightAmbient;
uniform vec3 uLight0Diffuse;
uniform vec3 uLight0Specular;
uniform vec3 uLight12Diffuse;
uniform vec3 uLight12Specular;
varying vec4 vColor;
vec3 lightTerm( vec3 N, vec3 L, vec3 amb, vec3 dif, vec3 spec ) {
float nDotL = max( dot( N, L ), 0.0 );
// GL_LIGHT_MODEL_LOCAL_VIEWER is off: the viewer sits at +z infinity.
vec3 H = normalize( L + vec3( 0.0, 0.0, 1.0 ) );
float sp = ( nDotL > 0.0 ) ? pow( max( dot( N, H ), 0.0 ), uShininess ) : 0.0;
return amb * uAmbient + nDotL * dif * uDiffuse + sp * spec * uSpecular;
}
void main() {
vec4 P4 = modelViewMatrix * vec4( position, 1.0 );
vec3 N = normalize( normalMatrix * normal ); // GL_NORMALIZE
vec3 c = uEmissive;
c += lightTerm( N, normalize( uHeadlightEye - P4.xyz ), uLightAmbient, uLight0Diffuse, uLight0Specular );
c += lightTerm( N, uLight1Dir, uLightAmbient, uLight12Diffuse, uLight12Specular );
c += lightTerm( N, uLight2Dir, uLightAmbient, uLight12Diffuse, uLight12Specular );
vColor = vec4( clamp( c, 0.0, 1.0 ), uAlpha );
gl_Position = projectionMatrix * P4;
}
`;
const FRAGMENT_SHADER = /* glsl */ `
varying vec4 vColor;
void main() {
gl_FragColor = vColor;
}
`;
/** The light uniforms every fixed-function material shares (one object, updated per frame). */
export interface SharedLightUniforms {
uHeadlightEye: { value: THREE.Vector3 };
}
export function makeSharedLightUniforms(): SharedLightUniforms {
return { uHeadlightEye: { value: new THREE.Vector3(0, 0, 1) } };
}
export interface FixedFunctionOptions {
/** `aOpacity` of `OglSetMaterial`: the footprint model's `(opacity …)`. */
opacity?: number;
/** `glDepthMask( GL_FALSE )` while the transparent models are drawn. */
depthWrite?: boolean;
/** `glEnable( GL_BLEND )` — the layer lists always set it, but alpha 1 makes it moot. */
transparent?: boolean;
/** `glPolygonOffset( factor, units )`. */
polygonOffset?: [number, number];
/** `glDisable( GL_CULL_FACE )`: the navigator gizmo only. */
doubleSide?: boolean;
/**
* `glColorMaterial( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE )` with the
* vertex colour = the material diffuse: ambient tracks diffuse.
*/
colorMaterial?: boolean;
}
/**
* `OglSetMaterial( aMaterial, aOpacity )` as a three.js material sharing one
* set of light uniforms. `uAlpha` is `( 1 - transparency ) * opacity`.
*/
export function makeFixedFunctionMaterial(
m: SMaterial,
lights: SharedLightUniforms,
o: FixedFunctionOptions = {},
): THREE.ShaderMaterial {
const opacity = o.opacity ?? 1;
const ambient = o.colorMaterial ? m.diffuse : m.ambient;
const mat = new THREE.ShaderMaterial({
vertexShader: VERTEX_SHADER,
fragmentShader: FRAGMENT_SHADER,
uniforms: {
uAmbient: { value: new THREE.Vector3(...ambient) },
uDiffuse: { value: new THREE.Vector3(...m.diffuse) },
uSpecular: { value: new THREE.Vector3(...m.specular) },
uEmissive: { value: new THREE.Vector3(...m.emissive) },
uShininess: { value: glShininess(m) },
uAlpha: { value: (1 - m.transparency) * opacity },
uHeadlightEye: lights.uHeadlightEye,
uLight1Dir: { value: new THREE.Vector3(...LIGHT1_DIR) },
uLight2Dir: { value: new THREE.Vector3(...LIGHT2_DIR) },
uLightAmbient: { value: new THREE.Vector3(...LIGHT_AMBIENT) },
uLight0Diffuse: { value: new THREE.Vector3(...LIGHT0_DIFFUSE) },
uLight0Specular: { value: new THREE.Vector3(...LIGHT0_SPECULAR) },
uLight12Diffuse: { value: new THREE.Vector3(...LIGHT12_DIFFUSE) },
uLight12Specular: { value: new THREE.Vector3(...LIGHT12_SPECULAR) },
},
side: o.doubleSide ? THREE.DoubleSide : THREE.FrontSide,
transparent: o.transparent ?? false,
depthWrite: o.depthWrite ?? true,
blending: THREE.NormalBlending,
toneMapped: false,
});
if (o.polygonOffset) {
mat.polygonOffset = true;
mat.polygonOffsetFactor = o.polygonOffset[0];
mat.polygonOffsetUnits = o.polygonOffset[1];
}
return mat;
}
/**
* An unlit, flat-colour material: `glDisable( GL_LIGHTING )` + `glColor4f`,
* for the grid lines and the gizmo's labels/axes.
*/
export function makeUnlitMaterial(
color: Vec3,
alpha = 1,
o: { depthTest?: boolean; depthWrite?: boolean } = {},
): THREE.ShaderMaterial {
return new THREE.ShaderMaterial({
vertexShader: /* glsl */ `
void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }
`,
fragmentShader: /* glsl */ `
uniform vec4 uColor;
void main() { gl_FragColor = uColor; }
`,
uniforms: { uColor: { value: new THREE.Vector4(color[0], color[1], color[2], alpha) } },
transparent: alpha < 1,
depthTest: o.depthTest ?? true,
depthWrite: o.depthWrite ?? true,
blending: THREE.NormalBlending,
toneMapped: false,
});
}
/**
* An unlit per-vertex-colour material (the grid's two line colours in one
* draw, the gizmo's coloured axes).
*/
export function makeVertexColorMaterial(o: { depthTest?: boolean } = {}): THREE.ShaderMaterial {
return new THREE.ShaderMaterial({
vertexShader: /* glsl */ `
attribute vec4 aColor;
varying vec4 vColor;
void main() {
vColor = aColor;
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}
`,
fragmentShader: /* glsl */ `
varying vec4 vColor;
void main() { gl_FragColor = vColor; }
`,
transparent: true,
depthTest: o.depthTest ?? true,
blending: THREE.NormalBlending,
toneMapped: false,
});
}
+20
View File
@@ -0,0 +1,20 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* @ziroeda/3d-viewer, KiCad's `3d-viewer/`: the three.js scene builder
* (`3d_rendering`'s counterpart), the OpenCascade STEP/IGES loader
* (`3d_cache`'s counterpart, minus the on-disk `.3dc` cache — that stays with
* the app, see `pcb3d.ts`'s header), and `EDA_3D_VIEWER_FRAME` itself
* (`3d_viewer/`) with its menu bar and toolbars.
*
* This package never imports `designer/`: whatever it needs from the running
* app — the tessellation cache, the hosted `packages3D` bucket, the
* Preferences dialog, the account's file dialogs — arrives through
* `Viewer3DFrame`'s props or `loadmodel.ts`'s `setModelCache`, the same seam
* `CVPCB_APP` gives `cvpcb/`.
*
* The package barrel; import a file by its KiCad name for anything else.
*/
export * from './viewer3d_types.js';
+210
View File
@@ -0,0 +1,210 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* Load a STEP/IGES model into a three.js object, in the browser. Counterpart:
* `plugins/3d/occ/loadmodel.cpp` — KiCad tessellates these formats with its
* OpenCascade kernel; we use the same kernel compiled to WASM
* (occt-import-js), lazy-loaded on first use so boards without project-local
* CAD models never pay for it.
*
* Three things happen here, in the order KiCad does them
* (`3d-viewer/3d_cache/3d_cache.cpp:255-315`):
*
* 1. hash the file's bytes,
* 2. answer from the cache if those exact bytes have been tessellated before,
* 3. otherwise run the kernel — in a worker — and cache what comes back.
*
* Step 2 is the whole performance story. Tessellation is 1.5-2x slower here
* than in native KiCad (measured: 10.99 s of WASM against a 6.87 s
* `kicad-cli pcb export glb` for the same four models), which is the ordinary
* WASM penalty and not something a different library fixes. Nobody pays it
* twice, on either side.
*
* Geometry comes out in the file's native millimetres, KiCad model space, with
* per-BREP-face STEP colors mapped to one material per color, exactly as our
* offline library converter does for the hosted `.glb` set.
*/
import * as THREE from 'three';
import type { CadKind, Tessellation } from './occt_types.js';
import { tessellate } from './occt_tessellate.js';
import type { OcctRequest, OcctResponse } from './occt_worker.js';
/**
* The tessellation cache's three operations (`designer/src/editors/pcb/model_cache.ts`,
* KiCad's `.3dc` cache in IndexedDB) — app-level storage, so it arrives
* through this settable seam rather than an import, the same one
* `PCBNEW_APP` / `CVPCB_APP` give a frame. Unconfigured (a package test, say)
* every model tessellates uncached rather than failing to load.
*/
export interface ModelCache {
modelKey(bytes: Uint8Array): Promise<string>;
cacheGet(hash: string): Promise<{ tess: Tessellation | null } | undefined>;
cachePut(hash: string, tess: Tessellation | null): Promise<void>;
}
const noCache: ModelCache = {
modelKey: () => Promise.reject(new Error('no model cache configured')),
cacheGet: () => Promise.resolve(undefined),
cachePut: () => Promise.resolve(),
};
let cache: ModelCache = noCache;
/** The app wires the real tessellation cache in once, at startup. */
export function setModelCache(ops: ModelCache): void {
cache = ops;
}
function toObject3D(tess: Tessellation): THREE.Object3D | null {
if (tess.meshes.length === 0) return null;
const root = new THREE.Group();
const matCache = new Map<string, THREE.MeshStandardMaterial>();
const materialFor = (color: [number, number, number] | null): THREE.MeshStandardMaterial => {
const key = color ? color.join(',') : 'default';
let m = matCache.get(key);
if (!m) {
m = new THREE.MeshStandardMaterial({
color: color ? new THREE.Color(color[0], color[1], color[2]) : 0xcccccc,
metalness: 0.1,
roughness: 0.6,
});
matCache.set(key, m);
}
return m;
};
for (const mesh of tess.meshes) {
const position = new THREE.Float32BufferAttribute(mesh.position, 3);
const normal = mesh.normal ? new THREE.Float32BufferAttribute(mesh.normal, 3) : null;
const allIdx = mesh.index;
// STEP colors are per-BREP-face; group triangle ranges by color into one
// mesh per color, sharing the vertex buffers.
const groups = new Map<
string,
{ color: [number, number, number] | null; ranges: [number, number][] }
>();
const faces = mesh.faces ?? [
{ first: 0, last: allIdx.length / 3 - 1, color: mesh.color ?? null },
];
for (const f of faces) {
const color = f.color ?? mesh.color ?? null;
const key = color ? color.join(',') : 'default';
let g = groups.get(key);
if (!g) {
g = { color, ranges: [] };
groups.set(key, g);
}
g.ranges.push([f.first, f.last]);
}
for (const { color, ranges } of groups.values()) {
let n = 0;
for (const [a, b] of ranges) n += (b - a + 1) * 3;
const idx = new Uint32Array(n);
let o = 0;
for (const [a, b] of ranges) {
idx.set(allIdx.subarray(a * 3, (b + 1) * 3), o);
o += (b - a + 1) * 3;
}
const geom = new THREE.BufferGeometry();
geom.setAttribute('position', position);
if (normal) geom.setAttribute('normal', normal);
else geom.computeVertexNormals();
geom.setIndex(new THREE.Uint32BufferAttribute(idx, 1));
root.add(new THREE.Mesh(geom, materialFor(color)));
}
}
return root;
}
interface Pending {
resolve: (t: Tessellation | null) => void;
}
let worker: Worker | null = null;
let workerBroken = false;
let nextId = 1;
const pending = new Map<number, Pending>();
/**
* The kernel worker, or null where there is no `Worker` to make one from
* (happy-dom under test, and any environment that has taken workers away).
* A missing worker must degrade to a slow main thread, never to a blank board.
*/
function ensureWorker(): Worker | null {
if (workerBroken) return null;
if (worker) return worker;
if (typeof Worker === 'undefined') {
workerBroken = true;
return null;
}
try {
worker = new Worker(new URL('./occt_worker.js', import.meta.url), { type: 'module' });
worker.onmessage = (e: MessageEvent<OcctResponse>) => {
const p = pending.get(e.data.id);
if (!p) return;
pending.delete(e.data.id);
p.resolve(e.data.tess);
};
// A worker that dies takes every in-flight request with it. Answer them
// (as failures) rather than leaving their promises hanging forever, and
// fall back to the main thread from here on.
worker.onerror = () => {
workerBroken = true;
worker = null;
for (const [, p] of pending) p.resolve(null);
pending.clear();
};
return worker;
} catch {
workerBroken = true;
return null;
}
}
function runTessellation(bytes: Uint8Array, kind: CadKind): Promise<Tessellation | null> {
const w = ensureWorker();
if (!w) return tessellate(bytes, kind);
return new Promise((resolve) => {
const id = nextId++;
pending.set(id, { resolve });
const req: OcctRequest = { id, bytes, kind };
// `bytes` belongs to the project's file list and is read again on every
// board load, so it is copied to the worker rather than transferred.
w.postMessage(req);
});
}
/**
* Tessellate STEP (or IGES) file content to a three.js object; null on failure.
*
* Answers from the cache when these exact bytes have been seen before — on
* this board, another board, or a previous session.
*/
export async function loadCadModel(
bytes: Uint8Array,
kind: CadKind,
): Promise<THREE.Object3D | null> {
let hash: string | null = null;
try {
hash = await cache.modelKey(bytes);
} catch {
// No SubtleCrypto (an insecure origin, say). Tessellate uncached rather
// than refuse to draw the model.
hash = null;
}
if (hash) {
const hit = await cache.cacheGet(hash);
// A row with `tess: null` is a remembered failure: the kernel already
// could not read these bytes, and re-running it would cost seconds to
// reach the same answer.
if (hit) return hit.tess ? toObject3D(hit.tess) : null;
}
const tess = await runTessellation(bytes, kind);
if (hash) await cache.cachePut(hash, tess);
return tess ? toObject3D(tess) : null;
}
+86
View File
@@ -0,0 +1,86 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* The OpenCascade kernel itself: read STEP/IGES bytes, hand back the compact
* form in `occt_types.ts`.
*
* Everything that does not need the kernel lives in that module instead, so
* importing the cache does not pull 7.6 MB of WASM (and a Vite-only `?url`
* import) into a test runner or a type check.
*/
import { type CadKind, OCCT_PARAMS, type TessMesh, type Tessellation } from './occt_types.js';
interface OcctFace {
first: number;
last: number;
color?: [number, number, number] | null;
}
interface OcctMesh {
name?: string;
attributes: { position: { array: number[] }; normal?: { array: number[] } };
index: { array: number[] };
color?: [number, number, number] | null;
brep_faces?: OcctFace[];
}
interface OcctResult {
success: boolean;
meshes: OcctMesh[];
}
interface OcctModule {
ReadStepFile(content: Uint8Array, params: unknown): OcctResult;
ReadIgesFile(content: Uint8Array, params: unknown): OcctResult;
}
let occtPromise: Promise<OcctModule> | null = null;
// Lazy singleton: the WASM kernel is ~7.6 MB, fetched only when a project
// actually ships a STEP/IGES model that is not already in the cache.
function occt(): Promise<OcctModule> {
if (!occtPromise) {
occtPromise = (async () => {
const [{ default: init }, { default: wasmUrl }] = await Promise.all([
import('occt-import-js'),
import('occt-import-js/dist/occt-import-js.wasm?url'),
]);
return (await init({ locateFile: () => wasmUrl })) as OcctModule;
})();
}
return occtPromise;
}
function compact(result: OcctResult): Tessellation | null {
if (!result.success || result.meshes.length === 0) return null;
const meshes: TessMesh[] = [];
for (const mesh of result.meshes) {
// occt-import-js hands back plain number[]; the typed copy is what makes
// the result cheap to transfer, cheap to store, and directly usable as a
// three.js buffer attribute without a second pass.
meshes.push({
position: Float32Array.from(mesh.attributes.position.array),
normal: mesh.attributes.normal ? Float32Array.from(mesh.attributes.normal.array) : null,
index: Uint32Array.from(mesh.index.array),
color: mesh.color ?? null,
faces:
mesh.brep_faces && mesh.brep_faces.length > 0
? mesh.brep_faces.map((f) => ({ first: f.first, last: f.last, color: f.color ?? null }))
: null,
});
}
return { meshes };
}
/**
* Tessellate STEP or IGES content. `null` means the kernel could not read it —
* a distinct outcome from "not tried", which is why the cache stores it.
*/
export async function tessellate(bytes: Uint8Array, kind: CadKind): Promise<Tessellation | null> {
try {
const mod = await occt();
const result =
kind === 'step' ? mod.ReadStepFile(bytes, OCCT_PARAMS) : mod.ReadIgesFile(bytes, OCCT_PARAMS);
return compact(result);
} catch {
return null;
}
}
+105
View File
@@ -0,0 +1,105 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* The shape of a tessellation, and the tolerances KiCad tessellates at.
*
* Split from `occt_tessellate.ts` so the cache and its tests can import the
* types and the constants without pulling in the WASM kernel behind them —
* that module's `?url` import of the 7.6 MB binary is a Vite construct that
* neither `tsc` outside the app nor a test runner can resolve.
*
* STEP is not a mesh. It is B-rep — NURBS patches, analytic solids, trimmed
* surfaces — so nothing can draw it until a kernel evaluates those surfaces
* and meshes them to a tolerance. That is what makes STEP hundreds of times
* slower to open than an already-tessellated format, on every platform: KiCad
* pays it too, which is why it keeps `<hash>.3dc` files under its user cache
* (`3d-viewer/3d_cache/3d_cache.cpp:305`) and tessellates each model once ever.
*
* This module is deliberately free of three.js so the worker that calls it does
* not drag a renderer into its bundle. It returns plain typed arrays, which
* are also exactly what IndexedDB can structured-clone into the cache.
*/
/**
* KiCad's tessellation tolerances, mirrored rather than chosen.
*
* `ADVANCED_CFG` defaults, `common/advanced_config.cpp:298-299`:
*
* m_OcePluginLinearDeflection = 0.14;
* m_OcePluginAngularDeflection = 30;
*
* and `plugins/3d/oce/loadmodel.cpp:1158` feeds them straight to
* `BRepMesh_IncrementalMesh( face, linDeflection, false, radians( angular ) )`.
* This is **data** in the sense CLAUDE.md means — a pair of numbers KiCad
* hardcodes — so it is mirrored, not tuned. Matching them is what makes our
* curves break into the same facets KiCad's do; measured on the four models
* CM5 Minima actually renders, the defaults give 41,628 triangles against
* KiCad's 24,684, so a model looked visibly different from the same file.
*
* The angle is in DEGREES. occt-import-js takes degrees where KiCad's C++ call
* takes radians (it converts with `glm::radians`), and passing 0.5236 here is
* silently accepted as an extremely fine angle: same four models, 13.79 s and
* 38,354 triangles, against 9.81 s and 24,684 for the correct 30.
*/
export const OCE_LINEAR_DEFLECTION = 0.14;
export const OCE_ANGULAR_DEFLECTION = 30;
/**
* `read.precision.val` is set from the same linear deflection upstream
* (`plugins/3d/oce/loadmodel.cpp:601`), and the models are millimetres in
* KiCad model space.
*/
export const OCCT_PARAMS = {
linearUnit: 'millimeter',
linearDeflectionType: 'absolute_value',
linearDeflection: OCE_LINEAR_DEFLECTION,
angularDeflection: OCE_ANGULAR_DEFLECTION,
} as const;
/** One BREP face's triangle range and its own colour, when STEP carries one. */
export interface TessFace {
first: number;
last: number;
color: [number, number, number] | null;
}
/** One mesh, in the compact form the cache stores and the loader rebuilds from. */
export interface TessMesh {
position: Float32Array;
normal: Float32Array | null;
index: Uint32Array;
color: [number, number, number] | null;
faces: TessFace[] | null;
}
export interface Tessellation {
meshes: TessMesh[];
}
export type CadKind = 'step' | 'iges';
/**
* Every buffer the result holds, so a worker can transfer rather than copy it.
* A board's models run to tens of megabytes of vertex data; structured-cloning
* that twice (worker -> main, then main -> IndexedDB) is the one avoidable cost
* in the whole path.
*/
export function tessellationBuffers(t: Tessellation): ArrayBuffer[] {
const out: ArrayBuffer[] = [];
for (const m of t.meshes) {
out.push(m.position.buffer as ArrayBuffer);
if (m.normal) out.push(m.normal.buffer as ArrayBuffer);
out.push(m.index.buffer as ArrayBuffer);
}
return out;
}
/** Total bytes of geometry, for the cache's size accounting. */
export function tessellationBytes(t: Tessellation): number {
let n = 0;
for (const m of t.meshes) {
n += m.position.byteLength + (m.normal?.byteLength ?? 0) + m.index.byteLength;
}
return n;
}
+40
View File
@@ -0,0 +1,40 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
/**
* The OpenCascade kernel, off the main thread.
*
* Tessellation is seconds of straight-line C++ per model — measured on this
* machine, 4.5 s for a 2.5 MB connector and 46 s for a 24 MB module. On the
* main thread that is not a slow load, it is a frozen tab: no repaint, no
* scroll, no cancel button. KiCad has the same cost and the same answer (its
* 3D viewer loads models off the UI thread), so this is where it belongs.
*
* The protocol is one request per message, answered once. Requests are not
* multiplexed: OCCT here is a single-threaded WASM instance, so a second
* concurrent call would queue behind the first anyway, and the caller
* (`loadmodel.ts`) already serialises through its own promise cache.
*/
import type { CadKind, Tessellation } from './occt_types.js';
import { tessellationBuffers } from './occt_types.js';
import { tessellate } from './occt_tessellate.js';
export interface OcctRequest {
id: number;
bytes: Uint8Array;
kind: CadKind;
}
export interface OcctResponse {
id: number;
tess: Tessellation | null;
}
self.onmessage = (e: MessageEvent<OcctRequest>): void => {
const { id, bytes, kind } = e.data;
void tessellate(bytes, kind).then((tess) => {
const reply: OcctResponse = { id, tess };
// Transfer the geometry rather than copy it; the worker has no further use
// for the buffers once they are on their way back.
(self as unknown as Worker).postMessage(reply, tess ? tessellationBuffers(tess) : []);
});
};
+30
View File
@@ -0,0 +1,30 @@
{
"name": "@ziroeda/3d-viewer",
"version": "0.0.0",
"description": "The 3D viewer mirroring KiCad's 3d-viewer/: EDA_3D_VIEWER_FRAME, its menu bar and toolbars, the three.js scene builder (create_scene.cpp's counterpart), the OpenCascade STEP/IGES loader, and the board-outline/appearance data the scene reads.",
"license": "GPL-3.0-or-later",
"type": "module",
"main": "./index.ts",
"types": "./index.ts",
"scripts": {
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@ziroeda/common": "workspace:*",
"@ziroeda/core": "workspace:*",
"@ziroeda/include": "workspace:*",
"@ziroeda/kimath": "workspace:*",
"@ziroeda/pcbnew": "workspace:*",
"@ziroeda/wx": "workspace:*",
"earcut": "^3.2.3",
"occt-import-js": "^0.0.23",
"react": "^18.3.1",
"three": "^0.185.1"
},
"devDependencies": {
"@types/earcut": "^3.0.0",
"@types/react": "^18.3.18",
"@types/three": "^0.185.1",
"vite": "^6.0.7"
}
}
+2262
View File
File diff suppressed because it is too large Load Diff
+249
View File
@@ -0,0 +1,249 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `RENDER_3D_RAYTRACE_BASE::IntersectBoardItem` (render_3d_raytrace_base.cpp
* :1771) and what `EDA_3D_CANVAS` makes of the answer — the HOVERED_ITEM
* message (eda_3d_canvas.cpp:985-1078) and the click that cross-probes
* (:1129-1163).
*
* Upstream shoots the mouse ray into the ray tracer's BVH, which holds every
* layer item (pad, track, via, zone fill — each carrying its `BOARD_ITEM`)
* and every model triangle (carrying its `FOOTPRINT`). Nothing in a WebGL
* rasteriser answers that, so the ray is met the other way round: the 3D
* models are tested by the caller (a mesh raycast), and the board items are
* found by dropping the ray onto the two outer copper faces and asking the
* pcbnew polygon ports which item covers that point. The nearer hit along
* the ray wins, as in the BVH.
*
* Only copper items produce a message; silk, mask and body do not
* (`default: break`). A footprint's field (its reference text) counts as
* the footprint for the click but says nothing on hover — left out.
*/
import { ARC_HIGH_DEF } from '@ziroeda/common/eda_units.js';
import { PCB_LAYER_ID } from '@ziroeda/common/layer_id.js';
import { escapeIpc, unescapeString } from '@ziroeda/common/string_utils.js';
import { KICAD_T } from '@ziroeda/core/typeinfo.js';
import { ERROR_LOC } from '@ziroeda/kimath/src/convert_basic_shapes_to_polygon.js';
import { SHAPE_POLY_SET } from '@ziroeda/kimath/src/geometry/shape_poly_set.js';
import { chainPointInside } from '@ziroeda/kimath/src/geometry/shape_poly_set_algorithms.js';
import type { Vec2 } from '@ziroeda/kimath/src/math/vector2.js';
import type { BOARD } from '@ziroeda/pcbnew/board.js';
import type { BOARD_CONNECTED_ITEM } from '@ziroeda/pcbnew/board_connected_item.js';
import type { PAD } from '@ziroeda/pcbnew/pad.js';
import type { PCB_ARC, PCB_TRACK, PCB_VIA } from '@ziroeda/pcbnew/pcb_track.js';
import type { ZONE } from '@ziroeda/pcbnew/zone.js';
import type { Vec3 } from './camera3d.js';
export type PickedItem =
/** By index into `Footprints()`, which is how the model meshes are keyed. */
| { kind: 'footprint'; footprint: number }
| { kind: 'pad'; footprint: number; pad: PAD }
| { kind: 'track'; track: PCB_TRACK }
| { kind: 'arc'; arc: PCB_ARC }
| { kind: 'via'; via: PCB_VIA }
| { kind: 'zone'; zone: ZONE; layer: string };
export interface PickFrame {
/** `BiuTo3dUnits()`. */
scale: number;
/** The outer copper faces the ray is dropped onto, 3D units. */
zTopFront: number;
zBottomBack: number;
/**
* `GetBoardPoly()`'s outer rings, IU. The board body and the mask are in
* the BVH too, carrying no item: a ray that lands on the board stops
* there whether or not a copper item is under it. Only off the board does
* it carry on to the far face.
*/
boardOutline: readonly (readonly Vec2[])[];
}
/** The point on the plane `z = planeZ` along the ray, with its parameter, or null. */
function hitPlane(
origin: Vec3,
dir: Vec3,
planeZ: number,
): { t: number; x: number; y: number } | null {
if (Math.abs(dir[2]) < 1e-12) return null;
const t = (planeZ - origin[2]) / dir[2];
if (t < 0) return null;
return { t, x: origin[0] + dir[0] * t, y: origin[1] + dir[1] * t };
}
/** `SEG::Distance`-style point-to-segment distance. */
function segDistance(p: Vec2, a: Vec2, b: Vec2): number {
const dx = b.x - a.x,
dy = b.y - a.y;
const l2 = dx * dx + dy * dy;
let t = l2 === 0 ? 0 : ((p.x - a.x) * dx + (p.y - a.y) * dy) / l2;
t = Math.max(0, Math.min(1, t));
return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy));
}
/** The copper item under a board point on one outer layer, or null. */
export function boardItemAt(aBoard: BOARD, pt: Vec2, layer: 'F.Cu' | 'B.Cu'): PickedItem | null {
const layerId = layer === 'F.Cu' ? PCB_LAYER_ID.F_Cu : PCB_LAYER_ID.B_Cu;
const inside = (aFill: (aSet: SHAPE_POLY_SET) => unknown): boolean => {
const set = new SHAPE_POLY_SET();
aFill(set);
return set.Contains(pt);
};
// Pads first: they sit on top of the layer's other items (drawn last, and
// the BVH's nearest hit is the pad's top face).
const footprints = aBoard.Footprints();
for (let fi = 0; fi < footprints.length; fi++) {
for (const pad of footprints[fi]!.Pads()) {
if (!pad.IsOnLayer(layerId)) continue;
if (
!inside((set) =>
pad.TransformShapeToPolygon(set, layerId, 0, ARC_HIGH_DEF, ERROR_LOC.ERROR_INSIDE),
)
)
continue;
// through the drill there is nothing to hit
if (inside((set) => pad.TransformHoleToPolygon(set, 0, ARC_HIGH_DEF, ERROR_LOC.ERROR_INSIDE)))
return null;
return { kind: 'pad', footprint: fi, pad };
}
}
const tracks = aBoard.Tracks();
for (const t of tracks) {
if (t.Type() !== KICAD_T.PCB_VIA_T) continue;
const v = t as PCB_VIA;
if (!v.IsOnLayer(layerId)) continue;
const d = Math.hypot(pt.x - v.GetStart().x, pt.y - v.GetStart().y);
if (d < v.GetDrillValue() / 2) return null;
if (d <= v.GetWidth(layerId) / 2) return { kind: 'via', via: v };
}
for (const t of tracks) {
if (t.Type() !== KICAD_T.PCB_TRACE_T || t.GetLayer() !== layerId) continue;
if (segDistance(pt, t.GetStart(), t.GetEnd()) <= t.GetWidth() / 2)
return { kind: 'track', track: t };
}
for (const t of tracks) {
if (t.Type() !== KICAD_T.PCB_ARC_T || t.GetLayer() !== layerId) continue;
if (
inside((set) =>
t.TransformShapeToPolygon(set, layerId, 0, ARC_HIGH_DEF, ERROR_LOC.ERROR_INSIDE),
)
)
return { kind: 'arc', arc: t as PCB_ARC };
}
for (const z of aBoard.Zones()) {
if (!z.IsOnLayer(layerId)) continue;
if (z.GetFilledPolysList(layerId).Contains(pt)) return { kind: 'zone', zone: z, layer };
}
return null;
}
export function pickBoardItem(
board: BOARD,
frame: PickFrame,
origin: Vec3,
dir: Vec3,
modelHit: { t: number; footprint: number } | null,
): PickedItem | null {
const planes: { z: number; layer: 'F.Cu' | 'B.Cu' }[] = [
{ z: frame.zTopFront, layer: 'F.Cu' },
{ z: frame.zBottomBack, layer: 'B.Cu' },
];
const hits = planes
.map((p) => ({ p, h: hitPlane(origin, dir, p.z) }))
.filter(
(x): x is { p: (typeof planes)[number]; h: NonNullable<ReturnType<typeof hitPlane>> } =>
x.h !== null,
)
.sort((a, b) => a.h.t - b.h.t);
for (const { p, h } of hits) {
// 3D units → board IU, y un-flipped. Rounded: the polygon ports are the
// integer-IU ones (`chainPointInside` goes through BigInt) and a ray hit
// is a float; a nanometre is well inside any pad.
const pt = { x: Math.round(h.x / frame.scale), y: Math.round(-h.y / frame.scale) };
const onBoard = frame.boardOutline.some((ring) => chainPointInside(ring, pt));
if (!onBoard) continue;
// the board (or a model in front of it) is what the ray meets first
if (modelHit && modelHit.t < h.t) return { kind: 'footprint', footprint: modelHit.footprint };
return boardItemAt(board, pt, p.layer);
}
return modelHit ? { kind: 'footprint', footprint: modelHit.footprint } : null;
}
/**
* `printNetInfo` (eda_3d_canvas.cpp:992-997): `_( "Net %s\tNet class %s" )`
* over `aItem->GetNet()->GetNetname()` and the net's own
* `GetNetClass()->GetHumanReadableName()`.
*/
const netInfo = (aItem: BOARD_CONNECTED_ITEM): string =>
`Net ${unescapeString(aItem.GetNetname())}\tNet class ${aItem.GetNet()?.GetNetClass().GetHumanReadableName() ?? ''}`;
export function hoveredItemMessage(aBoard: BOARD, item: PickedItem | null): string {
if (!item) return '';
switch (item.kind) {
case 'pad': {
const pad = item.pad;
let msg = '';
if (pad.GetNumber()) msg += `Pad ${pad.GetNumber()}\t`;
if (pad.IsOnCopperLayer()) msg += netInfo(pad);
return msg;
}
case 'footprint': {
const fp = aBoard.Footprints()[item.footprint]!;
return `${fp.GetReference()} ${fp.GetValue()}`;
}
case 'track':
return netInfo(item.track);
case 'arc':
return netInfo(item.arc);
case 'via':
return netInfo(item.via);
case 'zone': {
const z = item.zone;
let msg = '';
if (z.GetZoneName())
msg += z.GetIsRuleArea() ? `Rule area ${z.GetZoneName()}\t` : `Zone ${z.GetZoneName()}\t`;
if (/\.Cu$/.test(item.layer)) msg += netInfo(z);
return msg;
}
}
}
export function clickSelectionParts(aBoard: BOARD, item: PickedItem | null): string[] {
if (!item) return [];
if (item.kind !== 'footprint' && item.kind !== 'pad') return [];
const fp = aBoard.Footprints()[item.footprint]!;
return [`F${escapeIpc(fp.GetReference())}`];
}
+89
View File
@@ -0,0 +1,89 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* 3D viewer toolbar layout, transcribed from KiCad's
* `3d-viewer/3d_viewer/toolbars_3d.cpp`
* (EDA_3D_VIEWER_TOOLBAR_SETTINGS::DefaultToolbarConfig).
*
* TOP_MAIN is the only toolbar the 3D viewer has — upstream returns
* `std::nullopt` for LEFT, RIGHT and TOP_AUX, so there is deliberately no
* side toolbar here. Separators mirror each `AppendSeparator()`.
*
* Ids match `EDA_3D_ACTIONS::<name>` so this reads against the source, except
* where a name already means something else in the PCB editor's own toolbar
* inventory (`moveLeft` etc.), which take a `3d` suffix.
*/
import type { ToolEntry } from '@ziroeda/common/tool/action_toolbar_types.js';
import type { ToolbarDefaults } from '@ziroeda/common/tool/ui/toolbar_configuration.js';
const sep: ToolEntry = 'sep';
/**
* Not yet ported, shown greyed in its upstream position (repo convention).
* Raytracing is the whole second renderer (render_3d_raytrace_*.cpp) and is
* deferred; the button stays so the toolbar keeps KiCad's shape.
*/
const todo = { disabled: true } as const;
/** TOP_MAIN toolbar (the only one). */
export const VIEWER3D_TOP_TOOLBAR: ToolEntry[] = [
{ id: 'reloadBoard3d', icon: 'reloadBoard3d', title: 'Reload board' },
sep,
{ id: 'copyToClipboard3d', icon: 'copyToClipboard3d', title: 'Copy 3D image to clipboard' },
sep,
{
id: 'toggleRaytracing',
icon: 'toggleRaytracing',
title: 'Render current view using Raytracing',
toggle: true,
...todo,
}, // prettier-ignore
sep,
{ id: 'zoomRedraw', icon: 'zoomRedraw', title: 'Redraw view' },
{ id: 'zoomIn', icon: 'zoomIn', title: 'Zoom in' },
{ id: 'zoomOut', icon: 'zoomOut', title: 'Zoom out' },
{ id: 'zoomFit', icon: 'zoomFit', title: 'Zoom to fit 3D model' },
sep,
{ id: 'rotateXCW', icon: 'rotateXCW', title: 'Rotate X clockwise' },
{ id: 'rotateXCCW', icon: 'rotateXCCW', title: 'Rotate X counterclockwise' },
sep,
{ id: 'rotateYCW', icon: 'rotateYCW', title: 'Rotate Y clockwise' },
{ id: 'rotateYCCW', icon: 'rotateYCCW', title: 'Rotate Y counterclockwise' },
sep,
{ id: 'rotateZCW', icon: 'rotateZCW', title: 'Rotate Z clockwise' },
{ id: 'rotateZCCW', icon: 'rotateZCCW', title: 'Rotate Z counterclockwise' },
sep,
{ id: 'flipView3d', icon: 'flipView3d', title: 'Flip board view' },
sep,
{ id: 'moveLeft3d', icon: 'moveLeft3d', title: 'Move left' },
{ id: 'moveRight3d', icon: 'moveRight3d', title: 'Move right' },
{ id: 'moveUp3d', icon: 'moveUp3d', title: 'Move up' },
{ id: 'moveDown3d', icon: 'moveDown3d', title: 'Move down' },
sep,
{ id: 'toggleOrtho', icon: 'toggleOrtho', title: 'Use orthographic projection', toggle: true },
sep,
{
id: 'showLayersManager',
icon: 'showLayersManager',
title: 'Show appearance manager',
toggle: true,
},
];
/**
* `EDA_3D_VIEWER_TOOLBAR_SETTINGS::DefaultToolbarConfig`
* (`3d-viewer/3d_viewer/toolbars_3d.cpp:41-...`):
*
* case TOOLBAR_LOC::LEFT:
* case TOOLBAR_LOC::RIGHT:
* case TOOLBAR_LOC::TOP_AUX:
* return std::nullopt;
*
* — one toolbar, and the three absent keys say `std::nullopt` the way
* `GetToolbarConfig` returns it.
*/
export const VIEWER3D_DEFAULT_TOOLBARS: ToolbarDefaults = {
TOP_MAIN: VIEWER3D_TOP_TOOLBAR,
};
+11
View File
@@ -0,0 +1,11 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"rootDir": ".",
"jsx": "react-jsx",
"types": ["vite/client"],
"lib": ["ES2022", "DOM", "DOM.Iterable"]
},
"include": ["."],
"exclude": ["node_modules"]
}
+719
View File
@@ -0,0 +1,719 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `APPEARANCE_CONTROLS_3D` (3d-viewer/dialogs/appearance_controls_3D.cpp)
* and the `BOARD_ADAPTER` halves it drives — `GetVisibleLayers`,
* `SetVisibleLayers`, `GetLayerColors`, `GetDefaultColors`
* (3d_canvas/board_adapter.cpp:598-935) — as data and pure functions. The
* React panel (`Appearance3DPanel.tsx`) draws what these say; the viewer
* (`pcb3d.ts`) is rebuilt from what they answer. No widget in here, so qa
* can pin the semantics: which rows exist, what a toggle does to the preset,
* which colours the stackup is allowed to own.
*/
import type { Color4d } from '@ziroeda/common/gal/color4d.js';
import { COLOR4D_UNSPECIFIED } from '@ziroeda/common/gal/color4d.js';
import { BUILTIN_DEFAULT_THEME } from '@ziroeda/common/settings/builtin_color_themes.js';
import {
DEFAULT_BACKGROUND_BOT,
DEFAULT_BACKGROUND_TOP,
DEFAULT_BOARD_BODY,
DEFAULT_COMMENTS,
DEFAULT_ECOS,
DEFAULT_SILKSCREEN,
DEFAULT_SOLDERMASK,
DEFAULT_SOLDERPASTE,
DEFAULT_SURFACE_FINISH,
type StackupColors,
} from './board_adapter_colors.js';
import type { PlotLayerSelection } from './board_3d_layers.js';
/**
* `LAYER_3D_ID` (include/layer_ids.h:548-622) plus the three `GAL_LAYER_ID`s
* the pane also toggles, as names. The numbers upstream are a bitset index;
* nothing here needs them.
*/
export type Layer3dFlag =
| 'LAYER_3D_BACKGROUND_BOTTOM'
| 'LAYER_3D_BACKGROUND_TOP'
| 'LAYER_3D_BOARD'
| 'LAYER_3D_COPPER_TOP'
| 'LAYER_3D_COPPER_BOTTOM'
| 'LAYER_3D_SILKSCREEN_BOTTOM'
| 'LAYER_3D_SILKSCREEN_TOP'
| 'LAYER_3D_SOLDERMASK_BOTTOM'
| 'LAYER_3D_SOLDERMASK_TOP'
| 'LAYER_3D_SOLDERPASTE'
| 'LAYER_3D_ADHESIVE'
| 'LAYER_3D_USER_COMMENTS'
| 'LAYER_3D_USER_DRAWINGS'
| 'LAYER_3D_USER_ECO1'
| 'LAYER_3D_USER_ECO2'
| `LAYER_3D_USER_${number}`
| 'LAYER_3D_PLATED_BARRELS'
| 'LAYER_3D_TH_MODELS'
| 'LAYER_3D_SMD_MODELS'
| 'LAYER_3D_VIRTUAL_MODELS'
| 'LAYER_3D_MODELS_NOT_IN_POS'
| 'LAYER_3D_MODELS_MARKED_DNP'
| 'LAYER_3D_BOUNDING_BOXES'
| 'LAYER_3D_OFF_BOARD_SILK'
| 'LAYER_3D_NAVIGATOR'
| 'LAYER_FP_VALUES'
| 'LAYER_FP_REFERENCES'
| 'LAYER_FP_TEXT';
/** `LAYER_3D_USER_1..45`. */
export const userFlag = (n: number): Layer3dFlag => `LAYER_3D_USER_${n}`;
/** The `N` of a `LAYER_3D_USER_N` flag, or 0. */
export const userFlagIndex = (f: string): number => {
const m = /^LAYER_3D_USER_(\d+)$/.exec(f);
return m ? Number(m[1]) : 0;
};
/** One `APPEARANCE_SETTING_3D` (`RR( label, id, tooltip )`), or a spacer. */
export interface AppearanceRow3d {
label: string;
id: Layer3dFlag;
tooltip: string;
}
/**
* `s_layerSettings` (appearance_controls_3D.cpp:48-135), in order; `null`
* is an `RR()` spacer. The model rows carry their action's tooltip
* (eda_3d_actions.cpp:312-368).
*/
export const APPEARANCE_ROWS_3D: readonly (AppearanceRow3d | null)[] = [
{ label: 'Board Body', id: 'LAYER_3D_BOARD', tooltip: 'Show board body' },
{
label: 'Plated Barrels',
id: 'LAYER_3D_PLATED_BARRELS',
tooltip: 'Show barrels of plated through-holes and vias',
},
{ label: 'F.Cu', id: 'LAYER_3D_COPPER_TOP', tooltip: 'Show front copper / surface finish color' },
{
label: 'B.Cu',
id: 'LAYER_3D_COPPER_BOTTOM',
tooltip: 'Show back copper / surface finish color',
},
{ label: 'Adhesive', id: 'LAYER_3D_ADHESIVE', tooltip: 'Show adhesive' },
{ label: 'Solder Paste', id: 'LAYER_3D_SOLDERPASTE', tooltip: 'Show solder paste' },
{ label: 'F.Silkscreen', id: 'LAYER_3D_SILKSCREEN_TOP', tooltip: 'Show front silkscreen' },
{ label: 'B.Silkscreen', id: 'LAYER_3D_SILKSCREEN_BOTTOM', tooltip: 'Show back silkscreen' },
{ label: 'F.Mask', id: 'LAYER_3D_SOLDERMASK_TOP', tooltip: 'Show front solder mask' },
{ label: 'B.Mask', id: 'LAYER_3D_SOLDERMASK_BOTTOM', tooltip: 'Show back solder mask' },
{ label: 'User.Drawings', id: 'LAYER_3D_USER_DRAWINGS', tooltip: 'Show user drawings layer' },
{ label: 'User.Comments', id: 'LAYER_3D_USER_COMMENTS', tooltip: 'Show user comments layer' },
{ label: 'User.Eco1', id: 'LAYER_3D_USER_ECO1', tooltip: 'Show user ECO1 layer' },
{ label: 'User.Eco2', id: 'LAYER_3D_USER_ECO2', tooltip: 'Show user ECO2 layer' },
...Array.from({ length: 45 }, (_, i) => ({
label: `User.${i + 1}`,
id: userFlag(i + 1),
tooltip: `Show user defined layer ${i + 1}`,
})),
null,
{
label: 'Through-hole Models',
id: 'LAYER_3D_TH_MODELS',
tooltip: "Show 3D models for 'Through hole' type footprints",
},
{
label: 'SMD Models',
id: 'LAYER_3D_SMD_MODELS',
tooltip: "Show 3D models for 'Surface mount' type footprints",
},
{
label: 'Virtual Models',
id: 'LAYER_3D_VIRTUAL_MODELS',
tooltip: "Show 3D models for 'unspecified' type footprints",
},
{
label: 'Models not in POS File',
id: 'LAYER_3D_MODELS_NOT_IN_POS',
tooltip: 'Show 3D models even if not found in .pos file',
},
{
label: 'Models marked DNP',
id: 'LAYER_3D_MODELS_MARKED_DNP',
tooltip: "Show 3D models even if marked 'Do Not Place'",
},
{
label: 'Model Bounding Boxes',
id: 'LAYER_3D_BOUNDING_BOXES',
tooltip: 'Show 3D model bounding boxes in realtime renderer',
},
null,
{ label: 'Values', id: 'LAYER_FP_VALUES', tooltip: 'Show footprint values' },
{ label: 'References', id: 'LAYER_FP_REFERENCES', tooltip: 'Show footprint references' },
{ label: 'Footprint Text', id: 'LAYER_FP_TEXT', tooltip: 'Show all footprint text' },
{
label: 'Off-board Silkscreen',
id: 'LAYER_3D_OFF_BOARD_SILK',
tooltip: 'Do not clip silk layers to board outline',
},
null,
{ label: '3D Navigator', id: 'LAYER_3D_NAVIGATOR', tooltip: 'Show 3D navigator' },
{
label: 'Background Start',
id: 'LAYER_3D_BACKGROUND_TOP',
tooltip: 'Background gradient start color',
},
{
label: 'Background End',
id: 'LAYER_3D_BACKGROUND_BOTTOM',
tooltip: 'Background gradient end color',
},
];
/**
* `Map3DLayerToPCBLayer` for the rows whose label is the BOARD's layer name
* (`rebuildLayers`: `layerName = GetBoard()->GetLayerName( boardLayer )`).
*/
export function pcbLayerOfFlag(f: Layer3dFlag): string | undefined {
switch (f) {
case 'LAYER_3D_COPPER_TOP':
return 'F.Cu';
case 'LAYER_3D_COPPER_BOTTOM':
return 'B.Cu';
case 'LAYER_3D_SILKSCREEN_TOP':
return 'F.SilkS';
case 'LAYER_3D_SILKSCREEN_BOTTOM':
return 'B.SilkS';
case 'LAYER_3D_SOLDERMASK_TOP':
return 'F.Mask';
case 'LAYER_3D_SOLDERMASK_BOTTOM':
return 'B.Mask';
case 'LAYER_3D_ADHESIVE':
return 'F.Adhes';
case 'LAYER_3D_SOLDERPASTE':
return 'F.Paste';
case 'LAYER_3D_USER_COMMENTS':
return 'Cmts.User';
case 'LAYER_3D_USER_DRAWINGS':
return 'Dwgs.User';
case 'LAYER_3D_USER_ECO1':
return 'Eco1.User';
case 'LAYER_3D_USER_ECO2':
return 'Eco2.User';
default: {
const u = userFlagIndex(f);
return u ? `User.${u}` : undefined;
}
}
}
/**
* `inStackupColors` (appearance_controls_3D.cpp:139-145): the swatches
* "Use board stackup colors" takes over, and therefore locks.
*/
export const IN_STACKUP_COLORS: readonly Layer3dFlag[] = [
'LAYER_3D_BOARD',
'LAYER_3D_COPPER_TOP',
'LAYER_3D_COPPER_BOTTOM',
'LAYER_3D_SOLDERPASTE',
'LAYER_3D_SILKSCREEN_TOP',
'LAYER_3D_SILKSCREEN_BOTTOM',
'LAYER_3D_SOLDERMASK_TOP',
'LAYER_3D_SOLDERMASK_BOTTOM',
];
/** The rows that have a colour at all (`colors.count( layer )`). */
export const COLORED_FLAGS: readonly Layer3dFlag[] = [
'LAYER_3D_BACKGROUND_TOP',
'LAYER_3D_BACKGROUND_BOTTOM',
'LAYER_3D_BOARD',
'LAYER_3D_COPPER_TOP',
'LAYER_3D_COPPER_BOTTOM',
'LAYER_3D_SILKSCREEN_TOP',
'LAYER_3D_SILKSCREEN_BOTTOM',
'LAYER_3D_SOLDERMASK_TOP',
'LAYER_3D_SOLDERMASK_BOTTOM',
'LAYER_3D_SOLDERPASTE',
'LAYER_3D_USER_DRAWINGS',
'LAYER_3D_USER_COMMENTS',
'LAYER_3D_USER_ECO1',
'LAYER_3D_USER_ECO2',
...Array.from({ length: 45 }, (_, i) => userFlag(i + 1)),
];
export type Layer3dColors = ReadonlyMap<Layer3dFlag, Color4d>;
/**
* `BOARD_ADAPTER::GetDefaultColors()` (board_adapter.cpp:612-631): the
* `g_Default*` table — what a swatch's "Reset to Default" goes back to, and
* what the "legacy colors" preset holds.
*/
export function defaultColors3d(): Map<Layer3dFlag, Color4d> {
const m = new Map<Layer3dFlag, Color4d>();
m.set('LAYER_3D_BACKGROUND_TOP', DEFAULT_BACKGROUND_TOP);
m.set('LAYER_3D_BACKGROUND_BOTTOM', DEFAULT_BACKGROUND_BOT);
m.set('LAYER_3D_BOARD', DEFAULT_BOARD_BODY);
m.set('LAYER_3D_COPPER_TOP', DEFAULT_SURFACE_FINISH);
m.set('LAYER_3D_COPPER_BOTTOM', DEFAULT_SURFACE_FINISH);
m.set('LAYER_3D_SILKSCREEN_TOP', DEFAULT_SILKSCREEN);
m.set('LAYER_3D_SILKSCREEN_BOTTOM', DEFAULT_SILKSCREEN);
m.set('LAYER_3D_SOLDERMASK_TOP', DEFAULT_SOLDERMASK);
m.set('LAYER_3D_SOLDERMASK_BOTTOM', DEFAULT_SOLDERMASK);
m.set('LAYER_3D_SOLDERPASTE', DEFAULT_SOLDERPASTE);
m.set('LAYER_3D_USER_DRAWINGS', DEFAULT_COMMENTS);
m.set('LAYER_3D_USER_COMMENTS', DEFAULT_COMMENTS);
m.set('LAYER_3D_USER_ECO1', DEFAULT_ECOS);
m.set('LAYER_3D_USER_ECO2', DEFAULT_ECOS);
return m;
}
/**
* The colour theme's `3d_viewer.*` entries (`GetColorSettings( DEFAULT_THEME )
* ->GetColor( layer )` for every key of `GetDefaultColors()`), which is what
* `GetLayerColors` starts from when no saved preset is current. The theme has
* no entry for the four user layers, so `GetColor` answers UNSPECIFIED there;
* the 45 `User_N` rows take `3d_viewer.user_N`, whose default is the board
* editor's `User_N` colour (color_settings.cpp:256-263).
*/
export function themeColors3d(): Map<Layer3dFlag, Color4d> {
const T = BUILTIN_DEFAULT_THEME as Record<string, Color4d>;
const m = new Map<Layer3dFlag, Color4d>();
m.set('LAYER_3D_BACKGROUND_TOP', T.LAYER_3D_BACKGROUND_TOP!);
m.set('LAYER_3D_BACKGROUND_BOTTOM', T.LAYER_3D_BACKGROUND_BOTTOM!);
m.set('LAYER_3D_BOARD', T.LAYER_3D_BOARD!);
m.set('LAYER_3D_COPPER_TOP', T.LAYER_3D_COPPER_TOP!);
m.set('LAYER_3D_COPPER_BOTTOM', T.LAYER_3D_COPPER_TOP!);
m.set('LAYER_3D_SILKSCREEN_TOP', T.LAYER_3D_SILKSCREEN_TOP!);
m.set('LAYER_3D_SILKSCREEN_BOTTOM', T.LAYER_3D_SILKSCREEN_BOTTOM!);
m.set('LAYER_3D_SOLDERMASK_TOP', T.LAYER_3D_SOLDERMASK_TOP!);
m.set('LAYER_3D_SOLDERMASK_BOTTOM', T.LAYER_3D_SOLDERMASK_BOTTOM!);
m.set('LAYER_3D_SOLDERPASTE', T.LAYER_3D_SOLDERPASTE!);
m.set('LAYER_3D_USER_DRAWINGS', COLOR4D_UNSPECIFIED);
m.set('LAYER_3D_USER_COMMENTS', COLOR4D_UNSPECIFIED);
m.set('LAYER_3D_USER_ECO1', COLOR4D_UNSPECIFIED);
m.set('LAYER_3D_USER_ECO2', COLOR4D_UNSPECIFIED);
for (let n = 1; n <= 45; n++) m.set(userFlag(n), T[`User_${n}`] ?? COLOR4D_UNSPECIFIED);
return m;
}
/**
* `BOARD_ADAPTER::GetLayerColors()` (board_adapter.cpp:638-757): the preset's
* colours if one is current, else the theme's; the stackup's on top when
* "Use board stackup colors" is on; `m_ColorOverrides` (the swatches) last.
* COPPER_BOTTOM always copies COPPER_TOP.
*/
export function layerColors3d(
presetColors: Layer3dColors | undefined,
useStackupColors: boolean,
stackup: StackupColors | undefined,
overrides: Layer3dColors,
): Map<Layer3dFlag, Color4d> {
const colors = new Map<Layer3dFlag, Color4d>(presetColors ?? themeColors3d());
if (useStackupColors && stackup) {
colors.set('LAYER_3D_SILKSCREEN_TOP', stackup.silkTop);
colors.set('LAYER_3D_SILKSCREEN_BOTTOM', stackup.silkBottom);
colors.set('LAYER_3D_SOLDERMASK_TOP', stackup.maskTop);
colors.set('LAYER_3D_SOLDERMASK_BOTTOM', stackup.maskBottom);
if (stackup.body) colors.set('LAYER_3D_BOARD', stackup.body);
if (stackup.copper) colors.set('LAYER_3D_COPPER_TOP', stackup.copper);
}
colors.set('LAYER_3D_COPPER_BOTTOM', colors.get('LAYER_3D_COPPER_TOP')!);
for (const [k, v] of overrides) colors.set(k, v);
return colors;
}
/**
* The `show_*` flags of `EDA_3D_VIEWER_SETTINGS::m_Render` the visibility
* set is read from and written to (`GetVisibleLayers` / `SetVisibleLayers`).
*/
export interface RenderShowFlags {
show_board_body: boolean;
show_plated_barrels: boolean;
show_copper_top: boolean;
show_copper_bottom: boolean;
show_silkscreen_top: boolean;
show_silkscreen_bottom: boolean;
show_soldermask_top: boolean;
show_soldermask_bottom: boolean;
show_solderpaste: boolean;
show_adhesive: boolean;
show_comments: boolean;
show_drawings: boolean;
show_eco1: boolean;
show_eco2: boolean;
show_user: boolean[];
show_footprints_normal: boolean;
show_footprints_insert: boolean;
show_footprints_virtual: boolean;
show_footprints_not_in_posfile: boolean;
show_footprints_dnp: boolean;
show_fp_references: boolean;
show_fp_values: boolean;
show_fp_text: boolean;
/** `render.opengl_show_model_bbox` / `render.opengl_show_off_board_silk` — the two with the prefix. */
opengl_show_model_bbox: boolean;
opengl_show_off_board_silk: boolean;
show_navigator: boolean;
}
/** `eda_3d_viewer_settings.cpp:330-420`'s third arguments. */
export const RENDER_SHOW_DEFAULTS: RenderShowFlags = {
show_board_body: true,
show_plated_barrels: true,
show_copper_top: true,
show_copper_bottom: true,
show_silkscreen_top: true,
show_silkscreen_bottom: true,
show_soldermask_top: true,
show_soldermask_bottom: true,
show_solderpaste: true,
show_adhesive: true,
show_comments: true,
show_drawings: true,
show_eco1: true,
show_eco2: true,
show_user: Array.from({ length: 45 }, () => false),
show_footprints_normal: true,
show_footprints_insert: true,
show_footprints_virtual: true,
show_footprints_not_in_posfile: true,
show_footprints_dnp: false,
show_fp_references: true,
show_fp_values: true,
show_fp_text: true,
opengl_show_model_bbox: false,
opengl_show_off_board_silk: false,
show_navigator: true,
};
/** `FOLLOW_PCB` / `FOLLOW_PLOT_SETTINGS` / `LEGACY_PRESET_FLAG` (eda_3d_viewer_settings.h:32-34). */
export const FOLLOW_PCB = 'follow_pcb_editor';
export const FOLLOW_PLOT_SETTINGS = 'follow_plot_settings';
/** What the FOLLOW_PCB branch reads off the board editor. */
export interface PcbEditorVisibility {
/** `m_board->IsLayerVisible( layer )`, by canonical name. */
layers: ReadonlySet<string>;
/** `IsElementVisible( LAYER_FP_REFERENCES / VALUES / TEXT )`. */
fpReferences: boolean;
fpValues: boolean;
fpText: boolean;
}
/**
* `BOARD_ADAPTER::GetVisibleLayers()` (board_adapter.cpp:808-935), the
* board view branch: the render flags, then the preset's override.
*/
export function visibleLayers3d(
render: RenderShowFlags,
preset: string,
presets: readonly LayerPreset3d[],
plot: PlotLayerSelection | undefined,
pcb: PcbEditorVisibility | undefined,
/** `Map3DLayerToPCBLayer( layer )` → PCB_LAYER_ID, for the plot set test. */
layerId: (name: string) => number,
): Set<Layer3dFlag> {
const ret = new Set<Layer3dFlag>();
const set = (f: Layer3dFlag, on: boolean): void => {
if (on) ret.add(f);
else ret.delete(f);
};
set('LAYER_3D_BOARD', render.show_board_body);
set('LAYER_3D_PLATED_BARRELS', render.show_plated_barrels);
set('LAYER_3D_COPPER_TOP', render.show_copper_top);
set('LAYER_3D_COPPER_BOTTOM', render.show_copper_bottom);
set('LAYER_3D_SILKSCREEN_TOP', render.show_silkscreen_top);
set('LAYER_3D_SILKSCREEN_BOTTOM', render.show_silkscreen_bottom);
set('LAYER_3D_SOLDERMASK_TOP', render.show_soldermask_top);
set('LAYER_3D_SOLDERMASK_BOTTOM', render.show_soldermask_bottom);
set('LAYER_3D_SOLDERPASTE', render.show_solderpaste);
set('LAYER_3D_ADHESIVE', render.show_adhesive);
set('LAYER_3D_USER_COMMENTS', render.show_comments);
set('LAYER_3D_USER_DRAWINGS', render.show_drawings);
set('LAYER_3D_USER_ECO1', render.show_eco1);
set('LAYER_3D_USER_ECO2', render.show_eco2);
for (let n = 1; n <= 45; n++) set(userFlag(n), render.show_user[n - 1] ?? false);
set('LAYER_FP_REFERENCES', render.show_fp_references);
set('LAYER_FP_VALUES', render.show_fp_values);
set('LAYER_FP_TEXT', render.show_fp_text);
set('LAYER_3D_TH_MODELS', render.show_footprints_normal);
set('LAYER_3D_SMD_MODELS', render.show_footprints_insert);
set('LAYER_3D_VIRTUAL_MODELS', render.show_footprints_virtual);
set('LAYER_3D_MODELS_NOT_IN_POS', render.show_footprints_not_in_posfile);
set('LAYER_3D_MODELS_MARKED_DNP', render.show_footprints_dnp);
set('LAYER_3D_BOUNDING_BOXES', render.opengl_show_model_bbox);
set('LAYER_3D_OFF_BOARD_SILK', render.opengl_show_off_board_silk);
set('LAYER_3D_NAVIGATOR', render.show_navigator);
if (preset === FOLLOW_PCB) {
if (!pcb) return ret;
set('LAYER_3D_BOARD', true);
set('LAYER_3D_COPPER_TOP', pcb.layers.has('F.Cu'));
set('LAYER_3D_COPPER_BOTTOM', pcb.layers.has('B.Cu'));
set('LAYER_3D_SILKSCREEN_TOP', pcb.layers.has('F.SilkS'));
set('LAYER_3D_SILKSCREEN_BOTTOM', pcb.layers.has('B.SilkS'));
set('LAYER_3D_SOLDERMASK_TOP', pcb.layers.has('F.Mask'));
set('LAYER_3D_SOLDERMASK_BOTTOM', pcb.layers.has('B.Mask'));
set('LAYER_3D_SOLDERPASTE', pcb.layers.has('F.Paste'));
set('LAYER_3D_ADHESIVE', pcb.layers.has('F.Adhes'));
set('LAYER_3D_USER_COMMENTS', pcb.layers.has('Cmts.User'));
set('LAYER_3D_USER_DRAWINGS', pcb.layers.has('Dwgs.User'));
set('LAYER_3D_USER_ECO1', pcb.layers.has('Eco1.User'));
set('LAYER_3D_USER_ECO2', pcb.layers.has('Eco2.User'));
for (let n = 1; n <= 45; n++) set(userFlag(n), pcb.layers.has(`User.${n}`));
set('LAYER_FP_REFERENCES', pcb.fpReferences);
set('LAYER_FP_VALUES', pcb.fpValues);
set('LAYER_FP_TEXT', pcb.fpText);
} else if (preset === FOLLOW_PLOT_SETTINGS) {
if (!plot) return ret;
const has = (name: string): boolean => plot.layers.has(layerId(name));
set('LAYER_3D_BOARD', true);
set('LAYER_3D_COPPER_TOP', has('F.Cu'));
set('LAYER_3D_COPPER_BOTTOM', has('B.Cu'));
set('LAYER_3D_SILKSCREEN_TOP', has('F.SilkS'));
set('LAYER_3D_SILKSCREEN_BOTTOM', has('B.SilkS'));
set('LAYER_3D_SOLDERMASK_TOP', has('F.Mask'));
set('LAYER_3D_SOLDERMASK_BOTTOM', has('B.Mask'));
set('LAYER_3D_SOLDERPASTE', has('F.Paste'));
set('LAYER_3D_ADHESIVE', has('F.Adhes'));
set('LAYER_3D_USER_COMMENTS', has('Cmts.User'));
set('LAYER_3D_USER_DRAWINGS', has('Dwgs.User'));
set('LAYER_3D_USER_ECO1', has('Eco1.User'));
set('LAYER_3D_USER_ECO2', has('Eco2.User'));
for (let n = 1; n <= 45; n++) set(userFlag(n), has(`User.${n}`));
set('LAYER_FP_REFERENCES', plot.plotReference);
set('LAYER_FP_VALUES', plot.plotValue);
set('LAYER_FP_TEXT', plot.plotFPText);
} else {
const p = presets.find((x) => x.name === preset);
if (p) return new Set(p.layers);
}
return ret;
}
/**
* `BOARD_ADAPTER::SetVisibleLayers( aLayers )` (board_adapter.cpp:772-805):
* the set written back into the render flags.
*/
export function renderFlagsFromVisible(
render: RenderShowFlags,
v: ReadonlySet<Layer3dFlag>,
): RenderShowFlags {
return {
...render,
show_board_body: v.has('LAYER_3D_BOARD'),
show_plated_barrels: v.has('LAYER_3D_PLATED_BARRELS'),
show_copper_top: v.has('LAYER_3D_COPPER_TOP'),
show_copper_bottom: v.has('LAYER_3D_COPPER_BOTTOM'),
show_silkscreen_top: v.has('LAYER_3D_SILKSCREEN_TOP'),
show_silkscreen_bottom: v.has('LAYER_3D_SILKSCREEN_BOTTOM'),
show_soldermask_top: v.has('LAYER_3D_SOLDERMASK_TOP'),
show_soldermask_bottom: v.has('LAYER_3D_SOLDERMASK_BOTTOM'),
show_solderpaste: v.has('LAYER_3D_SOLDERPASTE'),
show_adhesive: v.has('LAYER_3D_ADHESIVE'),
show_comments: v.has('LAYER_3D_USER_COMMENTS'),
show_drawings: v.has('LAYER_3D_USER_DRAWINGS'),
show_eco1: v.has('LAYER_3D_USER_ECO1'),
show_eco2: v.has('LAYER_3D_USER_ECO2'),
show_user: Array.from({ length: 45 }, (_, i) => v.has(userFlag(i + 1))),
show_footprints_normal: v.has('LAYER_3D_TH_MODELS'),
show_footprints_insert: v.has('LAYER_3D_SMD_MODELS'),
show_footprints_virtual: v.has('LAYER_3D_VIRTUAL_MODELS'),
show_footprints_not_in_posfile: v.has('LAYER_3D_MODELS_NOT_IN_POS'),
show_footprints_dnp: v.has('LAYER_3D_MODELS_MARKED_DNP'),
show_fp_references: v.has('LAYER_FP_REFERENCES'),
show_fp_values: v.has('LAYER_FP_VALUES'),
show_fp_text: v.has('LAYER_FP_TEXT'),
opengl_show_model_bbox: v.has('LAYER_3D_BOUNDING_BOXES'),
opengl_show_off_board_silk: v.has('LAYER_3D_OFF_BOARD_SILK'),
show_navigator: v.has('LAYER_3D_NAVIGATOR'),
};
}
/**
* `APPEARANCE_CONTROLS_3D::OnLayerVisibilityChanged` (:322-408): the eye
* toggle, with its two meta-rules — Footprint Text drags References and
* Values off with it, and turning either of those on turns Footprint Text
* back on — and whether the change breaks a "Follow …" preset
* (`killFollow`): a layer does, a model row does not.
*/
export function layerVisibilityChanged(
visible: ReadonlySet<Layer3dFlag>,
layer: Layer3dFlag,
isVisible: boolean,
): { visible: Set<Layer3dFlag>; killFollow: boolean; fastRefresh: boolean } {
const v = new Set(visible);
const set = (f: Layer3dFlag, on: boolean): void => {
if (on) v.add(f);
else v.delete(f);
};
let killFollow = false;
let fastRefresh = false;
switch (layer) {
case 'LAYER_FP_TEXT':
if (!isVisible) {
set('LAYER_FP_REFERENCES', false);
set('LAYER_FP_VALUES', false);
}
set('LAYER_FP_TEXT', isVisible);
killFollow = true;
break;
case 'LAYER_FP_REFERENCES':
case 'LAYER_FP_VALUES':
if (isVisible) set('LAYER_FP_TEXT', true);
set(layer, isVisible);
killFollow = true;
break;
case 'LAYER_3D_BOARD':
case 'LAYER_3D_COPPER_TOP':
case 'LAYER_3D_COPPER_BOTTOM':
case 'LAYER_3D_PLATED_BARRELS':
case 'LAYER_3D_SILKSCREEN_BOTTOM':
case 'LAYER_3D_SILKSCREEN_TOP':
case 'LAYER_3D_SOLDERMASK_BOTTOM':
case 'LAYER_3D_SOLDERMASK_TOP':
case 'LAYER_3D_SOLDERPASTE':
case 'LAYER_3D_ADHESIVE':
case 'LAYER_3D_USER_COMMENTS':
case 'LAYER_3D_USER_DRAWINGS':
case 'LAYER_3D_USER_ECO1':
case 'LAYER_3D_USER_ECO2':
set(layer, isVisible);
killFollow = true;
break;
case 'LAYER_3D_TH_MODELS':
case 'LAYER_3D_SMD_MODELS':
case 'LAYER_3D_VIRTUAL_MODELS':
case 'LAYER_3D_MODELS_NOT_IN_POS':
case 'LAYER_3D_MODELS_MARKED_DNP':
fastRefresh = true;
set(layer, isVisible);
break;
default:
set(layer, isVisible);
if (userFlagIndex(layer)) killFollow = true;
break;
}
return { visible: v, killFollow, fastRefresh };
}
/**
* `onColorSwatchChanged` (:411-463): the three copper swatches are one
* colour — the renderer has a single `m_CopperColor`.
*/
export function colorSwatchChanged(
overrides: Layer3dColors,
layer: Layer3dFlag,
color: Color4d,
): Map<Layer3dFlag, Color4d> {
const next = new Map(overrides);
next.set(layer, color);
const copper: Layer3dFlag[] = [
'LAYER_3D_COPPER_TOP',
'LAYER_3D_COPPER_BOTTOM',
'LAYER_3D_PLATED_BARRELS',
];
if (copper.includes(layer)) for (const c of copper) next.set(c, color);
return next;
}
/** `LAYER_PRESET_3D` (eda_3d_viewer_settings.h): name, visibility, colours. */
export interface LayerPreset3d {
name: string;
layers: readonly Layer3dFlag[];
colors: Readonly<Record<string, Color4d>>;
}
export const PRESET_SEPARATOR_3D = '---';
/**
* `rebuildLayerPresetsWidget` (:555-573): the two Follow entries, the user's
* presets after a separator when there are any, then the two commands.
*/
export function presetComboItems3d(userPresetNames: readonly string[]): string[] {
return [
'Follow PCB Editor',
'Follow PCB Plot Settings',
...(userPresetNames.length ? [PRESET_SEPARATOR_3D, ...userPresetNames] : []),
PRESET_SEPARATOR_3D,
'Save preset...',
'Delete preset...',
];
}
/** `updateLayerPresetWidget`: which combo entry a preset name shows as. */
export function presetComboValue(
currentPreset: string,
userPresetNames: readonly string[],
): string {
if (currentPreset === FOLLOW_PCB) return 'Follow PCB Editor';
if (currentPreset === FOLLOW_PLOT_SETTINGS) return 'Follow PCB Plot Settings';
if (userPresetNames.includes(currentPreset)) return currentPreset;
return PRESET_SEPARATOR_3D; // GetCount() - 3, the separator
}
/**
* `syncLayerPresetSelection` (:576-615): after a manual change, the saved
* preset that matches the current state exactly, else none (`""`).
*/
export function syncLayerPresetSelection(
presets: readonly LayerPreset3d[],
visible: ReadonlySet<Layer3dFlag>,
colors: Layer3dColors,
useStackupColors: boolean,
): string {
const same = (a: Color4d, b: Color4d): boolean =>
a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a;
const hit = presets.find((p) => {
if (p.name.toLowerCase() === 'legacy colors' && useStackupColors) return false;
const pl = new Set(p.layers);
for (const f of visible) if (!pl.has(f)) return false;
for (const f of pl) if (!visible.has(f)) return false;
for (const [k, c] of colors) {
const pc = p.colors[k];
if (pc && !same(pc, c)) return false;
}
return true;
});
return hit ? hit.name : '';
}
/**
* `rebuildViewportsWidget` / `viewportComboItems`: the viewports
* alphabetically (a `std::map`), then the separator and the two commands.
*/
export function viewportComboItems3d(names: readonly string[]): string[] {
const cmp = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
return [...[...names].sort(cmp), PRESET_SEPARATOR_3D, 'Save viewport...', 'Delete viewport...'];
}
/**
* `BOARD_ADAPTER::GetDefaultVisibleLayers()` (board_adapter.cpp:948-985) —
* what the "legacy colors" preset the first open creates
* (eda_3d_viewer_frame.cpp:576-580) shows.
*/
export function defaultVisibleLayers3d(): Set<Layer3dFlag> {
return new Set<Layer3dFlag>([
'LAYER_3D_BOARD',
'LAYER_3D_PLATED_BARRELS',
'LAYER_3D_COPPER_TOP',
'LAYER_3D_COPPER_BOTTOM',
'LAYER_3D_SILKSCREEN_TOP',
'LAYER_3D_SILKSCREEN_BOTTOM',
'LAYER_3D_SOLDERMASK_TOP',
'LAYER_3D_SOLDERMASK_BOTTOM',
'LAYER_3D_SOLDERPASTE',
'LAYER_3D_ADHESIVE',
'LAYER_FP_REFERENCES',
'LAYER_FP_VALUES',
'LAYER_FP_TEXT',
'LAYER_3D_TH_MODELS',
'LAYER_3D_SMD_MODELS',
'LAYER_3D_VIRTUAL_MODELS',
'LAYER_3D_NAVIGATOR',
]);
}
/** The preset the first open of the frame leaves behind. */
export function legacyColorsPreset(): LayerPreset3d {
return {
name: 'legacy colors',
layers: [...defaultVisibleLayers3d()],
colors: Object.fromEntries(defaultColors3d()),
};
}
+220
View File
@@ -0,0 +1,220 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* The 3D viewer's *data* types, split out of `pcb3d.ts` for the same reason
* `menu_types.ts` was split out of `MenuBar.tsx`.
*
* `viewer3dMenus.ts` needs `Grid3D` and friends, but `pcb3d.ts` pulls in
* three.js, `component3d.ts` and `loadmodel.ts` — and `loadmodel.ts` imports
* `occt-import-js` (no types) and a `?url` wasm asset (Vite-only). A
* *type-only* import is still a module resolution, so importing these from
* `pcb3d.js` made the whole menu inventory fail `qa`'s typecheck with errors
* from a STEP loader it never touches.
*
* `pcb3d.ts` re-exports all of these, so existing importers are unaffected.
*/
/** The six standard directions of `CAMERA::ViewCommand_T1` (common/gal/3d/camera.cpp). */
export type View3DDir = 'top' | 'bottom' | 'left' | 'right' | 'front' | 'back';
/** `EDA_3D_ACTIONS::rotate{X,Y,Z}{CW,CCW}`. */
export type Rotate3DAxis = 'x' | 'y' | 'z';
/** `VIEW3D_PAN_*`. */
export type Move3DDir = 'left' | 'right' | 'up' | 'down';
/** The 3D Grid submenu (`EDA_3D_ACTIONS::noGrid` / `show{10,5,2_5,1}mmGrid`). */
export type Grid3D = 'none' | '10mm' | '5mm' | '2.5mm' | '1mm';
/** What the 5-pane status bar shows (`EDA_3D_VIEWER_STATUSBAR`). */
/**
* `EDA_3D_CANVAS::DisplayStatus` and the two reporters beside it: the panes
* are ACTIVITY ("Loading...", "Last render time N ms"), HOVERED_ITEM (the
* footprint/pad/net under the cursor), X_POS `dx %3.2f`, Y_POS `dy %3.2f`
* and ZOOM_LEVEL `zoom %3.2f` — where dx/dy are the camera's pan
* (`m_camera_pos.xy`, 3D units) and zoom is `1 / m_zoom`.
*/
export interface Viewer3DStatus {
dx: number;
dy: number;
zoom: number;
activity: string;
hovered: string;
}
export interface Viewer3D {
dispose: () => void;
// -- View menu / top toolbar commands ------------------------------------
/** `ACTIONS::zoomInCenter` — 1.26x, three steps per doubling. */
zoomIn: () => void;
/** `ACTIONS::zoomOutCenter`. */
zoomOut: () => void;
/** `ACTIONS::zoomFitScreen` — back to the initial framing. */
zoomFit: () => void;
/** `ACTIONS::zoomRedraw`. */
redraw: () => void;
/** One of the six axis-aligned views. */
setView: (dir: View3DDir) => void;
/** `EDA_3D_ACTIONS::flipView` — 180 deg about Y. */
flip: () => void;
/** `EDA_3D_ACTIONS::homeView` — reset the camera. */
home: () => void;
/** `EDA_3D_ACTIONS::rotate{X,Y,Z}{CW,CCW}`, `rotation_increment` degrees. */
rotate: (axis: Rotate3DAxis, cw: boolean) => void;
/** `VIEW3D_PAN_*`. */
move: (dir: Move3DDir) => void;
/** `EDA_3D_ACTIONS::toggleOrtho`. */
setOrtho: (on: boolean) => void;
/** The 3D Grid submenu. */
setGrid: (grid: Grid3D) => void;
/**
* `EDA_3D_VIEWER_SETTINGS::m_Camera` — Preferences > 3D Viewer > General's
* Camera Options, applied live rather than at mount.
*/
setCamera: (o: Partial<Viewer3dCameraOptions>) => void;
/** `EDA_3D_ACTIONS::pivotCenter` (Space) — look at the board point under the cursor. */
pivotCenter: () => void;
/**
* `EDA_3D_VIEWER_FRAME::NewDisplay( true )` → `ReloadRequest()`: rebuild the
* board scene for a new board / stackup / render set on the SAME canvas and
* camera, beside the frame on screen, and swap once its models are in —
* the previous picture stays up until then, as upstream's does while
* `reload()` runs. The camera, grid, selection and rollover survive.
*/
reload: (
board: import('@ziroeda/pcbnew/board.js').BOARD,
stackup: import('./board_adapter_colors.js').StackupColors | undefined,
render: Viewer3dRenderOptions,
projectFiles?: { name: string; text: string }[],
) => void;
/** `GetCurrentCamera().GetViewMatrix()` — what a saved viewport (`VIEWPORT3D`) holds. */
getViewMatrix: () => number[];
/** `GetCurrentCamera().SetViewMatrix()` — `doApplyViewport`. */
setViewMatrix: (m: readonly number[]) => void;
/**
* `FOOTPRINT::IsSelected()` as `renderOpaqueModels` reads it — the board
* editor's selection, by footprint index, drawn in the selection colour.
*/
setSelectedFootprints: (footprints: ReadonlySet<number>) => void;
/**
* `EDA_3D_CANVAS::OnLeftUp`'s `$SELECT: 0,F<ref>` — a click on a model or
* pad names its footprint, a click on nothing sends an empty list. The
* board editor treats it exactly as a `$SELECT` from the schematic.
*/
onSelect?: (parts: string[]) => void;
// -- File / Edit menu ----------------------------------------------------
/** `EDA_3D_ACTIONS::exportImage` — the current view as a PNG blob. */
snapshot: () => Promise<Blob | null>;
/** Called on pointer move / camera change to feed the status bar. */
onStatus?: (s: Viewer3DStatus) => void;
/** The status bar's fields as they stand — what a listener attached late has missed. */
readonly status: Viewer3DStatus;
}
/**
* `EDA_3D_VIEWER_SETTINGS::m_Render`, as the three.js scene reads it.
*
* The settings file's own shape is `prefs/settings.ts`' `Viewer3dRender`; this
* is the subset `mount3DViewer` can honour, named the way a renderer talks
* rather than the way a JSON key does. A field absent means "the file's
* default", which is what a viewer built with no settings object gets upstream.
*
* It lives beside `Grid3D` for the same reason that does: `viewer3dMenus.ts`
* and `Viewer3DFrame.tsx` both need the type, and importing it from `pcb3d.js`
* would drag three.js and the STEP loader into `qa`'s typecheck.
*/
export interface Viewer3dRenderOptions {
/** `render.show_zones` — zone fills in the copper layer. */
showZones?: boolean;
/** `render.material_mode`, a `MATERIAL_MODE`: 0 NORMAL, 1 DIFFUSE_ONLY, 2 CAD. */
materialMode?: 0 | 1 | 2;
/** `render.opengl_AA_mode`, an `ANTIALIASING_MODE`: 0 is NONE. */
antiAliasing?: 0 | 1 | 2 | 3;
/** `render.opengl_show_model_bbox` — a `Box3Helper` around each 3D model. */
showModelBbox?: boolean;
/** `render.opengl_selection_color`, as CSS. */
selectionColor?: string;
/** `render.opengl_highlight_on_rollover` (default true). */
highlightOnRollover?: boolean;
/**
* `BOARD_ADAPTER::GetVisibleLayers()` as the appearance pane resolved it —
* the `LAYER_3D_*` / `LAYER_FP_*` flags that are on. Given, it overrides
* every `show*` boolean here; absent, the plot settings decide.
*/
visible3d?: ReadonlySet<string>;
/** `render.use_board_editor_copper_colors` (default false), and `m_BoardEditorColors[F_Cu/B_Cu]`. */
useBoardEditorCopperColors?: boolean;
boardEditorCopperColors?: {
'F.Cu': import('@ziroeda/common/gal/color4d.js').Color4d;
'B.Cu': import('@ziroeda/common/gal/color4d.js').Color4d;
};
/** `GetLayerColors()` as the pane resolved it (preset, stackup, swatches). */
layerColors?: ReadonlyMap<string, import('@ziroeda/common/gal/color4d.js').Color4d>;
/**
* `EDA_3D_VIEWER_SETTINGS::m_UseStackupColors` — the appearance panel's
* "Use board stackup colors". Stored true, but the first open of the frame
* clears it (eda_3d_viewer_frame.cpp:574), so the working default is
* FALSE: the colour theme's `3d_viewer.*` entries.
*/
useStackupColors?: boolean;
/** `BOARD::IsFootprintHolder()` — the footprint editor/browser's board skips the ×1.6 "home zoom" hack. */
footprintHolder?: boolean;
/** `render.show_fp_references` / `show_fp_values` / `show_fp_text` (default true). */
showFpReferences?: boolean;
showFpValues?: boolean;
showFpText?: boolean;
/** `render.opengl_show_off_board_silk` (default false). */
showOffBoardSilk?: boolean;
/** `render.subtract_mask_from_silk` (default false). */
subtractMaskFromSilk?: boolean;
/** `render.clip_silk_on_via_annulus` (default false). */
clipSilkOnViaAnnuli?: boolean;
/** `render.show_plated_barrels` (default true). */
showPlatedBarrels?: boolean;
/** `render.plated_and_bare_copper` (default false): finish colour only where the mask opens. */
differentiatePlatedCopper?: boolean;
/** `render.opengl_copper_thickness` (default true): extrude the layers' walls. */
copperThickness?: boolean;
/** `render.show_board_body` (default true). */
showBoardBody?: boolean;
/** `render.show_soldermask_top` / `_bottom` (default true). */
showSoldermaskTop?: boolean;
showSoldermaskBottom?: boolean;
/** `render.show_navigator` (default true): the axis spheres in the corner. */
showNavigator?: boolean;
/** `render.show_footprints_{insert,normal,virtual,not_in_posfile,dnp}`. */
showFootprintsInsert?: boolean;
showFootprintsNormal?: boolean;
showFootprintsVirtual?: boolean;
showFootprintsNotInPosfile?: boolean;
showFootprintsDnp?: boolean;
}
/**
* `EDA_3D_VIEWER_SETTINGS::m_Camera`, as the scene reads it.
*
* Applied through a setter rather than at mount: `EDA_3D_CANVAS` re-reads these
* on `CommonSettingsChanged`, and rebuilding the scene to change a rotation
* step would re-tessellate every STEP model in it.
*/
export interface Viewer3dCameraOptions {
/** `camera.rotation_increment`, DEGREES. */
rotationIncrement: number;
/** `camera.animation_enabled` — whether a view change is animated at all. */
animationEnabled: boolean;
/** `camera.moving_speed_multiplier`, the 1..5 slider. */
movingSpeedMultiplier: number;
}
/**
* What a frame hands the 3D viewer: the BOARD to show, wrapped so that a new
* handle means "the board changed" (`EDA_3D_VIEWER_FRAME::NewDisplay`) while
* the BOARD itself stays the one model.
*/
export interface BOARD_3D_HANDLE {
readonly k: import('@ziroeda/pcbnew/board.js').BOARD;
}
+122
View File
@@ -0,0 +1,122 @@
# Changelog
All notable changes to ZiroEDA Designer, newest first. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and versions follow
[Semantic Versioning](https://semver.org/): while ZiroEDA is in beta the major
version is 0, and every minor version is a milestone. Each version is a git tag
(`v0.9.0`, ...) on the commit it describes.
Each entry says what changed for someone using ZiroEDA. The commit history has
the engineering detail (3,700+ commits since 29 June 2026).
## [Unreleased]
### Changed
- Anonymous usage counts no longer switch off for Do Not Track, a signal the
W3C abandoned in 2019. They still switch off for Global Privacy Control and
with the in-app privacy setting, and they never include which project.
## [0.9.0] - 2026-10-20
KiCad's own outputs, GitHub projects, and a faster board editor.
### Added
- **Open any public KiCad project on GitHub** straight from its address:
`designer.ziroeda.com/gh/<owner>/<repo>`, read-only, with "Save a copy" to
make it yours. An "Open in ZiroEDA" badge for repository READMEs.
- **Gerber and PDF output through KiCad's own plotters**, so fabrication and
documentation files come out the way KiCad writes them.
- **Electrical Rules Check runs KiCad's full ERC tester**, including library,
footprint-link, text-variable and simulation-model checks.
- **Zone fills run in the background** with KiCad's progress dialogs, and the
board can draw in a background worker, so a large board no longer freezes
the window.
- Anonymous usage counts (which kind of screen is open and for how long, never
which project), opt-out, off under Do Not Track.
### Fixed
- Accounts created before end-to-end encryption (10 September) were refused
with their correct password and told nothing. Sign-in now explains the
one-time upgrade: use "Forgot password?" once; no recovery key is needed.
- ERC no longer flags every title-block field of a correct schematic.
- Toolbar toggles and zone display switches no longer repaint the whole board.
## [0.8.0] - 2026-09-27 - Public beta
### Added
- **Live multiplayer in the schematic editor**: edit a schematic together in
real time, with everyone's cursor and selection, **end-to-end encrypted**
like the projects themselves. Contributed by
[@kaminaris](https://github.com/kaminaris) (#638).
- **KiCad's graphics engine on WebGL2**: the board editor now draws through a
port of KiCad's own GAL renderer, shaders, antialiasing and bitmap font.
- Public beta opened at designer.ziroeda.com.
## [0.7.0] - 2026-09-13 - End-to-end encryption
### Added
- **End-to-end encrypted cloud projects.** Every project has its own key and is
encrypted in the browser before upload; the server stores ciphertext only.
Board files, schematics, file names and project metadata are all covered.
- A **recovery key**, shown once at sign-up, that is the only way back into
encrypted projects if the password is forgotten.
- Your password never reaches the server; it is used to derive the keys.
## [0.6.0] - 2026-09-06 - Sharing
### Added
- **Share a project by link or invite**, so someone else opens the real
project in their browser instead of a zip file or screenshots.
- Project version history in the cloud, with compare-and-swap saves so two
devices cannot silently overwrite each other.
## [0.5.0] - 2026-08-16 - Routing
### Added
- **KiCad's interactive router (PNS)**: route tracks with push-and-shove, the
same router KiCad uses, including interactive differential-pair routing.
- **Design Rules Check** in the board editor, including copper-sliver checks.
- Netlist exports, among them the PADS, CadStar and Cadence Allegro formats.
## [0.4.0] - 2026-08-02 - Zones and schematic-to-board
### Added
- **Copper zones**: pour, refill and hatch-pattern fills that KiCad reads back
unchanged.
- **Update PCB from Schematic**, the step that turns a schematic into a board.
## [0.3.0] - 2026-07-19 - The KiCad tools
### Added
- **Gerber Viewer**. Contributed by [@gcoenwebber](https://github.com/gcoenwebber).
- **PCB Calculator** and the **Image Converter**.
- The Plugin and Content Manager.
## [0.2.0] - 2026-07-12 - Accounts and cloud
### Added
- **Accounts and cloud projects**: sign in and open your projects from any
device.
- **Symbol Editor** and **Footprint Editor**.
- Demo projects that open with no sign-up.
- Click selection and a Properties readout in the PCB editor.
## [0.1.0] - 2026-07-06 - First editors
### Added
- **Schematic editor** reading and writing `.kicad_sch` losslessly: symbols
from KiCad's libraries, wires, selection, move, undo and redo, save.
- **PCB editor**, first version: reads `.kicad_pcb` and draws it like KiCad.
- **3D viewer** for boards.
- The KiCad-style project manager home screen.
[Unreleased]: https://github.com/ZiroEDA/ziro-designer/compare/v0.9.0...HEAD
[0.9.0]: https://github.com/ZiroEDA/ziro-designer/compare/v0.8.0...v0.9.0
[0.8.0]: https://github.com/ZiroEDA/ziro-designer/compare/v0.7.0...v0.8.0
[0.7.0]: https://github.com/ZiroEDA/ziro-designer/compare/v0.6.0...v0.7.0
[0.6.0]: https://github.com/ZiroEDA/ziro-designer/compare/v0.5.0...v0.6.0
[0.5.0]: https://github.com/ZiroEDA/ziro-designer/compare/v0.4.0...v0.5.0
[0.4.0]: https://github.com/ZiroEDA/ziro-designer/compare/v0.3.0...v0.4.0
[0.3.0]: https://github.com/ZiroEDA/ziro-designer/compare/v0.2.0...v0.3.0
[0.2.0]: https://github.com/ZiroEDA/ziro-designer/compare/v0.1.0...v0.2.0
[0.1.0]: https://github.com/ZiroEDA/ziro-designer/releases/tag/v0.1.0
+138
View File
@@ -0,0 +1,138 @@
# Working on ZiroEDA
ZiroEDA is a port of KiCad 10.0.6 to the browser. The reference source is
pinned at `/home/akshay/kicad-reference` (checked out at tag `10.0.6`) — read
that, never KiCad master, because the parity target is the installed build.
When Ubuntu updates the `kicad` package, move the reference tag with it:
`kicad-cli version` and `git -C /home/akshay/kicad-reference describe --tags`
must agree, or every kicad-cli oracle is checking against a different version
than the source we port.
**The manual is on disk too**, at the same version, and it is the second half of
the answer whenever the source is ambiguous about *intent*:
| | |
|---|---|
| `/home/akshay/kicad-docs` | the installed `kicad-doc-en` HTML (a symlink, so it tracks the package), images included |
| `/home/akshay/kicad-docs-text` | the same, tags stripped, for `grep` |
`eeschema.txt` and `pcbnew.txt` are ~500 kB and ~660 kB of prose. Reach for them
when a reading of the C++ could go two ways — what a control is *for*, which of
two behaviours is the documented one, what a warning actually means. Several
things have been implemented backwards here from a defensible but wrong reading
of the source; the manual usually settles those in one grep.
The goal is that a user cannot tell whether they are in KiCad or in ours.
## The central-value rule
**Wherever KiCad gets a value from a shared place, we must get it from ours.
Never a local literal.**
| KiCad asks | we ask |
|---|---|
| the GTK theme (`wxSYS_*`, `gtk-font-name`, the Yaru stylesheet) | the tokens in `common/widgets/shell.css` |
| `common/` — `EDA_TEXT`, `SEG`, `StrNumCmp`, `COLOR4D`, `PLOTTER` statics | `common/**` |
| a base class every subclass inherits | one shared module, never a per-editor copy |
| its own data table — resistor bands, layer palette | mirror *that data*; do not invent |
**This is not only fonts.** It covers colours, sizes, spacing, row pitch, control
metrics, pen widths, strings, and the widgets themselves.
### Chrome versus data
- **Chrome** is anything the theme decides: a face colour, a border, a font, a
control height, padding. A literal here means we have drifted, because KiCad
never wrote one — it asked GTK, and that single answer is why all of KiCad's
launchers look like each other.
- **Data** is a value KiCad itself hardcodes: the resistor colour-code bands, the
galvanic series, the built-in colour themes. These stay local, but must mirror
KiCad's own table rather than our invention.
A surviving literal should carry a comment saying which of the two it is.
### Why this keeps happening
1. `.ze-app`, the root every launcher inherits from, hardcoded `13px` and a
`"Segoe UI"` stack while `--ui-font-size` and `--ui-font-family` sat unused in
the same file.
2. The drawing sheet wrote every metric as a literal — label font 11px against
KiCad's 14.67, row pitch 26 against 37 — and its notebook tabs rendered in
**Arial**, because a bare `<button>` takes the user-agent font unless
something says `font: inherit`.
3. The calculator re-invented the GTK theme in `calculator.css`: 13px/system-ui,
`#1d1f23` fields, `#55585e` borders, and an orange Calculate button that
exists nowhere in `pcb_calculator`.
### Specificity is the trap that hides the fix
A launcher-local rule at (0,2,0) silently beats a shared widget at (0,1,0), so
fixing the shared thing changes nothing at the call site. The fix is never to
restate the right value locally — it is to state **nothing** locally.
## Verifying a change
- Verify by **mutating the implementation** and confirming a test fails.
Typecheck every mutant *before* running its tests: one that does not compile is
a false negative, not a kill. Score build failures separately from survivors.
- **Mutate the test too.** Four shapes of test cannot fail: an expectation
computed by calling the code under test; a file-level check where the rule is
per-occurrence; a value nothing ever reads; and a rule scoped to the directory
a bug was found in.
- If a behaviour change moves **zero** existing expectations, that is the
finding: the behaviour was never pinned.
- Never re-baseline a moved expectation to whatever the new code prints.
Re-derive it from the C++ or from a measurement, and say why it is right.
- **Confirm every mutant actually applied.** An edit whose anchor missed leaves
the file untouched, and an untouched file passes its tests - indistinguishable
from a mutant that was killed. Assert the file changed before scoring it, and
commit the baseline first: a sweep that restores with `git checkout --` over
an uncommitted baseline reverts the feature on its first restore.
- **A number GTK or wx decides can be measured, not guessed.** `qa/probes/`
builds the widget with wxWidgets and asks it - the same call KiCad makes, on
this machine, with this theme. That beats reading Yaru's stylesheet, sampling
a screenshot pixel, or deriving from Pango metrics; all three have been wrong
here. Two derivations agreeing corroborate only if they are independent.
## CI
`biome check .` judged by the **error count** at `--diagnostic-level=error`
(unused imports are warnings here, not errors), `pnpm -r typecheck`,
`pnpm -r test`, `pnpm -C designer build`.
**The biome baseline is not the same in every tree.** In the main checkout it is
`Found 1 error`, and that one comes from a gitignored `.claude/settings.local.json`.
A fresh worktree does not have that file, so **its baseline is zero** and biome
prints no `Found` line at all. Read the count against the tree you are in: in a
worktree, `Found 1 error` means you have introduced one, not that you are green.
Confirm it by running biome on a pristine worktree of `origin/main` if in doubt.
`designer/save_cost` and `eeschema/writer_kicad_grammar` are wall-clock
assertions and flake under load — re-run in isolation before believing either.
**Hook dependency lists are not optional (#7).** Every value a `useEffect` /
`useCallback` / `useMemo` body reads goes in its list, or is read through a
ref; an effect whose dependency is only the *trigger* gets a
`biome-ignore lint/correctness/useExhaustiveDependencies: <why>` on the line
above. Never the autofix. Check with
`npx biome lint <file> --only=correctness/useExhaustiveDependencies` before
committing a `.tsx` — biome's default output stops at 20 diagnostics, so a
plain `biome lint` under-reports this badly.
## Durability
Scratch space under `/tmp` is wiped without warning. Anything worth keeping —
findings, captures, harnesses — belongs in `$HOME` or in the repo. Commit each
coherent piece as you finish it rather than at the end.
## Worktrees and `qa`'s dependencies
`qa` gained a DOM in Aug 2026 — `happy-dom`, `@testing-library/react`, and
`react` itself, because the JSX runtime has to resolve from `qa`. A git
worktree keeps the `node_modules` it was created with and does **not** pick up
a dependency added afterwards, so an older worktree fails with
`Failed to resolve import "react/jsx-dev-runtime"` while `main` is green.
**Run `pnpm install` in a new worktree before trusting its gate.** A worktree
whose `node_modules` predates a dependency will report failures that are not
yours — and, worse, can report a passing typecheck for the same reason.
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+179
View File
@@ -0,0 +1,179 @@
# Third-party notices
ZiroEDA is a browser-native reimplementation of the KiCad workflow, and it
reuses a substantial amount of KiCad's own work. This file records what came
from where, and under which terms.
ZiroEDA is distributed under the GNU General Public License, version 3 or
later (see [LICENSE](./LICENSE)). Every licence below is compatible with that,
so the combined work is governed by the GPL. Attribution, however, is required
independently of compatibility, which is what this file provides.
ZiroEDA is not affiliated with or endorsed by the KiCad project. "KiCad" is a
trademark of its respective owners.
## KiCad source code
Copyright The KiCad Developers. See `AUTHORS.txt` in the KiCad source
distribution for the list of contributors.
Licensed under the GNU General Public License, version 3 or later.
- Source: https://gitlab.com/kicad/code/kicad
- Licence: https://www.kicad.org/about/licenses/
Large parts of `common/`, `eeschema/`, `pcbnew/`, `gerbview/`,
`pcb_calculator/` and `libs/` are ports of KiCad's C++ implementation into
TypeScript. They follow KiCad's source layout, algorithms and file formats
closely, and individual files name the upstream file they were ported from.
These are derived works of KiCad and are licensed under the GPL accordingly.
## KiCad icons
Copyright The KiCad Developers. Licensed under the GNU General Public License,
version 3 or later.
The toolbar and menu icons in `designer/src/assets/` are taken from KiCad's
`resources/bitmaps_png/sources/`. Most are reproduced unmodified.
## KiCad symbol, footprint and 3D model libraries
Copyright the KiCad Libraries Team and contributors.
Licensed under the Creative Commons Attribution-ShareAlike 4.0 International
licence, **with the KiCad library exception**. The exception is important for
users of this application: it means that using these symbols and footprints in
a design does not place the resulting design under the share-alike terms.
- Source: https://gitlab.com/kicad/libraries
- Licence and exception: https://www.kicad.org/libraries/license/
This applies to:
- the symbol libraries bundled in `designer/src/pcm/defaultRepo.ts`, which are
reproduced verbatim from KiCad's official libraries;
- the symbol, footprint and 3D model libraries the application downloads at
runtime from ZiroEDA's library host.
ZiroEDA packages and hosts this content. It did not author it.
## KiCad colour themes
The colour themes in every editor's Colors page beyond the two built-ins are
Thomas Pointhuber's `kicad-color-schemes`, the same ones KiCad's own repository
offers through its Plugin and Content Manager. They are dedicated to the public
domain under CC0 1.0 Universal.
- Source: https://github.com/pointhi/kicad-color-schemes
- Licence: https://creativecommons.org/publicdomain/zero/1.0/
The theme files under `designer/src/assets/color_schemes/` are reproduced
verbatim. Their designers, as each package's metadata names them: Black/White,
Solarized Dark and Solarized Light — Thomas Pointhuber; Eagle Dark — Rachel
Mant; Nord — Jordi Pakey-Rodriguez (@0xdec); wDark and wLight — Jan Vykydal
(wykys).
## rectpack2d
Copyright (c) 2017 Patryk Czachurski and contributors. Licensed under the MIT
licence.
`libs/rectpack2d/` is a TypeScript port of the header-only C++ library that
KiCad vendors in `thirdparty/rectpack2d/`.
- Source: https://github.com/TeamHypersomnia/rectpack2D
> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal
> in the Software without restriction, including without limitation the rights
> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
> copies of the Software, and to permit persons to whom the Software is
> furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in all
> copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
> SOFTWARE.
## earcut
Copyright (c) 2026, Mapbox. Licensed under the ISC licence.
`designer/src/render/gl/vendor/earcut.js` is earcut 3.2.3, unmodified, with its
type declarations alongside it. It triangulates the board's filled areas — copper
pours and the clearances punched through them — for the WebGL renderer.
Vendored rather than depended on: it is one self-contained file, and it is
excluded from formatting and linting so it stays byte-identical to upstream.
- Source: https://github.com/mapbox/earcut
- Licence text: `designer/src/render/gl/vendor/earcut-LICENSE.txt`
> Permission to use, copy, modify, and/or distribute this software for any
> purpose with or without fee is hereby granted, provided that the above
> copyright notice and this permission notice appear in all copies.
>
> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
> REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
> FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
> INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
> LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
> OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
> PERFORMANCE OF THIS SOFTWARE.
## GNU C Library (libm)
Copyright (C) 2001-2024 Free Software Foundation, Inc. Licensed under the GNU
Lesser General Public License, version 2.1 or later.
`libs/kimath/src/math/libm.ts` and `libs/kimath/src/math/libm_tables.ts` are
ports of glibc 2.39's `sysdeps/ieee754/dbl-64` `sin`, `cos`, `atan2`, `asin`,
`acos` (the IBM Accurate Mathematical Library, `s_sin.c`, `branred.c`,
`e_atan2.c`, `e_asin.c` with their tables) and `hypot` (`e_hypot.c`). KiCad's
zone filler links against that libm, and its polygon offsets round the way
those routines round; V8's own `Math.*` differs in the last bit often enough
to move a vertex by a nanometre.
- Source: https://ftp.gnu.org/gnu/glibc/glibc-2.39.tar.xz
- Licence: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
## Ubuntu (bitmap font atlas)
`designer/src/render/gl/bitmap_font.png` and the metrics in `bitmap_font.ts` are
generated from KiCad's `common/gal/opengl/bitmap_font_img.c` and
`bitmap_font_desc.c`, a signed-distance-field atlas of the **Ubuntu** typeface
baked by msdf-atlasgen. KiCad's OpenGL GAL draws pad numbers and net names from
it rather than from the stroke font, so matching what pcbnew puts on screen means
shipping the same glyphs. `tools/gen_bitmap_font.mjs` regenerates both from a
KiCad checkout; it repacks the printable ASCII range into a smaller sheet and
copies the texels unchanged.
Ubuntu is Copyright 2010, 2011 Canonical Ltd, licensed under the Ubuntu Font
Licence 1.0.
- Licence text: `designer/src/render/gl/bitmap_font-LICENCE.txt`
## Runtime dependencies
The npm packages listed in each `package.json` carry their own licences. Run
`pnpm licenses list` to enumerate them for a given install.
## Yaru icon theme
`bitmaps_png/sources/theme/dialog-warning.png`,
`bitmaps_png/sources/theme/dialog-information.png` and
`bitmaps_png/sources/theme/window-close.png` are byte-identical copies of
Ubuntu's Yaru icon theme (`/usr/share/icons/Yaru/16x16/`), Copyright the Yaru
authors, licensed **CC-BY-SA-4.0** — https://github.com/ubuntu/yaru
They are here because `WX_INFOBAR` does not draw KiCad bitmaps at this call
site. `wxICON_WARNING`, `wxICON_INFORMATION` and `wxBitmapButton::NewCloseButton` ask the art
provider, so the glyphs KiCad shows are the desktop theme's; using KiCad's own
`dialog_warning.svg` produced an amber triangle where KiCad draws a red disc.
CC-BY-SA-4.0 is one-way compatible with this project's GPL-3.0-or-later.
+69
View File
@@ -0,0 +1,69 @@
# ZiroEDA: Philosophy & Compatibility Promise
ZiroEDA exists for one reason: the world's largest open-source EDA community
should be able to open a browser tab and be instantly at home. Same UI, same
hotkeys, same files. **Open a tab, not learn a tool.**
This document is our public commitment about how ZiroEDA relates to the
[KiCad](https://www.kicad.org/) project and its community. It is written to be
held against us.
## What ZiroEDA is
- A **browser-native port of KiCad** (TypeScript and WebGL instead of C++
and wxWidgets) that reads and writes KiCad's native file formats directly.
- **A complement to KiCad desktop, not a replacement for it.** KiCad remains
the deep, mature desktop suite. ZiroEDA is the way you open, share, review,
and edit those same projects from any machine with a browser.
- **GPL-3.0-or-later, like KiCad itself.** The core of ZiroEDA is and will
remain free software. There is no proprietary fork of the editor waiting in
the wings.
## What ZiroEDA is not
- **Not a fork of KiCad's repository.** ZiroEDA is a TypeScript translation
of KiCad's C++ source, kept file for file against a pinned KiCad release, so
it carries KiCad's GPL and credits it in [NOTICE.md](./NOTICE.md) (see
[README: How it is built](./README.md#how-it-is-built)).
- **Not affiliated with or endorsed by the KiCad project.** "KiCad" is a
trademark of its respective owners. We describe ourselves as
*KiCad-compatible*; we do not use the KiCad name or logo as our brand.
- **Not a walled garden.** Your designs live in `.kicad_sch` / `.kicad_pcb` /
`.kicad_sym` / `.kicad_mod` files that you own and that open in desktop KiCad
at any time. Leaving ZiroEDA must never cost you anything.
## The compatibility promise
1. **KiCad desktop is the upstream source of truth for the file formats.**
We follow the formats KiCad defines. We do not extend them, we do not add
Ziro-only tokens to them, and we never will.
2. **Anything ZiroEDA needs beyond the format lives in sidecar files**
(for example a `.ziro/` folder next to the project), never inside
KiCad-format files. A project touched by ZiroEDA must remain a 100% valid
KiCad project.
3. **Round-trip fidelity is a release blocker.** A file opened and saved by
ZiroEDA must load in desktop KiCad with no loss and no surprises. Format
regressions are treated as our highest-severity bugs.
4. **When we find format ambiguities or undocumented behaviour** while
reimplementing, we report them upstream (issues, documentation, test
cases) so both projects benefit.
## Giving back
Being commercially built around KiCad's ecosystem creates an obligation:
- We contribute upstream what a reimplementation uniquely produces: format
edge cases, documentation of undocumented behaviour, and round-trip test
corpora.
- As ZiroEDA earns revenue, a share of it goes to KiCad development (via the
project's official donation channels). Growing the open ecosystem grows us.
- We engage in the open, in KiCad community spaces, as ourselves, before
anyone has to ask who we are.
## The open-core boundary
The editor, everything needed to open, edit, and save a KiCad project in the
browser, is free and GPL, forever. What we charge for is what a hosted
service uniquely adds on top: cloud compute (simulation, autorouting, batch
DRC), real-time team collaboration, and AI assistance. If a feature's absence
would lock your data or break the local workflow, it belongs in the free core.
+197
View File
@@ -0,0 +1,197 @@
# ZiroEDA
**KiCad-compatible electronics design in a browser tab. Nothing to install.**
**[Open the editor →](https://designer.ziroeda.com)** ·
**[Try a demo project, no sign-up →](https://designer.ziroeda.com/demo/ecc83)** ·
**[What's new (changelog) →](./CHANGELOG.md)** ·
**[Join the Discord →](https://www.ziroeda.com/discord)**
<a href="https://www.ziroeda.com/designer#video"><img src="docs/public/screenshots/intro-video.jpg" alt="Watch the one-minute introduction to ZiroEDA Designer" width="100%"></a>
ZiroEDA is an open-source, browser-native port of KiCad 10: the schematic
editor, the PCB editor, and the tools around them, running in any modern
browser. It reads and writes KiCad's native files directly, so a `.kicad_pro`
made on the desktop opens here with no import step, and a project saved here
opens back in KiCad unchanged.
ZiroEDA **extends the KiCad ecosystem; it does not replace KiCad.** For very
large, heavy designs, desktop KiCad is the right tool. ZiroEDA is for
everything around it: small and medium projects, working from any machine,
reviewing a board without installing anything, and sharing a project by link.
Your projects live in the cloud **end-to-end encrypted**, so not even we can
read them, and they stay ordinary KiCad files you can take back to the desktop
at any time.
> ZiroEDA is an independent project. It is **not** affiliated with or endorsed
> by the KiCad project; "KiCad" is a trademark of its respective owners. See
> [PHILOSOPHY.md](./PHILOSOPHY.md) for how we relate to it.
## Who it is for
- **Students and labs.** College lab PCs and Chromebooks where you cannot
install software. Open a tab and design.
- **Teams and reviewers.** Send a link instead of a zip; the other side opens
the real project, not a screenshot.
- **KiCad users away from their desk.** Open, check and edit the same
projects from any machine, then carry on in desktop KiCad.
- **Anyone browsing open hardware.** Open any public KiCad project on GitHub
straight from its address.
## What works today
| | |
|---|---|
| **Schematic editor** | KiCad's eeschema: symbols, wires, buses, labels, hierarchical sheets, annotation, ERC, symbol fields table, plot and print |
| **PCB editor** | KiCad's pcbnew: footprints, interactive router, zones with KiCad's own fill algorithm, DRC, board setup, 3D viewer, plotting and fabrication outputs |
| **Library editors** | Symbol editor, footprint editor, Assign Footprints (CvPcb) |
| **Other KiCad tools** | Gerber viewer, PCB calculator, image converter, drawing sheet editor |
| **Libraries** | KiCad's official symbol, footprint and 3D model libraries, served from the cloud |
| **Cloud projects** | End-to-end encrypted; open them from any device; share with collaborators by invite or link; export as ordinary KiCad files at any time |
| **Open from GitHub** | Any public repository's KiCad project opens read-only at `designer.ziroeda.com/gh/<owner>/<repo>`, with "Save a copy" to make it yours |
The port is ongoing and some dialogs and rarely used tools are not there yet.
If something you rely on is missing, [open an issue](https://github.com/ZiroEDA/ziro-designer/issues).
### Add an "Open in ZiroEDA" badge to your KiCad repository
Let visitors open your public KiCad project in their browser with one click.
Paste this into your README, with your own owner and repository name:
```markdown
[![Open in ZiroEDA](https://img.shields.io/badge/Open%20in-ZiroEDA-2f6feb)](https://designer.ziroeda.com/gh/OWNER/REPO)
```
## Screenshots
| | |
|---|---|
| ![The PCB editor with a four-layer ESP32 board](docs/public/screenshots/pcb.jpg) | ![The schematic editor with the CM5 Minima carrier board](docs/public/screenshots/schematic.jpg) |
| The PCB editor ([open this board](https://designer.ziroeda.com/demo/openair-max)) | The schematic editor ([open it](https://designer.ziroeda.com/demo/cm5_minima)) |
| ![The 3D viewer](docs/public/screenshots/3d.jpg) | ![A GitHub project opened from its address](docs/public/screenshots/github.jpg) |
| The 3D viewer | [Cynthion](https://designer.ziroeda.com/gh/greatscottgadgets/cynthion-hardware), opened from its GitHub address |
## Your designs stay yours: end-to-end encryption
Cloud projects are encrypted **in your browser, before upload**, with a key the
server never sees. What we store is ciphertext; there is no master key on our
side that opens it.
- Every project has its own random key. Board files, schematics, file names and
the project's metadata are all encrypted with it (AES-256-GCM).
- The project key is wrapped under your account key. Your account key is
wrapped twice: once by a key derived from your password (Argon2id), once by a
**recovery key** shown to you once at sign-up. Your password itself never
reaches the server.
- Sharing a project seals only its key to the collaborator's public key
(ECDH P-256), so sharing never re-encrypts or exposes the boards.
- Live collaboration traffic (edits, cursors, selections) travels under the
same project key.
- All of it uses the browser's built-in Web Crypto, so the whole scheme is in
this repository for anyone to audit.
The trade-off is real: lose both your password and your recovery key and your
encrypted projects cannot be recovered by anyone, including us.
Plain-language details: [docs/security.md](./docs/security.md). Design and
reasoning: [docs/encryption-design.md](./docs/encryption-design.md).
## How it is built
ZiroEDA is a **TypeScript port of KiCad's C++ source**, mirrored file for file
(`eeschema/`, `pcbnew/`, `common/`, `libs/` …) against the KiCad 10.0.6 tag, so
behaviour can be checked against the original line by line. KiCad's own
`kicad-cli` is used as a test oracle: our file writers, zone fills and plots are
compared against what KiCad itself produces.
| Concern | Choice |
| --- | --- |
| Language | TypeScript |
| UI | React, with KiCad's wxWidgets dialogs rebuilt to the same layout |
| 2D rendering | WebGL, with KiCad's own stroke and outline fonts |
| 3D viewer | three.js |
| Auth, cloud, realtime | Supabase |
| Crash reporting | Sentry (opt-out, scrubbed) |
| Build / monorepo | Vite + pnpm workspaces |
| Tests | Vitest (1,500+ test files), mutation-tested |
```
ziro-designer/
designer/ # the app: launcher, editor frames, cloud sync, encryption
eeschema/ # schematic engine (port of KiCad's eeschema/)
pcbnew/ # board engine (port of KiCad's pcbnew/)
common/ # shared KiCad classes: shapes, text, units, plotters, widgets
libs/ # kimath, core, sexpr (lossless S-expression parser)
gerbview/ cvpcb/ pcb_calculator/ pagelayout_editor/ bitmap2component/
qa/ # unit tests (qa/unittests/<module>) + fixtures
```
See **[STRUCTURE.md](./STRUCTURE.md)** for the full map and conventions.
## Run it locally
```bash
pnpm install
pnpm -C designer dev # http://localhost:5173/pcb/
pnpm -C designer build # typecheck + production build
pnpm -r test # all unit tests
pnpm -r typecheck
```
The app defaults to the `/pcb/` deployment path. Upload the contents of
`designer/dist/` to `/www/sites/cadworld-studio.robotquan.com/index/pcb/`
to serve it at `https://cadworld-studio.robotquan.com/pcb/`. Assets, frontend
routes and the PWA use this same base. For direct access to frontend routes,
configure Nginx with `try_files $uri $uri/ /pcb/index.html;` inside the
`location ^~ /pcb/` block. Use `VITE_BASE=/another-path/ pnpm -C designer build`
only when deploying to a different path.
For development, a clone starts with no configuration. Accounts, cloud
projects and sharing need a Supabase project; every integration is env-gated
and simply switches off when its variables are absent.
| Variable | Effect when unset |
| --- | --- |
| `VITE_SUPABASE_URL`, `VITE_SUPABASE_ANON_KEY` | Accounts, cloud sync and sharing disabled |
| `VITE_SUPABASE_STORAGE_BUCKET` | Cloud file storage disabled |
| `VITE_SENTRY_DSN` | Crash reporting disabled |
| `VITE_RELEASE` | Falls back to the build's git SHA |
| `SENTRY_ORG`, `SENTRY_PROJECT` | Source maps not uploaded (set in `vercel.json`) |
| `SENTRY_AUTH_TOKEN` | Source maps not uploaded (secret, dashboard only) |
| `SENTRY_URL` | Defaults to `https://de.sentry.io/` |
To self-host the cloud side, apply the migrations in `supabase/migrations/` to
your own Supabase project.
### Cloud sync design
- **Content-addressed, encrypted blobs.** Each file is stored under the hash of
its plaintext as `iv‖ciphertext`, so an upload only ever adds, a download is
verified after decryption, and earlier versions stay restorable.
- **Commit last.** Every blob is stored and confirmed present before the
project row that references it is written, so a failed push changes nothing.
- **Compare-and-swap on the version.** Two devices cannot silently overwrite
each other's work.
- **One transport interface** (`designer/src/cloud/backend.ts`); only
`supabaseBackend.ts` touches Supabase, so the sync logic is fully testable.
### Crash reporting
Opt-out (Preferences → Common → Privacy). Reports are scrubbed in
`designer/src/telemetry/scrub.ts`: file names and URL query strings are
removed, and no account or IP address is attached. Tracing, session replay and
profiling are off: this collects stack traces to fix bugs, not usage
analytics. Source maps are uploaded to Sentry and never deployed.
## License
GPL-3.0-or-later, the same as KiCad. See [LICENSE](./LICENSE).
Much of the engine is a TypeScript port of KiCad's C++, the icons are KiCad's,
and the symbol, footprint and 3D model libraries are KiCad's official
libraries. Code and icons are GPL; the libraries are CC-BY-SA 4.0 with the
KiCad library exception. Full attribution: [NOTICE.md](./NOTICE.md).
## Contact
Questions, bugs or collaboration: [open an issue](https://github.com/ZiroEDA/ziro-designer/issues),
chat with us on [Discord](https://www.ziroeda.com/discord), or write to **admin@ziroeda.com**.
+65
View File
@@ -0,0 +1,65 @@
# Repository structure
ZiroEDA is organised as a pnpm monorepo: one app package (`designer/`)
on top of framework-agnostic engine packages. The engine tree follows the
source-layout conventions of the upstream KiCad codebase, the one place in
the project where we deliberately keep that vocabulary, so ported logic has
an obvious home next to its C++ origin and stays easy to audit for
format-compatibility.
| Directory | Upstream counterpart | Contents |
| ---------------- | -------------------- | ------------------------------------------------------------------------ |
| `designer/` | *(ours)* | The ZiroEDA app (Vite + React): launcher/home, menus/toolbars, editor frames, auth + cloud sync, served libraries under `designer/public/` |
| `eeschema/` | `eeschema/` | Schematic engine: document model, `sch_io/sexpr` reader/writer, `connectivity/` (nets, ERC), `tools/` (interactive editing) |
| `pcbnew/` | `pcbnew/` | Board engine: board/footprint/pad/zone object model, `pcb_io/sexpr` parser + formatter, board and footprint editing |
| `gerbview/` | `gerbview/` | Gerber viewer engine: RS-274X Gerber + Excellon drill readers, `D_CODE` apertures, `APERTURE_MACRO` primitives, `GERBER_DRAW_ITEM` model, `GBR_LAYOUT`, `.gbrjob` job-file parsing |
| `bitmap2component/` | `bitmap2component/` | Image Converter: `BITMAPCONV_INFO` (trace and write symbol / footprint / PostScript / drawing sheet), `IMAGE_SIZE`, `BITMAP2CMP_PANEL` and its view, `BITMAP2CMP_FRAME`, `BITMAP2CMP_CONTROL`, `BITMAP2CMP_SETTINGS` — see its `STRUCTURE.md` |
| `pagelayout_editor/` | `pagelayout_editor/` | Drawing Sheet Editor (`pl_editor`): `PL_EDITOR_FRAME`, its layout, settings and undo/redo, the toolbars, the properties and inspector dialogs, `tools/` (the `PL_*` tools); per-unit table in `pagelayout_editor/STRUCTURE.md` |
| `cvpcb/` | `cvpcb/` | Assign Footprints (CvPcb): `CVPCB_MAINFRAME`'s COMPONENT list and association state, the listboxes, `auto_associate`, `tools/` (association and control), the footprint viewer's toolbars; the windows are still the app's. Per-unit table in `cvpcb/STRUCTURE.md` |
| `3d-viewer/` | `3d-viewer/` | The 3D viewer engine: the three.js scene builder (`3d_canvas`/`3d_rendering`'s counterpart), the OpenCascade STEP/IGES loader (`plugins/3d/occ`'s counterpart), board-outline tessellation, appearance data, the menu bar and toolbars. `EDA_3D_VIEWER_FRAME` itself is still the app's; see `3d-viewer/STRUCTURE.md` |
| `common/` | `common/` | Shared EDA classes: shapes, text, units, placement transforms, stroke `font/` |
| `pcb_calculator/`| `pcb_calculator/` + `common/transline_calculations/` | Calculator Tools engine: regulators, track/via/fusing current, E-series, electrical spacing (IPC-2221 + IEC 60664), board classes, galvanic corrosion, and the `transline/` models (microstrip, coupled microstrip, coplanar, coax, rectangular waveguide, stripline, twisted pair) |
| `libs/kimath/` | `libs/kimath/` | Math: `math/vector2`, `geometry/eda_angle`, `trigo` |
| `libs/core/` | `libs/core/` | Small shared utilities (`mirror`, flip directions) |
| `libs/potrace/` | `thirdparty/potrace` | potracelib 1.15, the tracer `bitmap2component` links, pinned bit for bit against KiCad's C |
| `libs/sexpr/` | `libs/sexpr/` | Lossless S-expression tokenizer/parser/serializer |
| `qa/` | `qa/` | Unit tests (`qa/unittests/<module>/`) and test fixtures (`qa/data/`) |
| `tools/` | *(ours)* | Offline build pipelines (not workspace packages): `models3d/` converts the upstream STEP 3D library to the hosted `.glb` set |
Each directory is a workspace package (`@ziroeda/<dir>`); `qa/` holds the
Vitest suites for all of them, arranged by the module under test.
## Conventions
- **Modules are named after their upstream counterpart files** (snake_case,
as upstream): `home/project_tree.ts` ↔ `kicad/project_tree.cpp`,
`home/project_archiver.ts` ↔ `common/project/project_archiver.cpp`,
`home/dialogs/dialog_template_selector.tsx` ↔
`kicad/dialogs/dialog_template_selector.cpp`. New modules should name their
counterpart in the header comment.
- **Product names, not tool names, for our own code.** The app lives in
`designer/` and file/folder names avoid third-party product names; data
fixtures keep their native file extensions (`.kicad_sch`, `.kicad_pcb`, …)
because that is the on-disk format itself.
- **Editor UI frames currently live in `designer/src/editors/`** (schematic,
pcb, symbol, footprint). Migrating each frame into its engine package is
planned once the shared-widget layer is extracted.
- **Shared chooser widgets live in `designer/src/widgets/`**, mirroring
upstream `common/widgets/` + `common/lib_tree_model*` (`lib_tree.tsx`,
`lib_tree_model.ts`, `lib_tree_model_adapter.ts`,
`footprint_preview_widget.tsx`, `footprint_select_widget.tsx`); editor-
specific widgets sit in `designer/src/editors/<frame>/widgets/` after
their upstream `<frame>/widgets/` counterparts.
- **The 3D viewer** moved to its own package, `3d-viewer/`, 09-28. Its frame,
`Viewer3DFrame.tsx` (`EDA_3D_VIEWER_FRAME`), is still in
`designer/src/editors/pcb/` — it calls the Preferences settings store
directly at dozens of sites and needs a `VIEWER3D_APP` interface (the
`CVPCB_APP` / `PL_EDITOR_APP` pattern) before it can follow; see
`3d-viewer/STRUCTURE.md`.
- **`designer/public/templates/`** holds project templates;
symbol/footprint/3D-model libraries under `designer/public/` are served as
static assets.
- **Future tools get their own engine dirs** following the same upstream
conventions (gerber viewer → `gerbview/` ✅, drawing-sheet editor →
`pagelayout_editor/` ✅, …), with their UI frames in the app. The Gerber
Viewer's UI frame lives in `designer/src/editors/gerbview/`.
+106
View File
@@ -0,0 +1,106 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
/**
* The tab's link to the AI agent running on the user's machine (`npx ziroeda-agent`): whether
* it is there and which AI it drives, and - while it is - a live link over which tool calls from
* the user's own AI app (Claude Code, Cursor, Codex... connected to the agent as an MCP server)
* reach this tab. Each runs like a panel tool call (runAiTool) and its answer goes back.
*/
import { useEffect, useState } from 'react';
import { AI_AGENT_URL } from './ai_flag.js';
import { runAiTool, type ToolOutput } from './ai_bridge.js';
export interface AgentState {
connected: boolean;
/** The AI the agent drives ("claude-code"), or null when it found none. */
engine: string | null;
}
/** How often the pane looks for the agent while it is not connected. */
const PROBE_MS = 5000;
export function useAgentLink(): AgentState {
const [state, setState] = useState<AgentState>({ connected: false, engine: null });
useEffect(() => {
let source: EventSource | null = null;
let timer: ReturnType<typeof setTimeout> | null = null;
let stopped = false;
const probe = async () => {
try {
const r = await fetch(`${AI_AGENT_URL}/health`);
const h = (await r.json()) as { ok?: boolean; engine?: string | null };
if (stopped || !h.ok) throw new Error('no agent');
setState({ connected: true, engine: h.engine ?? null });
open();
} catch {
if (stopped) return;
setState({ connected: false, engine: null });
timer = setTimeout(probe, PROBE_MS);
}
};
const open = () => {
source = new EventSource(`${AI_AGENT_URL}/link`);
source.addEventListener('tool', (ev) => {
const call = JSON.parse((ev as MessageEvent<string>).data) as {
id: string;
name: string;
args: Record<string, unknown>;
};
void runAiTool(call.name, call.args)
.catch((err: unknown): { out: ToolOutput } => ({
out: { text: `${call.name} failed: ${String(err)}`, isError: true, note: '' },
}))
.then(({ out }) =>
fetch(`${AI_AGENT_URL}/tool-result`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
id: call.id,
text: out.text,
isError: out.isError,
...(out.imagePng ? { imagePng: out.imagePng } : {}),
}),
}),
);
});
source.onerror = () => {
source?.close();
source = null;
if (stopped) return;
setState({ connected: false, engine: null });
timer = setTimeout(probe, PROBE_MS);
};
};
void probe();
return () => {
stopped = true;
source?.close();
if (timer) clearTimeout(timer);
};
}, []);
return state;
}
/** The line at the top of the pane: how to connect, or what is connected and how to use it elsewhere. */
export function AgentStatus({ agent }: { agent: AgentState }): JSX.Element {
if (!agent.connected)
return (
<div className="ze-ai-agent ze-ai-agent-off" data-testid="ai-agent-status">
Connect your AI: run <code>npx ziroeda-agent</code> in a terminal.
</div>
);
return (
<div className="ze-ai-agent ze-ai-agent-on" data-testid="ai-agent-status">
Connected
{agent.engine ? `: ${agent.engine === 'claude-code' ? 'Claude Code' : agent.engine}` : ''}.{' '}
From your own AI app, add the MCP server <code>npx ziroeda-agent --mcp</code>.
</div>
);
}
+87
View File
@@ -0,0 +1,87 @@
/**
* The seam between the AI pane and the editors. Each editor that the AI can
* drive registers a bridge for as long as its frame exists; a bridge owns
* the tools for its editor and runs them against the live document.
*/
export interface ApplyResult {
applied: number;
errors: string[];
/** Facts that help fix the errors, e.g. a part's real pin names. */
hints?: string[];
}
/** What a tool call answers. */
export interface ToolOutput {
text: string;
isError?: boolean;
/** A picture for the model (PNG, base64 without the data: prefix). */
imagePng?: string;
/** One line for the chat, so the user sees the model working. */
note: string;
}
/** The editors, plus the app shell (switching editors) and the project manager. */
export type EditorKind = 'sch' | 'pcb' | 'app' | 'project' | '3d';
export interface AiBridge {
kind: EditorKind;
/** The open document as compact text, sent when it changed since last seen. */
read(): string;
/** Run one of this editor's tools; null when the tool is not this editor's. */
run(name: string, args: Record<string, unknown>): Promise<ToolOutput> | null;
/** Refuse a tool before any bridge runs it (no project open); null lets it run. */
guard?(name: string): ToolOutput | null;
/** The open project's name (the app bridge); chats are kept per project. */
project?(): string | null;
/** Bring that editor to the front (the app bridge): the user watches the work. */
show?(kind: EditorKind): void;
}
const bridges = new Map<EditorKind, AiBridge>();
export function registerAiBridge(b: AiBridge): () => void {
bridges.set(b.kind, b);
return () => {
if (bridges.get(b.kind) === b) bridges.delete(b.kind);
};
}
export function aiBridge(kind: EditorKind): AiBridge | undefined {
return bridges.get(kind);
}
export function allBridges(): AiBridge[] {
return [...bridges.values()];
}
/**
* Run one agent tool on whichever bridge takes it: the app tools first, a guard may refuse.
* The chat pane's turns and tool calls from the user's own AI app (over the agent's link) both
* come through here. `kind` is the bridge that ran it (absent when none could).
*/
export async function runAiTool(
name: string,
args: Record<string, unknown>,
): Promise<{ out: ToolOutput; kind?: EditorKind }> {
for (const b of allBridges()) {
const refused = b.guard?.(name);
if (refused) return { out: refused };
}
for (const b of [...allBridges()].sort(
(x, y) => Number(y.kind === 'app') - Number(x.kind === 'app'),
)) {
const out = b.run(name, args);
if (out) {
// The editor doing the work is the one on screen.
if (b.kind === 'sch' || b.kind === 'pcb') aiBridge('app')?.show?.(b.kind);
return { out: await out, kind: b.kind };
}
}
return {
out: {
text: `Nothing open can run ${name} right now: open the editor it belongs to (open_editor) first.`,
isError: true,
note: `${name}: its editor is not open`,
},
};
}
+112
View File
@@ -0,0 +1,112 @@
/**
* Mounts the AI pane app-wide, docked on the right of every editor the way
* KiCad docks Properties or Appearance: a 5px AUI sash on its inner (left)
* edge to resize it, the editors shrinking to make room (html.ze-ai-open)
* while the frame's title bar still spans the window. Its toggle sits at the
* right end of that title bar, opening and closing it; Ctrl+Shift+A too.
*/
import { DockSash } from '@ziroeda/wx/wx_aui_sash.js';
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { AiChatPane } from './chat_pane.js';
import { DocViewer } from './doc_viewer.js';
/** [ours] KiCad has no such pane; a width that fits a chat and a tool line. */
const DEFAULT_WIDTH = 380;
const MIN_WIDTH = 280;
const WIDTH_KEY = 'ziroeda.ai.paneWidth';
function storedWidth(): number {
try {
const v = Number(localStorage.getItem(WIDTH_KEY));
return v >= MIN_WIDTH ? v : DEFAULT_WIDTH;
} catch {
return DEFAULT_WIDTH;
}
}
export function AiDock(): JSX.Element {
// Open whenever the app loads; the title-bar icon brings it back once closed.
const [open, setOpen] = useState(true);
const [width, setWidth] = useState(storedWidth);
useEffect(() => {
const root = document.documentElement;
root.classList.toggle('ze-ai-open', open);
root.style.setProperty('--ai-pane-width', `${width}px`);
try {
localStorage.setItem(WIDTH_KEY, String(width));
} catch {
// private window: the width is just not remembered
}
// Canvases size themselves from resize events.
window.dispatchEvent(new Event('resize'));
}, [open, width]);
// The frame's status bar spans the window under the pane, as the title bar
// does over it; its height is the frame's own (--statusbar-height differs
// per frame), so the pane's bottom follows the bar on screen.
useEffect(() => {
if (!open) return;
let last = -1;
const fit = () => {
const bar = [...document.querySelectorAll<HTMLElement>('#root .ze-statusbar')].find(
(e) => e.offsetParent !== null,
);
const h = bar ? bar.getBoundingClientRect().height : 0;
if (h !== last) {
last = h;
document.documentElement.style.setProperty('--ai-dock-bottom', `${h}px`);
}
};
fit();
const id = setInterval(fit, 500);
return () => clearInterval(id);
}, [open]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.ctrlKey && e.shiftKey && e.key.toLowerCase() === 'a') {
e.preventDefault();
setOpen((o) => !o);
}
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, []);
return createPortal(
<>
<DocViewer />
{open && (
<div className="ze-app ze-ai-dock">
<DockSash
edge="left"
width={width}
min={MIN_WIDTH}
max={Math.max(MIN_WIDTH, Math.round(window.innerWidth * 0.6))}
onResize={setWidth}
/>
<AiChatPane />
</div>
)}
{/* Always in the title bar: opens the pane, and closes it again. */}
<button
type="button"
className={`ze-ai-toggle${open ? ' on' : ''}`}
title={open ? 'Close the AI Assistant (Ctrl+Shift+A)' : 'AI Assistant (Ctrl+Shift+A)'}
aria-label={open ? 'Close the AI Assistant' : 'Open the AI Assistant'}
aria-pressed={open}
onClick={() => setOpen((o) => !o)}
>
<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">
<path
fill="currentColor"
d="M8 1l1.6 4.4L14 7l-4.4 1.6L8 13l-1.6-4.4L2 7l4.4-1.6zM13 11l.6 1.4L15 13l-1.4.6L13 15l-.6-1.4L11 13l1.4-.6z"
/>
</svg>
</button>
</>,
document.body,
);
}
+32
View File
@@ -0,0 +1,32 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Modified by VibeMake to make the AI assistant opt-in at build time.
/**
* The AI assistant is available only in builds that explicitly enable it. In
* those builds, add `?ai=1` to turn it on for the tab's session; `?ai=0` turns
* it off. Production VibeMake builds keep the feature disabled.
*
* The pane talks to a separately configured AI agent server at AI_AGENT_URL.
*/
const KEY = 'ziroeda.ai';
const BUILD_ENABLED =
(import.meta as { env?: Record<string, string | undefined> }).env?.VITE_ENABLE_AI === 'true';
/** Whether the AI assistant is enabled for this build and shown in this tab. */
export function aiEnabled(): boolean {
if (!BUILD_ENABLED || typeof window === 'undefined') return false;
const flag = new URLSearchParams(window.location.search).get('ai');
try {
if (flag === '1') window.sessionStorage.setItem(KEY, '1');
else if (flag === '0') window.sessionStorage.removeItem(KEY);
return window.sessionStorage.getItem(KEY) === '1';
} catch {
return flag === '1';
}
}
/** Where the agent server listens; VITE_AI_AGENT_URL overrides the local default. */
export const AI_AGENT_URL: string =
(import.meta as { env?: Record<string, string | undefined> }).env?.VITE_AI_AGENT_URL ??
'http://127.0.0.1:8787';
+263
View File
@@ -0,0 +1,263 @@
/**
* The AI's hands on the app itself, beside the editors: switching to (and
* opening) an editor, and creating a project from a template. Two bridges,
* because the two live in different places: editor switching in the shell
* (App), projects in the project manager.
*/
import { type AiBridge, aiBridge, type EditorKind, type ToolOutput } from './ai_bridge.js';
import { showDoc } from './doc_viewer.js';
/** The editors the model can open, by the name the tool takes. */
export const EDITORS = ['schematic', 'pcb', 'symbol_editor', 'footprint_editor'] as const;
export type EditorName = (typeof EDITORS)[number];
/** Which bridge an opened editor registers, for the ones the AI can drive. */
const DRIVEN: Partial<Record<EditorName, EditorKind>> = { schematic: 'sch', pcb: 'pcb' };
export interface Workspace {
/** The open project's name; null when none is open. */
project: string | null;
onScreen: string;
files: readonly string[];
/** DESIGN.md's text; null when the project has none yet. */
designDoc: string | null;
}
export interface AppScriptApi {
/** Show the editor, mounting its frame if it has never been opened. */
open(editor: EditorName): void;
/** What is on screen and which project is open, one line. */
describe(): string;
workspace?(): Workspace;
/** Write the project's DESIGN.md; throws when no project is open. */
writeDesignDoc?(text: string): void;
/** Show the project manager, which owns the project tools. */
goHome?(): void;
}
/** Tools the project manager owns; it is mounted only while on screen. */
const PROJECT_TOOLS = new Set(['new_project', 'list_templates']);
/** The design doc lives beside the project file, like Zener's spec.md. */
export function designDocName(proFile: string): string {
const slash = proFile.lastIndexOf('/');
return `${slash >= 0 ? proFile.slice(0, slash + 1) : ''}DESIGN.md`;
}
/** What the model is shown of the workspace at the start of a turn. */
export function describeWorkspace(w: Workspace): string {
if (!w.project)
return `No project is open (on screen: ${w.onScreen}). The schematic and PCB tools refuse until one is: create one with new_project, or ask the user to open theirs.`;
const lines = [
`project ${w.project} (on screen: ${w.onScreen})`,
`files: ${w.files.map((f) => f.replace(/^.*\//, '')).join(', ')}`,
];
lines.push(
w.designDoc === null
? 'DESIGN.md: none yet - write one (write_design_doc) before designing.'
: `DESIGN.md:\n${w.designDoc}`,
);
return lines.join('\n');
}
/** The tools that need no project: the app's own and the library lookups.
* Every other tool works on a schematic or board. */
const APP_TOOLS = new Set([
'design_guide',
'view_3d',
'open_editor',
'list_templates',
'new_project',
'read_design_doc',
'write_design_doc',
'search_symbols',
'search_footprints',
]);
/** Resolves once `kind`'s bridge is registered, or after `ms`. */
async function waitForBridge(kind: EditorKind, ms = 8000): Promise<boolean> {
const until = Date.now() + ms;
while (!aiBridge(kind)) {
if (Date.now() > until) return false;
await new Promise((r) => setTimeout(r, 100));
}
return true;
}
export function appBridge(api: AppScriptApi): AiBridge {
const tools: Record<string, (args: Record<string, unknown>) => Promise<ToolOutput>> = {
open_editor: async (args) => {
const editor = String(args.editor ?? '') as EditorName;
if (!EDITORS.includes(editor))
return {
text: `editor is one of ${EDITORS.join(', ')}`,
isError: true,
note: 'open editor: unknown editor',
};
api.open(editor);
const kind = DRIVEN[editor];
if (kind && !(await waitForBridge(kind)))
return {
text: `The ${editor} editor did not finish opening.`,
isError: true,
note: `${editor} did not open`,
};
return {
text: `${editor} is open. ${api.describe()}`,
note: `opened the ${editor.replace('_', ' ')}`,
};
},
// design_guide is answered by the agent server: it needs nothing from the open design.
read_design_doc: async () => {
const w = api.workspace?.();
if (!w?.project)
return { text: 'No project is open.', isError: true, note: 'no project open' };
return { text: w.designDoc ?? '(no DESIGN.md yet)', note: 'read the spec' };
},
write_design_doc: async (args) => {
const text = String(args.markdown ?? '');
if (!text.trim())
return { text: 'markdown is required', isError: true, note: 'design doc: empty' };
try {
api.writeDesignDoc?.(text);
} catch (e) {
return {
text: (e as Error).message,
isError: true,
note: `design doc: ${(e as Error).message}`,
};
}
// Open it for the user to read, beside the chat.
showDoc({ title: `DESIGN.md - ${api.workspace?.()?.project ?? ''}`, text });
return {
text: 'DESIGN.md saved and opened for the user to read.',
note: 'wrote the spec',
};
},
};
return {
kind: 'app',
read: () => {
const w = api.workspace?.();
return w ? describeWorkspace(w) : '';
},
project: () => api.workspace?.()?.project ?? null,
show: (kind) => {
const editor = kind === 'sch' ? 'schematic' : kind === 'pcb' ? 'pcb' : null;
if (editor && api.workspace?.()?.onScreen !== editor) api.open(editor);
},
guard: (name) => {
if (APP_TOOLS.has(name)) return null;
const w = api.workspace?.();
if (!w || w.project) return null;
return {
text: 'No project is open, so there is no schematic or board to work on. Create one with new_project, or ask the user to open theirs.',
isError: true,
note: `${name}: no project open`,
};
},
run: (name, args) => {
if (name === 'view_3d') {
// The 3D viewer is a child of the PCB editor: bring the board up,
// have it open the 3D frame, wait for that, and hand the call over.
return (async () => {
if (!aiBridge('3d')) {
api.open('pcb');
if (!(await waitForBridge('pcb')))
return {
text: 'The PCB editor did not open.',
isError: true,
note: 'view 3D: no PCB editor',
};
const opened = await aiBridge('pcb')?.run('open_3d', {});
if (opened?.isError) return opened;
if (!(await waitForBridge('3d', 20000)))
return {
text: 'The 3D viewer did not open.',
isError: true,
note: 'view 3D: viewer did not open',
};
}
return (
(await aiBridge('3d')?.run('view_3d', args)) ?? {
text: 'The 3D viewer cannot take a picture.',
isError: true,
note: 'view 3D: unavailable',
}
);
})();
}
if (PROJECT_TOOLS.has(name)) {
// The project manager is mounted only while on screen: bring it up,
// wait for it, and hand the call over.
return (async () => {
if (!aiBridge('project')) api.goHome?.();
if (!(await waitForBridge('project')))
return {
text: 'The project manager did not open.',
isError: true,
note: `${name}: project manager did not open`,
};
return (
(await aiBridge('project')?.run(name, args)) ?? {
text: `${name} is not available`,
isError: true,
note: `${name}: unavailable`,
}
);
})();
}
return tools[name]?.(args) ?? null;
},
};
}
export interface ProjectTemplateInfo {
id: string;
title: string;
description: string;
}
export interface ProjectScriptApi {
templates(): Promise<readonly ProjectTemplateInfo[]>;
/** File > New Project from `templateId` (the Default template when absent),
* named `name`; opens it. Returns the name it was created under. */
create(name: string, templateId?: string): Promise<string>;
}
export function projectBridge(api: ProjectScriptApi): AiBridge {
const tools: Record<string, (args: Record<string, unknown>) => Promise<ToolOutput>> = {
list_templates: async () => {
const list = await api.templates();
return {
text:
list
.map((t) => `${t.id}: ${t.title}${t.description ? ` - ${t.description}` : ''}`)
.join('\n') || 'no templates',
note: `listed ${list.length} project templates`,
};
},
new_project: async (args) => {
const name = String(args.name ?? '').trim();
if (!name)
return { text: 'a project name is required', isError: true, note: 'new project: no name' };
try {
const made = await api.create(
name,
args.template === undefined ? undefined : String(args.template),
);
return {
text: `Created project "${made}" and opened it in the schematic editor. Write its DESIGN.md next.`,
note: `created project ${made}`,
};
} catch (e) {
return {
text: (e as Error).message,
isError: true,
note: `new project failed: ${(e as Error).message}`,
};
}
},
};
return { kind: 'project', read: () => '', run: (name, args) => tools[name]?.(args) ?? null };
}
+595
View File
@@ -0,0 +1,595 @@
/* The AI pane, docked like a KiCad AUI pane (Properties, Appearance): a
.ze-panel with its 17px caption, a DockSash on its inner edge. Every value
is a shell token (chrome); the one literal is the pane width, which is
ours - KiCad has no such pane. Form controls take their look from the
shared `.ze-app` rules, which is why the dock root carries that class. */
:root {
--ai-pane-width: 380px; /* [ours] set from the dock's stored width */
}
html.ze-ai-open #root {
width: calc(100% - var(--ai-pane-width));
}
/* (0,2,0) on purpose: the dock IS a .ze-app root and its pane IS a
.ze-panel, and those shared rules (column flow, height 100%, a 220px pane)
must not win by stylesheet order. */
.ze-app.ze-ai-dock {
position: fixed;
/* Below the frame's title bar, which spans the window (see below). */
top: var(--titlebar-height);
right: 0;
bottom: var(--ai-dock-bottom, 0px);
width: var(--ai-pane-width);
display: flex;
flex-direction: row;
/* The sash sits between the editor and the pane, as the AUI sash does. */
background: var(--aui-sash);
height: auto;
z-index: 10;
}
.ze-panel.ze-ai-pane {
flex: 1 1 auto;
width: auto;
min-width: 0;
height: 100%;
}
.ze-ai-body {
display: flex;
flex-direction: column;
min-height: 0;
flex: 1 1 auto;
}
.ze-ai-cost {
flex: 1 1 auto;
color: var(--chrome-fg-muted);
font-size: var(--ui-font-size-small);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.ze-ai-list {
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
padding: 6px 8px;
display: flex;
flex-direction: column;
gap: 8px;
/* The conversation sits on the pane's own face; only the composer is an
entry. */
background: transparent;
}
.ze-ai-empty {
color: var(--chrome-fg-muted);
margin: auto 8px;
text-align: center;
}
.ze-ai-msg {
overflow-wrap: anywhere;
}
.ze-ai-user {
white-space: pre-wrap;
padding: 4px 8px;
border: 1px solid var(--ctl-border);
border-radius: var(--ctl-radius);
background: var(--ctl-face);
}
.ze-ai-note {
white-space: pre-wrap;
color: var(--chrome-fg-muted);
font-size: var(--ui-font-size-small);
}
/* The frame's title bar spans the whole window, over the pane too, the way
a WM title bar spans its window whatever the client area holds. */
html.ze-ai-open .ze-titlebar,
html.ze-ai-open #root .ze-statusbar {
margin-right: calc(-1 * var(--ai-pane-width));
}
/* The toggle, at the right end of the title bar while the pane is closed;
the bar keeps room for it so nothing in .ze-titlebar-right sits under it. */
.ze-titlebar {
padding-right: calc(var(--titlebar-height) + 8px);
}
.ze-ai-toggle.on {
color: var(--chrome-fg);
background: var(--chrome-hover);
}
.ze-ai-toggle {
position: fixed;
top: 0;
right: 4px;
width: var(--titlebar-height);
height: var(--titlebar-height);
display: flex;
align-items: center;
justify-content: center;
padding: 0;
border: 0;
background: transparent;
color: var(--chrome-fg);
cursor: pointer;
z-index: 10;
}
.ze-ai-toggle:hover {
background: var(--chrome-hover);
}
/* The sash between editor and pane carries a pane border on each side,
the token a right-docked AUI pane draws on its edge (.ze-leftdock.on-right),
so it reads as a resizer the way the manager's splitter does. */
.ze-ai-dock .ze-dock-sash {
border-left: var(--aui-pane-border-size) solid var(--aui-pane-border);
border-right: var(--aui-pane-border-size) solid var(--aui-pane-border);
}
/* ---- Markdown (markdown.tsx), with github-markdown-css's metrics ----
GitHub's `.markdown-body` sizes in px at a 16px base; here every one is
the same ratio in em, so the spec viewer (16px, as GitHub) matches it and
chat replies keep the proportions at the UI font size. Colours are the
shell's tokens. */
.ze-md {
line-height: 1.5;
overflow-wrap: break-word;
}
.ze-md > :first-child {
margin-top: 0 !important;
}
.ze-md > :last-child {
margin-bottom: 0 !important;
}
.ze-md p,
.ze-md blockquote,
.ze-md ul,
.ze-md ol,
.ze-md dl,
.ze-md table,
.ze-md pre,
.ze-md details {
margin-top: 0;
margin-bottom: 1em;
}
.ze-md h1,
.ze-md h2,
.ze-md h3,
.ze-md h4,
.ze-md h5,
.ze-md h6 {
margin-top: 1.5em;
margin-bottom: 1em;
font-weight: 600;
line-height: 1.25;
}
.ze-md h1 {
font-size: 2em;
padding-bottom: 0.3em;
border-bottom: 1px solid var(--ctl-border);
}
.ze-md h2 {
font-size: 1.5em;
padding-bottom: 0.3em;
border-bottom: 1px solid var(--ctl-border);
}
.ze-md h3 {
font-size: 1.25em;
}
.ze-md h4 {
font-size: 1em;
}
.ze-md h5 {
font-size: 0.875em;
}
.ze-md h6 {
font-size: 0.85em;
color: var(--chrome-fg-muted);
}
.ze-md strong {
font-weight: 600;
}
.ze-md ul,
.ze-md ol {
padding-left: 2em;
}
.ze-md ul ul,
.ze-md ul ol,
.ze-md ol ol,
.ze-md ol ul {
margin-top: 0;
margin-bottom: 0;
}
.ze-md li + li {
margin-top: 0.25em;
}
.ze-md li > p {
margin-top: 1em;
}
.ze-md code {
padding: 0.2em 0.4em;
margin: 0;
font-family: monospace;
font-size: 85%;
white-space: break-spaces;
border-radius: var(--ctl-radius);
background: var(--chrome-bg2);
}
.ze-md pre {
padding: 1em;
overflow: auto;
font-size: 85%;
line-height: 1.45;
border-radius: var(--ctl-radius);
background: var(--chrome-bg2);
}
.ze-md pre code {
padding: 0;
font-size: 100%;
white-space: pre;
background: transparent;
}
.ze-md blockquote {
padding: 0 1em;
color: var(--chrome-fg-muted);
border-left: 0.25em solid var(--ctl-border);
}
.ze-md hr {
height: 0.25em;
padding: 0;
margin: 1.5em 0;
border: 0;
background: var(--ctl-border);
}
.ze-md table {
display: block;
width: max-content;
max-width: 100%;
overflow: auto;
border-spacing: 0;
border-collapse: collapse;
}
.ze-md th,
.ze-md td {
padding: 0.375em 0.8125em;
border: 1px solid var(--ctl-border);
}
.ze-md th {
font-weight: 600;
}
.ze-md tr {
background: var(--content-bg);
border-top: 1px solid var(--ctl-border);
}
.ze-md tr:nth-child(2n) {
background: var(--chrome-bg2);
}
.ze-md a {
color: var(--link-fg);
text-decoration: none;
}
.ze-md a:hover {
text-decoration: underline;
}
.ze-md del {
color: var(--chrome-fg-muted);
}
.ze-md li.task-list-item {
list-style: none;
}
.ze-md li.task-list-item input {
margin: 0 0.2em 0.25em -1.4em;
vertical-align: middle;
}
/* The spec reads at GitHub's size and measure. */
.ze-md-doc {
max-width: 980px; /* [ours] GitHub's readme column, 1012px less padding */
margin: 0 auto;
font-size: 16px; /* [data] github-markdown-css .markdown-body */
}
/* ---- Tool steps: live while working, folded to one line after ---- */
.ze-ai-steps {
display: flex;
flex-direction: column;
gap: 3px;
color: var(--chrome-fg-muted);
font-size: var(--ui-font-size-small);
}
.ze-ai-steps-head {
display: flex;
align-items: center;
gap: 5px;
align-self: flex-start;
padding: 0;
border: 0;
background: none;
color: inherit;
font: inherit;
cursor: pointer;
}
.ze-ai-steps-head:hover {
color: var(--chrome-fg);
}
.ze-ai-step {
display: flex;
align-items: flex-start;
gap: 6px;
padding-left: 2px;
}
.ze-ai-step > span:last-child {
overflow-wrap: anywhere;
}
.ze-ai-step.running {
color: var(--chrome-fg);
}
.ze-ai-step.error {
color: var(--error-ink);
}
.ze-ai-step-icon,
.ze-ai-spinner {
flex: 0 0 auto;
margin-top: 2px;
}
.ze-ai-spinner {
width: 10px;
height: 10px;
margin-left: 1px;
margin-right: 1px;
border: 1.5px solid var(--ctl-border);
border-top-color: var(--chrome-fg);
border-radius: 50%;
animation: ze-ai-spin 0.8s linear infinite;
}
@keyframes ze-ai-spin {
to {
transform: rotate(360deg);
}
}
/* Thinking: shown only while the model thinks, a soft pulse. */
.ze-ai-thinking {
color: var(--chrome-fg-muted);
font-size: var(--ui-font-size-small);
animation: ze-ai-pulse 1.6s ease-in-out infinite;
}
@keyframes ze-ai-pulse {
50% {
opacity: 0.45;
}
}
/* ---- The spec viewer (doc_viewer.tsx): a KiCad dialog over the free area ---- */
.ze-ai-docview-scrim {
position: fixed;
top: 0;
left: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5); /* the shell's .ze-modal-backdrop */
z-index: 19;
}
/* .ze-app is height: 100%; this root is exactly the box it is given, and
clips, so a long spec scrolls inside rather than growing the dialog. */
.ze-app.ze-ai-docview {
position: fixed;
height: auto;
z-index: 20;
display: flex;
overflow: hidden;
}
/* (0,2,0): .ze-modal sizes to its content; this one is the box it is given. */
.ze-modal.ze-ai-docview-dialog {
flex: 1 1 auto;
min-width: 0;
min-height: 0;
width: auto;
height: auto;
max-width: none;
max-height: none;
}
.ze-ai-docview-body {
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
padding: 32px; /* [data] github-markdown-css .markdown-body padding */
/* The central area's own face (the launcher pane's), not an entry's. */
background: var(--content-bg);
}
/* ---- The pane's head: a strip the menu bar's height, no caption ---- */
.ze-ai-head {
display: flex;
align-items: center;
gap: 6px;
height: var(--menu-row);
padding: 0 6px;
background: var(--chrome-bg);
border-bottom: 1px solid var(--chrome-border);
flex: 0 0 auto;
}
.ze-ai-head-fill {
flex: 1 1 auto;
}
.ze-ai-iconbtn,
.ze-ai-textbtn,
.ze-ai-roundbtn {
display: flex;
align-items: center;
justify-content: center;
padding: 0;
border: 0;
background: transparent;
color: var(--chrome-fg);
font: inherit;
cursor: pointer;
}
.ze-ai-iconbtn {
width: calc(var(--menu-row) - 4px);
height: calc(var(--menu-row) - 4px);
border-radius: var(--ctl-radius);
}
.ze-ai-textbtn {
height: calc(var(--menu-row) - 4px);
padding: 0 8px;
border-radius: var(--ctl-radius);
}
.ze-ai-iconbtn:hover,
.ze-ai-textbtn:hover {
background: var(--chrome-hover);
}
.ze-ai-head .ze-ai-cost {
flex: 0 0 auto;
color: var(--chrome-fg-muted);
}
.ze-ai-menu-anchor {
position: relative;
}
/* The chats menu is the app's popup (.ze-dropdown), as a plain column. */
.ze-dropdown.ze-ai-menu {
display: flex;
flex-direction: column;
min-width: 240px;
max-width: 320px;
max-height: 60vh;
overflow-y: auto;
}
.ze-ai-menu-item {
padding: 4px 12px;
border: 0;
background: none;
color: var(--chrome-fg);
font: inherit;
text-align: left;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
cursor: default;
}
.ze-ai-menu-item:hover:not(:disabled) {
background: var(--chrome-hover);
}
.ze-ai-menu-item.current {
font-weight: bold;
}
.ze-ai-menu-sep {
margin: 4px 0;
border-top: 1px solid var(--chrome-border);
}
/* ---- The composer: one rounded box holding the text and its buttons ---- */
.ze-ai-composer {
display: flex;
flex-direction: column;
gap: 4px;
margin: 8px;
padding: 6px 8px;
border: 1px solid var(--ctl-border);
border-radius: calc(2 * var(--window-radius));
/* A button's face, a step lighter than the pane, so the box reads as
the place to type. */
background: var(--ctl-face);
}
.ze-ai-composer:focus-within {
border-color: var(--chrome-fg-muted);
}
/* (0,2,1): the shell's entry rule (.ze-app textarea) frames every text
box; inside the composer the box itself is the frame. */
.ze-app .ze-ai-composer textarea {
min-height: 40px;
max-height: 200px;
resize: none;
padding: 2px;
border: 0;
outline: none;
background: transparent;
color: var(--chrome-fg);
font: inherit;
box-shadow: none;
}
.ze-ai-composer-row {
display: flex;
align-items: center;
gap: 6px;
}
.ze-ai-roundbtn {
width: 28px; /* [ours] KiCad has no such control */
height: 28px;
border-radius: 50%;
border: 1px solid var(--ctl-border);
color: var(--chrome-fg-muted);
}
.ze-ai-roundbtn:hover:not(:disabled) {
background: var(--chrome-hover);
color: var(--chrome-fg);
}
.ze-ai-roundbtn.live {
color: var(--error-ink);
border-color: var(--error-ink);
}
.ze-ai-roundbtn.send {
border-color: transparent;
background: var(--chrome-fg);
color: var(--ctl-face);
}
.ze-ai-pillbtn {
display: flex;
align-items: center;
gap: 5px;
height: 28px;
padding: 0 10px;
border: 1px solid var(--ctl-border);
border-radius: 14px;
background: transparent;
color: var(--chrome-fg-muted);
font: inherit;
cursor: pointer;
}
.ze-ai-pillbtn:hover {
background: var(--chrome-hover);
color: var(--chrome-fg);
}
.ze-ai-roundbtn.send:disabled {
opacity: 0.35;
cursor: default;
}
.ze-ai-thumbs {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.ze-ai-thumbs img {
max-width: 96px;
max-height: 72px;
border-radius: var(--ctl-radius);
object-fit: cover;
}
.ze-ai-thumb {
position: relative;
}
.ze-ai-thumb button {
position: absolute;
top: -6px;
right: -6px;
width: 18px;
height: 18px;
padding: 0;
border: 0;
border-radius: 50%;
background: var(--chrome-bg);
color: var(--chrome-fg);
line-height: 18px;
cursor: pointer;
}
/* …and its focus ring: the composer's own border answers focus instead. */
.ze-app .ze-ai-composer textarea:focus {
border: 0;
outline: none;
box-shadow: none;
}
/* The agent link line: how to connect, or what is connected (ai/agent_link.tsx). Ours, not a
KiCad control: it takes the chrome tokens like the rest of the pane. */
.ze-ai-agent {
flex: 0 0 auto;
padding: 4px 6px;
font-size: var(--ui-font-size-small);
color: var(--chrome-fg-muted);
background: var(--chrome-bg2);
border-bottom: 1px solid var(--chrome-border);
}
.ze-ai-agent code {
color: var(--chrome-fg);
}
+742
View File
@@ -0,0 +1,742 @@
/**
* The app-wide AI chat pane, docked on the right of every editor.
*
* It talks to whatever editor registered a bridge (ai_bridge.ts). Each turn
* sends the compact view of the open document only when it changed since the
* model last saw it. The model works through tools (read_schematic,
* apply_zsch, run_erc) and runs its own loop until it is done; this pane only
* executes each call against the bridge, so every edit is one undoable
* commit in that editor.
*/
import { useEffect, useRef, useState } from 'react';
import { aiBridge, allBridges, type EditorKind, runAiTool, type ToolOutput } from './ai_bridge.js';
import { AgentStatus, useAgentLink } from './agent_link.js';
import { hideDoc, showDoc } from './doc_viewer.js';
import { Markdown } from './markdown.js';
import { AI_AGENT_URL } from './ai_flag.js';
import type { ChatEvent, ToolResult } from './protocol.js';
import './chat_pane.css';
/** One tool call as the chat shows it: running, then what it did. */
export interface Step {
label: string;
state: 'running' | 'done' | 'error';
}
/**
* The conversation. A run of tool calls is one `steps` entry: open while
* the model works, folded to a one-line summary once text follows it or the
* turn ends; the user can unfold it.
*/
type Msg =
| { role: 'user' | 'ai' | 'note'; text: string; images?: string[] }
| { role: 'steps'; steps: Step[]; open: boolean };
/** What a tool is doing, before its own note says what it did. */
export function runningLabel(tool: string): string {
const words = tool.replace(/_/g, ' ');
if (tool.startsWith('read_')) return `Reading the ${words.slice(5)}`;
if (tool.startsWith('view_')) return `Looking at the ${words.slice(5)}`;
if (tool.startsWith('search_')) return `Searching ${words.slice(7)}`;
if (tool.startsWith('run_')) return `Running ${words.slice(4).toUpperCase()}`;
return `${words.charAt(0).toUpperCase()}${words.slice(1)}`;
}
/** A folded run of steps, in one line. */
export function stepsSummary(steps: readonly Step[]): string {
const failed = steps.filter((s) => s.state === 'error').length;
return `${steps.length} step${steps.length === 1 ? '' : 's'}${failed ? ` · ${failed} failed` : ''}`;
}
/** Fold every steps entry (the turn ended, or text came after them). */
const fold = (m: Msg[]): Msg[] =>
m.map((x) => (x.role === 'steps' && x.open ? { ...x, open: false } : x));
export interface Totals {
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
costUsd: number;
turns: number;
}
/** A tool that has not answered by then is reported to the model as failed,
* so one stuck call cannot hang the whole turn. */
const TOOL_TIMEOUT_MS = 120_000;
const ZERO: Totals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, costUsd: 0, turns: 0 };
export function addUsage(a: Totals, b: Totals): Totals {
return {
input: a.input + b.input,
output: a.output + b.output,
cacheRead: a.cacheRead + b.cacheRead,
cacheWrite: a.cacheWrite + b.cacheWrite,
costUsd: a.costUsd + b.costUsd,
turns: a.turns + b.turns,
};
}
function subUsage(a: Totals, b: Totals): Totals {
return addUsage(a, {
input: -b.input,
output: -b.output,
cacheRead: -b.cacheRead,
cacheWrite: -b.cacheWrite,
costUsd: -b.costUsd,
turns: -b.turns,
});
}
const fmtK = (n: number) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n));
export function AiChatPane(): JSX.Element {
const [msgs, setMsgs] = useState<Msg[]>([]);
const [draft, setDraft] = useState('');
const [busy, setBusy] = useState(false);
const [totals, setTotals] = useState<Totals>(ZERO);
const [last, setLast] = useState<Totals | null>(null);
/** What the model is doing right now, and since when. */
const [status, setStatus] = useState<{ text: string; since: number } | null>(null);
const [, setTick] = useState(0);
/** Pictures attached to the next message. */
const [attached, setAttached] = useState<Attachment[]>([]);
const [listening, setListening] = useState(false);
const [menuOpen, setMenuOpen] = useState(false);
/** This project's saved chats, and which one is on screen. */
const [project, setProject] = useState<string | null>(() => currentProject());
const [chats, setChats] = useState<SavedChat[]>(() => loadChats(currentProject()));
const [chatId, setChatId] = useState(() => newId());
const recognizer = useRef<SpeechRecognitionLike | null>(null);
const fileRef = useRef<HTMLInputElement>(null);
const session = useRef<string | undefined>(undefined);
const lastSeen = useRef(new Map<EditorKind, string>());
const agent = useAgentLink();
const abort = useRef<AbortController | null>(null);
const listRef = useRef<HTMLDivElement>(null);
// A running clock on the status line, so a long think never looks dead.
useEffect(() => {
if (!status) return;
const id = setInterval(() => setTick((t) => t + 1), 1000);
return () => clearInterval(id);
}, [status]);
// biome-ignore lint/correctness/useExhaustiveDependencies: scroll on every new message
useEffect(() => {
listRef.current?.scrollTo(0, listRef.current.scrollHeight);
}, [msgs]);
const newChat = () => {
session.current = undefined;
lastSeen.current.clear();
setMsgs([]);
setTotals(ZERO);
setLast(null);
setChatId(newId());
setMenuOpen(false);
};
/** Reopen a saved chat of this project; the CLI session resumes with it. */
const openChat = (c: SavedChat) => {
session.current = c.sessionId;
lastSeen.current.clear();
setMsgs(c.msgs);
setTotals(c.totals);
setLast(null);
setChatId(c.id);
setMenuOpen(false);
};
// The chat on screen is saved under the open project as it changes.
useEffect(() => {
if (msgs.length === 0) return;
const firstUser = msgs.find(
(m): m is Extract<Msg, { role: 'user' | 'ai' | 'note' }> => m.role === 'user',
);
const saved: SavedChat = {
id: chatId,
sessionId: session.current,
title: (firstUser?.text ?? 'Chat').slice(0, 60),
updated: Date.now(),
// Pictures are not kept: a saved chat says how many there were.
msgs: msgs.map((m) => (m.role !== 'steps' && m.images ? { ...m, images: undefined } : m)),
totals,
};
setChats((list) => {
const next = [saved, ...list.filter((c) => c.id !== chatId)].slice(0, MAX_CHATS);
storeChats(project, next);
return next;
});
}, [msgs, totals, chatId, project]);
// Another project opened: its own chats, starting from a fresh one.
useEffect(() => {
const id = setInterval(() => {
const p = currentProject();
if (p === project) return;
setProject(p);
// The spec on screen was the old project's.
hideDoc();
setChats(loadChats(p));
if (!busy) {
session.current = undefined;
lastSeen.current.clear();
setMsgs([]);
setTotals(ZERO);
setChatId(newId());
}
}, 1000);
return () => clearInterval(id);
}, [project, busy]);
const attach = async (files: FileList | File[]) => {
const pics = [...files].filter((f) => f.type.startsWith('image/'));
const read = await Promise.all(
pics.map(
(f) =>
new Promise<Attachment>((resolve) => {
const r = new FileReader();
r.onload = () => {
const url = String(r.result);
resolve({ url, mediaType: f.type, data: url.replace(/^data:[^,]*,/, '') });
};
r.readAsDataURL(f);
}),
),
);
setAttached((a) => [...a, ...read]);
};
/** Voice input: the browser's speech recognition, dictating into the box. */
const toggleVoice = () => {
if (listening) {
recognizer.current?.stop();
return;
}
const Ctor = speechRecognition();
if (!Ctor) return;
const rec = new Ctor();
rec.continuous = true;
rec.interimResults = false;
rec.onresult = (e) => {
let said = '';
for (let i = e.resultIndex; i < e.results.length; i++)
said += e.results[i]?.[0]?.transcript ?? '';
if (said.trim())
setDraft((d) => (d ? `${d.replace(/\s*$/, '')} ${said.trim()}` : said.trim()));
};
rec.onend = () => {
setListening(false);
recognizer.current = null;
};
recognizer.current = rec;
setListening(true);
rec.start();
};
/** Run one tool call from the model on whichever editor owns that tool. */
const runTool = async (name: string, args: Record<string, unknown>): Promise<ToolOutput> => {
const { out, kind } = await runAiTool(name, args);
// What the model just read is what it has seen.
if (kind && name.startsWith('read_')) lastSeen.current.set(kind, out.text);
return out;
};
const send = async (override?: string) => {
const text = (override ?? draft).trim();
const pics = attached;
if ((!text && pics.length === 0) || busy) return;
if (override === undefined) setDraft('');
setAttached([]);
setBusy(true);
// Each open editor's view, when it changed since the model last saw it.
const views: string[] = [];
for (const b of allBridges()) {
const view = b.read();
if (!view || view === lastSeen.current.get(b.kind)) continue;
lastSeen.current.set(b.kind, view);
const tag = b.kind === 'sch' ? 'schematic' : b.kind === 'app' ? 'workspace' : 'board';
views.push(`<${tag}>\n${view}\n</${tag}>`);
}
const message = views.length ? `${views.join('\n\n')}\n\n${text}` : text;
setMsgs((m) => [
...m,
{ role: 'user', text, ...(pics.length ? { images: pics.map((p) => p.url) } : {}) },
]);
// Assistant text arrives between tool calls; each run of it is one bubble.
let bubble = false;
const say = (t: string) => {
const open = bubble;
bubble = true;
setMsgs((m) => {
const lastMsg = m[m.length - 1];
return open && lastMsg?.role === 'ai'
? [...m.slice(0, -1), { role: 'ai', text: lastMsg.text + t }]
: [...fold(m), { role: 'ai', text: t }];
});
};
const note = (t: string) => {
bubble = false;
setMsgs((m) => [...m, { role: 'note', text: t }]);
};
/** A step joins the run at the end of the chat, or starts one. */
const stepStart = (label: string) => {
bubble = false;
setMsgs((m) => {
const lastMsg = m[m.length - 1];
const step: Step = { label, state: 'running' };
return lastMsg?.role === 'steps'
? [...m.slice(0, -1), { ...lastMsg, open: true, steps: [...lastMsg.steps, step] }]
: [...m, { role: 'steps', open: true, steps: [step] }];
});
};
const stepEnd = (label: string, failed: boolean) =>
setMsgs((m) => {
const lastMsg = m[m.length - 1];
if (lastMsg?.role !== 'steps') return m;
const steps = lastMsg.steps.map((x, i) =>
i === lastMsg.steps.length - 1
? ({ label, state: failed ? 'error' : 'done' } as Step)
: x,
);
return [...m.slice(0, -1), { ...lastMsg, steps }];
});
const ctl = new AbortController();
abort.current = ctl;
let turnLive: Totals = ZERO;
try {
const res = await fetch(`${AI_AGENT_URL}/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
sessionId: session.current,
message: message || 'See the picture.',
...(pics.length
? { images: pics.map((p) => ({ mediaType: p.mediaType, data: p.data })) }
: {}),
}),
signal: ctl.signal,
});
if (!res.body) throw new Error(`HTTP ${res.status}`);
const reader = res.body.getReader();
const dec = new TextDecoder();
let buf = '';
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buf += dec.decode(value, { stream: true });
for (let nl = buf.indexOf('\n'); nl >= 0; nl = buf.indexOf('\n')) {
const e = JSON.parse(buf.slice(0, nl)) as ChatEvent;
buf = buf.slice(nl + 1);
if (e.type === 'text') {
setStatus(null);
say(e.text);
} else if (e.type === 'status')
setStatus(e.text ? { text: e.text, since: Date.now() } : null);
else if (e.type === 'session') {
session.current = e.sessionId;
} else if (e.type === 'tool') {
setStatus(null);
stepStart(runningLabel(e.name));
const answer = await Promise.race([
runTool(e.name, e.args).catch(
(err: unknown): ToolOutput => ({
text: `${e.name} failed: ${String(err)}`,
isError: true,
note: `${e.name} failed: ${String(err)}`,
}),
),
new Promise<ToolOutput>((res) =>
setTimeout(
() =>
res({
text: `${e.name} did not answer within ${TOOL_TIMEOUT_MS / 1000} s`,
isError: true,
note: `${e.name} timed out after ${TOOL_TIMEOUT_MS / 1000} s`,
}),
TOOL_TIMEOUT_MS,
),
),
]);
stepEnd(answer.note.charAt(0).toUpperCase() + answer.note.slice(1), !!answer.isError);
setStatus({ text: 'thinking', since: Date.now() });
const result: ToolResult = {
id: e.id,
text: answer.text,
isError: answer.isError,
...(answer.imagePng ? { imagePng: answer.imagePng } : {}),
};
await fetch(`${AI_AGENT_URL}/tool-result`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(result),
});
} else if (e.type === 'usage-live') {
// Counted as each call ends, so a long or stopped turn still shows.
turnLive = addUsage(turnLive, { ...e, costUsd: 0, turns: 0 });
setTotals((t) => addUsage(t, { ...e, costUsd: 0, turns: 0 }));
setLast(turnLive);
} else if (e.type === 'usage') {
// The CLI's own account of the turn (with its price) replaces the
// running count for it.
const final = { ...e, turns: 1 };
const live = turnLive;
setTotals((t) => addUsage(subUsage(t, live), final));
setLast(final);
turnLive = ZERO;
} else if (e.type === 'error') note(`Error: ${e.message}`);
}
}
} catch (err) {
note(ctl.signal.aborted ? 'Stopped.' : `Error: ${String(err)}`);
}
abort.current = null;
setStatus(null);
setMsgs(fold);
setBusy(false);
};
const toggleSteps = (index: number) =>
setMsgs((m) =>
m.map((x, i) => (i === index && x.role === 'steps' ? { ...x, open: !x.open } : x)),
);
const openSpec = async () => {
const out = await aiBridge('app')?.run('read_design_doc', {});
if (out && !out.isError)
showDoc({ title: `DESIGN.md - ${currentProject() ?? ''}`, text: out.text });
else {
hideDoc();
setMsgs((m) => [
...m,
{ role: 'note', text: 'No project is open, so there is no spec to show.' },
]);
}
};
const tokenTitle = [
`This chat: ${fmtK(totals.input + totals.cacheRead + totals.cacheWrite)} in, ${fmtK(totals.output)} out`,
`Last turn: ${fmtK((last?.input ?? 0) + (last?.cacheRead ?? 0) + (last?.cacheWrite ?? 0))} in, ${fmtK(last?.output ?? 0)} out`,
].join('\n');
return (
<div className="ze-panel ze-ai-pane" data-testid="ai-pane">
<AgentStatus agent={agent} />
<div className="ze-ai-head">
<div className="ze-ai-menu-anchor">
<button
type="button"
className="ze-ai-iconbtn"
title="Chats in this project"
aria-label="Chats in this project"
onClick={() => setMenuOpen((o) => !o)}
>
<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true">
<path
d="M2.5 4h11M2.5 8h11M2.5 12h11"
stroke="currentColor"
strokeWidth="1.4"
fill="none"
/>
</svg>
</button>
{menuOpen && (
<div className="ze-dropdown ze-ai-menu" role="menu">
<button type="button" className="ze-ai-menu-item" onClick={newChat} disabled={busy}>
New chat
</button>
{chats.length > 0 && <div className="ze-ai-menu-sep" />}
{chats.map((c) => (
<button
key={c.id}
type="button"
className={`ze-ai-menu-item${c.id === chatId ? ' current' : ''}`}
disabled={busy}
onClick={() => openChat(c)}
title={new Date(c.updated).toLocaleString()}
>
{c.title}
</button>
))}
</div>
)}
</div>
<span className="ze-ai-head-fill" />
<span className="ze-ai-cost" title={tokenTitle}>
${totals.costUsd.toFixed(2)}
</span>
</div>
<div className="ze-panel-body ze-ai-body">
<div className="ze-ai-list" ref={listRef}>
{msgs.length === 0 && (
<div className="ze-ai-empty">
Describe a circuit or a change. The assistant edits the open schematic and board,
checks its work with ERC and DRC, and every edit is one undo.
</div>
)}
{msgs.map((m, i) =>
m.role === 'steps' ? (
// biome-ignore lint/suspicious/noArrayIndexKey: messages are append-only
<div key={i} className="ze-ai-msg ze-ai-steps">
<button type="button" className="ze-ai-steps-head" onClick={() => toggleSteps(i)}>
<Chevron open={m.open} /> {stepsSummary(m.steps)}
</button>
{m.open &&
m.steps.map((x, j) => (
// biome-ignore lint/suspicious/noArrayIndexKey: steps are append-only
<div key={j} className={`ze-ai-step ${x.state}`}>
<StepIcon state={x.state} />
<span>{x.label}</span>
</div>
))}
</div>
) : (
// biome-ignore lint/suspicious/noArrayIndexKey: messages are append-only
<div key={i} className={`ze-ai-msg ze-ai-${m.role}`}>
{m.role === 'user' && m.images?.length ? (
<div className="ze-ai-thumbs">
{m.images.map((url, j) => (
// biome-ignore lint/suspicious/noArrayIndexKey: attachments never reorder
<img key={j} src={url} alt="attached" />
))}
</div>
) : null}
{m.role === 'ai' ? <Markdown text={m.text} /> : m.text}
</div>
),
)}
{busy && status && (
<div className="ze-ai-thinking">
{status.text.startsWith('writing ')
? `Preparing ${runningLabel(status.text.slice(8)).toLowerCase()}`
: 'Thinking'}
… {Math.round((Date.now() - status.since) / 1000)} s
</div>
)}
</div>
<div className="ze-ai-composer">
{attached.length > 0 && (
<div className="ze-ai-thumbs">
{attached.map((a, j) => (
// biome-ignore lint/suspicious/noArrayIndexKey: attachments never reorder
<span key={j} className="ze-ai-thumb">
<img src={a.url} alt="attachment" />
<button
type="button"
title="Remove"
onClick={() => setAttached((list) => list.filter((_, k) => k !== j))}
>
×
</button>
</span>
))}
</div>
)}
<textarea
value={draft}
placeholder="Ask, or describe a circuit to draw…"
rows={2}
onChange={(e) => setDraft(e.target.value)}
onPaste={(e) => {
const files = [...e.clipboardData.files];
if (files.some((f) => f.type.startsWith('image/'))) void attach(files);
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
void send();
}
}}
/>
<div className="ze-ai-composer-row">
<button
type="button"
className="ze-ai-roundbtn"
title="Attach images"
onClick={() => fileRef.current?.click()}
>
<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true">
<path d="M8 3v10M3 8h10" stroke="currentColor" strokeWidth="1.5" fill="none" />
</svg>
</button>
<input
ref={fileRef}
type="file"
accept="image/*"
multiple
hidden
onChange={(e) => {
if (e.target.files) void attach(e.target.files);
e.target.value = '';
}}
/>
<button
type="button"
className="ze-ai-pillbtn"
title="Open the project's spec (DESIGN.md)"
onClick={() => void openSpec()}
>
<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">
<path
d="M4 1.5h5.5L12.5 4.5V14.5H4zM9.5 1.5v3h3M6 8h4.5M6 10.5h4.5"
stroke="currentColor"
strokeWidth="1.2"
fill="none"
/>
</svg>
Spec
</button>
<span className="ze-ai-head-fill" />
{speechRecognition() && (
<button
type="button"
className={`ze-ai-roundbtn${listening ? ' live' : ''}`}
title={listening ? 'Stop dictation' : 'Dictate'}
onClick={toggleVoice}
>
<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true">
<rect
x="6"
y="2"
width="4"
height="8"
rx="2"
fill="none"
stroke="currentColor"
strokeWidth="1.4"
/>
<path
d="M3.5 8a4.5 4.5 0 0 0 9 0M8 12.5V14.5"
stroke="currentColor"
strokeWidth="1.4"
fill="none"
/>
</svg>
</button>
)}
{busy ? (
<button
type="button"
className="ze-ai-roundbtn send"
title="Stop"
onClick={() => abort.current?.abort()}
>
<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true">
<rect x="4.5" y="4.5" width="7" height="7" rx="1" fill="currentColor" />
</svg>
</button>
) : (
<button
type="button"
className="ze-ai-roundbtn send"
title="Send"
disabled={!draft.trim() && attached.length === 0}
onClick={() => void send()}
>
<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true">
<path
d="M8 13V3.5M3.5 8 8 3.5 12.5 8"
stroke="currentColor"
strokeWidth="1.6"
fill="none"
/>
</svg>
</button>
)}
</div>
</div>
</div>
</div>
);
}
/** The step's state: a spinner while it runs, a tick or a cross after. */
function StepIcon({ state }: { state: Step['state'] }): JSX.Element {
if (state === 'running') return <span className="ze-ai-spinner" aria-label="running" />;
return (
<svg className="ze-ai-step-icon" viewBox="0 0 12 12" width="12" height="12" aria-hidden="true">
{state === 'done' ? (
<path d="M2.5 6.2l2.3 2.3 4.7-5" fill="none" stroke="currentColor" strokeWidth="1.4" />
) : (
<path d="M3 3l6 6M9 3l-6 6" fill="none" stroke="currentColor" strokeWidth="1.4" />
)}
</svg>
);
}
function Chevron({ open }: { open: boolean }): JSX.Element {
return (
<svg className="ze-ai-chevron" viewBox="0 0 10 10" width="10" height="10" aria-hidden="true">
<path
d={open ? 'M2 3.5l3 3 3-3' : 'M3.5 2l3 3-3 3'}
fill="none"
stroke="currentColor"
strokeWidth="1.3"
/>
</svg>
);
}
interface Attachment {
url: string;
mediaType: string;
data: string;
}
/** A chat kept under its project, to reopen from the menu. */
export interface SavedChat {
id: string;
sessionId?: string;
title: string;
updated: number;
msgs: Msg[];
totals: Totals;
}
/** [ours] how many chats a project keeps. */
const MAX_CHATS = 30;
const chatsKey = (project: string | null) => `ziroeda.ai.chats.${project ?? '(no project)'}`;
const newId = () => `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
/** The open project, as the app bridge reports it. */
function currentProject(): string | null {
return aiBridge('app')?.project?.() ?? null;
}
export function loadChats(project: string | null): SavedChat[] {
try {
const raw = localStorage.getItem(chatsKey(project));
return raw ? (JSON.parse(raw) as SavedChat[]) : [];
} catch {
return [];
}
}
export function storeChats(project: string | null, chats: readonly SavedChat[]): void {
try {
localStorage.setItem(chatsKey(project), JSON.stringify(chats));
} catch {
// private window or full storage: the chat is just not kept
}
}
interface SpeechRecognitionLike {
continuous: boolean;
interimResults: boolean;
onresult:
| ((e: { resultIndex: number; results: ArrayLike<ArrayLike<{ transcript: string }>> }) => void)
| null;
onend: (() => void) | null;
start(): void;
stop(): void;
}
/** The browser's speech recognition, where it has one (Chrome, Edge, Safari). */
function speechRecognition(): (new () => SpeechRecognitionLike) | null {
const w = window as unknown as {
SpeechRecognition?: new () => SpeechRecognitionLike;
webkitSpeechRecognition?: new () => SpeechRecognitionLike;
};
return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null;
}
+111
View File
@@ -0,0 +1,111 @@
/**
* The project's spec, shown for reading in a KiCad dialog centred on the
* space between the file explorer (the manager's left dock) and the AI
* pane, so the tree and the chat stay usable beside it.
* It opens when the assistant writes DESIGN.md and from the pane's Spec
* button; it is not modal - the user answers in the chat.
*/
import { useEffect, useState, useSyncExternalStore } from 'react';
import { Markdown } from './markdown.js';
interface ShownDoc {
title: string;
text: string;
}
let shown: ShownDoc | null = null;
const listeners = new Set<() => void>();
const changed = () => {
for (const l of listeners) l();
};
export function showDoc(doc: ShownDoc): void {
shown = doc;
changed();
}
export function hideDoc(): void {
shown = null;
changed();
}
export function shownDoc(): ShownDoc | null {
return shown;
}
function subscribe(l: () => void): () => void {
listeners.add(l);
return () => listeners.delete(l);
}
/** The free area between the left dock and the AI pane, below the frame chrome. */
function freeArea(): { left: number; top: number; right: number; bottom: number } {
const dock = document.querySelector('.ze-leftdock')?.getBoundingClientRect();
const ai = document.querySelector('.ze-ai-dock')?.getBoundingClientRect();
const chrome = document.querySelector('.ze-framechrome')?.getBoundingClientRect();
const left = dock && dock.width > 0 ? dock.right : 0;
const right = ai && ai.width > 0 ? ai.left : window.innerWidth;
const top = chrome && chrome.height > 0 ? chrome.bottom : 0;
return { left, top, right, bottom: window.innerHeight };
}
/** [ours] the share of the free area's width and height the viewer takes. */
const SHARE = 0.8;
export function DocViewer(): JSX.Element | null {
const doc = useSyncExternalStore(subscribe, shownDoc);
const [, relayout] = useState(0);
useEffect(() => {
if (!doc) return;
const onResize = () => relayout((n) => n + 1);
window.addEventListener('resize', onResize);
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') hideDoc();
};
window.addEventListener('keydown', onKey);
return () => {
window.removeEventListener('resize', onResize);
window.removeEventListener('keydown', onKey);
};
}, [doc]);
if (!doc) return null;
const a = freeArea();
const w = (a.right - a.left) * SHARE;
const h = (a.bottom - a.top) * SHARE;
// A KiCad dialog (.ze-modal: the CSD title bar, the window radius and
// shadow), centred on the free area. Not modal: the user answers in chat.
return (
<>
{/* Everything but the chat dims, as a modal dims its parent, so the
spec stands out and the chat stays live. A click on it closes. */}
<div
className="ze-ai-docview-scrim"
style={{ right: window.innerWidth - a.right }}
onClick={hideDoc}
/>
<div
className="ze-app ze-ai-docview"
style={{
left: (a.left + a.right - w) / 2,
top: (a.top + a.bottom - h) / 2,
width: w,
height: h,
}}
>
<div
className="ze-modal ze-ai-docview-dialog"
role="dialog"
aria-label={doc.title}
data-testid="ai-doc-viewer"
>
<div className="ze-modal-header">
{doc.title}
<span className="x" title="Close (Esc)" onClick={hideDoc}>
✕
</span>
</div>
<div className="ze-ai-docview-body">
<Markdown text={doc.text} className="ze-md-doc" />
</div>
</div>
</div>
</>
);
}
+13
View File
@@ -0,0 +1,13 @@
export { AiDock } from './ai_dock.js';
export { AI_AGENT_URL, aiEnabled } from './ai_flag.js';
export {
type AiBridge,
type ApplyResult,
type EditorKind,
type ToolOutput,
aiBridge,
allBridges,
registerAiBridge,
} from './ai_bridge.js';
// sch_bridge.ts is imported by path ('@ziroeda/ai/sch_bridge.js') from the
// schematic frame's lazy chunk, so the entry chunk never pulls in eeschema.
+28
View File
@@ -0,0 +1,28 @@
/**
* The Markdown the assistant writes, rendered as GitHub does it:
* react-markdown with remark-gfm (tables, task lists, strikethrough,
* autolinks). Raw HTML in the source is never rendered, and react-markdown's
* URL filter drops javascript: and the like.
*/
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
const plugins = [remarkGfm];
const components = {
// Links leave the app rather than replacing it.
a: ({ href, children }: { href?: string; children?: React.ReactNode }) => (
<a href={href} target="_blank" rel="noreferrer">
{children}
</a>
),
};
export function Markdown({ text, className }: { text: string; className?: string }): JSX.Element {
return (
<div className={className ? `ze-md ${className}` : 'ze-md'}>
<ReactMarkdown remarkPlugins={plugins} components={components}>
{text}
</ReactMarkdown>
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
{
"name": "@ziroeda/ai",
"version": "0.0.0",
"description": "AI assistant, app side: the chat pane and the bridges that apply the agent's edits to the open design. The agent itself is a separate server.",
"license": "GPL-3.0-or-later",
"type": "module",
"main": "./index.ts",
"types": "./index.ts",
"scripts": {
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@ziroeda/common": "workspace:*",
"@ziroeda/eeschema": "workspace:*",
"@ziroeda/kimath": "workspace:*",
"@ziroeda/pcbnew": "workspace:*",
"@ziroeda/wx": "workspace:*",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-markdown": "^9.1.0",
"remark-gfm": "^4.0.1"
},
"devDependencies": {
"@types/node": "^22.20.0",
"@types/react": "^18.3.18",
"@types/react-dom": "^18.3.5",
"vite": "^6.0.7"
}
}
+660
View File
@@ -0,0 +1,660 @@
/**
* The AI's hands and eyes on the board. Parts and nets come from the
* schematic (Update PCB from Schematic); what the model decides here is
* actions: the outline, where each footprint goes, pours, and checking the
* result. Every edit is one BOARD_COMMIT on the live BOARD, so one Ctrl+Z.
*/
import { SHAPE_T } from '@ziroeda/common/eda_shape.js';
import { toCss } from '@ziroeda/common/gal/color4d.js';
import { LAYER_PCB_BACKGROUND, PCB_LAYER_ID } from '@ziroeda/common/layer_id.js';
import { LSET } from '@ziroeda/common/lset.js';
import { DEFAULT_THEME, PgmOrNull } from '@ziroeda/common/pgm_base.js';
import { PLOT_FORMAT } from '@ziroeda/common/plotters/plotter.js';
import { Reporter } from '@ziroeda/common/reporter.js';
import { COLOR_SETTINGS } from '@ziroeda/common/settings/color_settings.js';
import { RPT_SEVERITY_ERROR, RPT_SEVERITY_IGNORE } from '@ziroeda/common/reporter.js';
import { EDA_ANGLE } from '@ziroeda/kimath/src/geometry/eda_angle.js';
import { BOARD } from '@ziroeda/pcbnew/board.js';
import { BOARD_COMMIT } from '@ziroeda/pcbnew/board_commit.js';
import type { DRC_JOB_VIOLATION } from '@ziroeda/pcbnew/browser/drc_job.js';
import { DRC_ITEM } from '@ziroeda/pcbnew/drc/drc_item.js';
import type { FOOTPRINT } from '@ziroeda/pcbnew/footprint.js';
import { PAD } from '@ziroeda/pcbnew/pad.js';
import {
CTL_ENUMERATE_LAYERS,
CTL_FOR_BOARD,
FormatBoardAsync,
} from '@ziroeda/pcbnew/pcb_io/kicad_sexpr/pcb_io_kicad_sexpr.js';
import type { PcbScriptApi } from '@ziroeda/pcbnew/browser/pcb_script_api.js';
import { PCB_PLOTTER } from '@ziroeda/pcbnew/pcb_plotter.js';
import { DRILL_MARKS, PCB_PLOT_PARAMS } from '@ziroeda/pcbnew/pcb_plot_params.js';
import { PCB_SHAPE } from '@ziroeda/pcbnew/pcb_shape.js';
import { PADSTACK } from '@ziroeda/pcbnew/padstack.js';
import { PCB_VIA } from '@ziroeda/pcbnew/pcb_track.js';
import { VIATYPE } from '@ziroeda/pcbnew/pcb_track_types.js';
import { ZONE } from '@ziroeda/pcbnew/zone.js';
import type { AiBridge, ToolOutput } from './ai_bridge.js';
/** Board units: 1 nm. */
const NM_PER_MM = 1e6;
const mm = (nm: number) => String(Math.round((nm / NM_PER_MM) * 100) / 100);
const nm = (v: unknown) => Math.round(Number(v) * NM_PER_MM);
const EDGE_CUTS = 'Edge.Cuts';
const padName = (p: PAD) => `${p.GetParentFootprint()?.GetReference() ?? '?'}.${p.GetNumber()}`;
function describe(item: unknown): string {
if (item instanceof PAD) return padName(item);
const it = item as { GetNetname?: () => string; GetPosition?: () => { x: number; y: number } };
const at = it.GetPosition?.();
return `${it.GetNetname?.() || 'item'}${at ? `@${mm(at.x)},${mm(at.y)}` : ''}`;
}
/** KiCad's standard layer name (B.Cu), not a board's own rename of it. */
const layerName = (id: number) => BOARD.GetStandardLayerName(id);
function outlineOf(board: BOARD): string {
const edges = board.Drawings().filter((d) => d.GetLayer() === board.GetLayerID(EDGE_CUTS));
if (!edges.length) return 'outline none';
// A lone shape by its own geometry: the bounding box carries half the
// line width on every side.
const only = edges.length === 1 ? edges[0] : undefined;
if (only instanceof PCB_SHAPE) {
const shape = only.GetShape();
if (shape === SHAPE_T.RECTANGLE) {
const a = only.GetStart();
const b = only.GetEnd();
const x = Math.min(a.x, b.x);
const y = Math.min(a.y, b.y);
const r = only.GetCornerRadius();
return `outline rect @${mm(x)},${mm(y)} ${mm(Math.abs(b.x - a.x))}x${mm(Math.abs(b.y - a.y))}${r > 0 ? ` r=${mm(r)}` : ''}`;
}
if (shape === SHAPE_T.CIRCLE) {
const c = only.getCenter();
return `outline circle @${mm(c.x)},${mm(c.y)} d=${mm(2 * only.GetRadius())}`;
}
if (shape === SHAPE_T.POLY)
return `outline poly ${only
.GetPolyPoints()
.map((p) => `${mm(p.x)},${mm(p.y)}`)
.join(' ')}`;
}
const b = board.GetBoardEdgesBoundingBox();
return `outline bbox @${mm(b.GetX())},${mm(b.GetY())} ${mm(b.GetWidth())}x${mm(b.GetHeight())}`;
}
/** The compact board view: what the model needs to place, pour and check. */
export function readBoard(board: BOARD): string {
const lines = [`board ${board.GetCopperLayerCount()}-layer ${outlineOf(board)}`];
for (const fp of board.Footprints()) {
const p = fp.GetPosition();
const box = fp.GetBoundingBox(false);
const rot = Math.round(fp.GetOrientation().AsDegrees());
lines.push(
`fp ${fp.GetReference()} ${fp.GetFPID().Format()} @${mm(p.x)},${mm(p.y)}${rot ? ` r${rot}` : ''} ${
fp.IsFlipped() ? 'B' : 'F'
} size ${mm(box.GetWidth())}x${mm(box.GetHeight())} val=${fp.GetValue()}${fp.IsBoardOnly() ? ' board-only' : ''}`,
);
}
// Nets by their pads, so the model knows what wants to be near what.
const byNet = new Map<string, string[]>();
for (const fp of board.Footprints())
for (const pad of fp.Pads()) {
const net = pad.GetNetname();
if (!net) continue;
byNet.set(net, [...(byNet.get(net) ?? []), padName(pad)]);
}
for (const [net, pads] of byNet) if (pads.length > 1) lines.push(`net ${net} ${pads.join(' ')}`);
let tracks = 0;
let vias = 0;
for (const t of board.Tracks()) {
if (t instanceof PCB_VIA) {
vias++;
const p = t.GetPosition();
lines.push(`via ${t.GetNetname()} @${mm(p.x)},${mm(p.y)}`);
} else tracks++;
}
for (const z of board.Zones())
lines.push(
`zone ${z.GetNetname() || '(no net)'} ${layerName(z.GetFirstLayer())}${z.IsFilled() ? ' filled' : ''}`,
);
const conn = board.GetConnectivity();
const unrouted: string[] = [];
conn.RunOnUnconnectedEdges((e) => {
const a = e.GetSourceNode()?.Parent();
const b = e.GetTargetNode()?.Parent();
if (a && b) unrouted.push(`${a.GetNetname()}: ${describe(a)}-${describe(b)}`);
return unrouted.length < 40;
});
lines.push(`tracks ${tracks} vias ${vias} unrouted ${conn.GetUnconnectedCount(false)}`);
if (unrouted.length) lines.push(...unrouted.map((u) => ` unrouted ${u}`));
return lines.join('\n');
}
/** One BOARD_COMMIT around `edit`, pushed with `message`. */
function commit(
api: PcbScriptApi,
message: string,
edit: (c: BOARD_COMMIT, b: BOARD) => void,
): void {
const frame = api.frame();
const board = api.board();
if (!frame || !board) throw new Error('no board open');
const c = new BOARD_COMMIT(frame);
edit(c, board);
if (!c.Empty()) c.Push(message);
}
/**
* Replace the board outline (Edge.Cuts) with one closed shape: a rectangle
* (optionally with rounded corners), a circle, or any polygon.
*/
function setOutline(api: PcbScriptApi, args: Record<string, unknown>): string {
const kind = String(args.shape ?? 'rect');
let make: (b: BOARD) => PCB_SHAPE;
let said: string;
if (kind === 'rect') {
const x = nm(args.x ?? 100);
const y = nm(args.y ?? 50);
const w = nm(args.width);
const h = nm(args.height);
if (!(w > 0 && h > 0)) throw new Error('a rect needs width and height (mm)');
const r = args.corner_radius !== undefined ? nm(args.corner_radius) : 0;
if (r < 0 || 2 * r > Math.min(w, h))
throw new Error('corner_radius must be at most half the shorter side');
make = (b) => {
const s = new PCB_SHAPE(b, SHAPE_T.RECTANGLE);
s.SetStart({ x, y });
s.SetEnd({ x: x + w, y: y + h });
if (r > 0) s.SetCornerRadius(r);
return s;
};
said = `rectangle ${args.width} x ${args.height} mm at ${mm(x)},${mm(y)}${r > 0 ? `, corners r ${args.corner_radius}` : ''}`;
} else if (kind === 'circle') {
const cx = nm(args.x);
const cy = nm(args.y);
const d = nm(args.diameter);
if (!(d > 0)) throw new Error('a circle needs x, y (centre) and diameter (mm)');
make = (b) => {
const s = new PCB_SHAPE(b, SHAPE_T.CIRCLE);
s.SetStart({ x: cx, y: cy });
s.SetEnd({ x: cx + d / 2, y: cy });
return s;
};
said = `circle d ${args.diameter} mm at ${mm(cx)},${mm(cy)}`;
} else if (kind === 'polygon') {
const pts = ((args.points ?? []) as unknown[]).map((p) => {
const [x, y] = Array.isArray(p) ? p : [];
return { x: nm(x), y: nm(y) };
});
if (pts.length < 3 || pts.some((p) => !Number.isFinite(p.x) || !Number.isFinite(p.y)))
throw new Error('a polygon needs at least 3 points [[x,y],...] in mm');
make = (b) => {
const s = new PCB_SHAPE(b, SHAPE_T.POLY);
s.SetPolyPoints(pts);
return s;
};
said = `polygon of ${pts.length} corners`;
} else throw new Error('shape is rect, circle or polygon');
commit(api, 'Board outline', (c, b) => {
const layer = b.GetLayerID(EDGE_CUTS);
for (const d of b.Drawings()) if (d.GetLayer() === layer) c.Remove(d);
const s = make(b);
s.SetLayer(layer);
s.SetWidth(nm(0.1));
c.Add(s);
});
return `Outline set: ${said}.`;
}
interface Placement {
ref: string;
x: number;
y: number;
rot?: number;
side?: 'F' | 'B';
}
function place(api: PcbScriptApi, args: Record<string, unknown>): string {
const list = (args.placements ?? []) as Placement[];
const errors: string[] = [];
let moved = 0;
commit(api, 'Place footprints', (c, b) => {
const flipDir = api.frame()?.GetPcbNewSettings().m_FlipDirection;
for (const p of list) {
const fp: FOOTPRINT | null = b.FindFootprintByReference(p.ref);
if (!fp) {
errors.push(`no footprint ${p.ref}`);
continue;
}
c.Modify(fp);
const at = { x: nm(p.x), y: nm(p.y) };
const wantBack = p.side === 'B';
if (p.side && wantBack !== fp.IsFlipped() && flipDir !== undefined)
fp.Flip(fp.GetPosition(), flipDir);
fp.SetPosition(at);
if (p.rot !== undefined) fp.SetOrientation(new EDA_ANGLE(Number(p.rot)));
moved++;
}
});
return `Placed ${moved} footprints.${errors.length ? `\n${errors.join('\n')}` : ''}`;
}
function addZone(api: PcbScriptApi, args: Record<string, unknown>): string {
const netName = String(args.net ?? '');
const layerName = String(args.layer ?? 'B.Cu');
commit(api, 'Add zone', (c, b) => {
const net = b.FindNet(netName);
if (!net) throw new Error(`no net ${netName}`);
const layer = b.GetLayerID(layerName);
if (layer < 0) throw new Error(`no layer ${layerName}`);
// The board outline, unless a rectangle is given.
const box = b.GetBoardEdgesBoundingBox();
const x = args.x !== undefined ? nm(args.x) : box.GetX();
const y = args.y !== undefined ? nm(args.y) : box.GetY();
const w = args.width !== undefined ? nm(args.width) : box.GetWidth();
const h = args.height !== undefined ? nm(args.height) : box.GetHeight();
const z = new ZONE(b);
z.SetLayer(layer);
z.SetNetCode(net.GetNetCode());
for (const p of [
{ x, y },
{ x: x + w, y },
{ x: x + w, y: y + h },
{ x, y: y + h },
])
z.AppendCorner(p, -1);
c.Add(z);
});
return `Zone added: ${netName} on ${layerName}. Run fill_zones to pour it.`;
}
async function runDrc(api: PcbScriptApi): Promise<string> {
const frame = api.frame();
const board = api.board();
if (!frame || !board) return 'no board open';
const text = await FormatBoardAsync(
board,
() => new Promise((r) => setTimeout(r, 0)),
() => false,
undefined,
undefined,
CTL_FOR_BOARD | CTL_ENUMERATE_LAYERS,
);
if (text === null) return 'DRC could not read the board';
const found: DRC_JOB_VIOLATION[] = [];
await frame.RunDrcJob(
{
boardText: text,
boardPath: board.GetFileName(),
boardUuid: board.m_Uuid,
projectText: frame.GetProjectText(),
rulesText: frame.GetDesignRulesText(),
rulesPath: frame.GetDesignRulesPath(),
netlistText: frame.GetSchematicNetlistText(),
units: frame.GetUserUnits(),
reportAllTrackErrors: false,
testFootprints: true,
},
{ onPhase: () => {}, onProgress: () => {}, onViolation: (v) => found.push(v) },
);
// Name the items by what the model knows them as.
const names = new Map<string, string>();
for (const fp of board.Footprints()) {
names.set(fp.m_Uuid, fp.GetReference());
for (const pad of fp.Pads()) names.set(pad.m_Uuid, padName(pad));
}
for (const t of board.Tracks()) names.set(t.m_Uuid, describe(t));
for (const z of board.Zones()) names.set(z.m_Uuid, `zone ${z.GetNetname()}`);
const settings = board.GetDesignSettings();
const lines = new Set<string>();
for (const v of found) {
const sev = settings.GetSeverity(v.errorCode);
if (sev === RPT_SEVERITY_IGNORE) continue;
const title = DRC_ITEM.Create(v.errorCode)?.GetErrorText(false) ?? `code ${v.errorCode}`;
const items = v.ids.map((id) => names.get(id) ?? '').filter(Boolean);
lines.add(
`${sev === RPT_SEVERITY_ERROR ? 'error' : 'warning'} ${title}${v.errorMessage ? `: ${v.errorMessage}` : ''} @${mm(v.pos.x)},${mm(v.pos.y)}${items.length ? ` [${items.join(' ')}]` : ''}`,
);
}
const unrouted = board.GetConnectivity().GetUnconnectedCount(false);
const head = `${lines.size} DRC violations, ${unrouted} unrouted connections`;
return lines.size || unrouted ? [head, ...[...lines].slice(0, 60)].join('\n') : 'DRC clean';
}
/** Remove the tracks, arcs and vias of a net, or of every net. */
function unroute(api: PcbScriptApi, args: Record<string, unknown>): string {
const net = args.net === undefined ? undefined : String(args.net);
let n = 0;
commit(api, net ? `Unroute ${net}` : 'Unroute all', (c, b) => {
if (net && !b.FindNet(net)) throw new Error(`no net ${net}`);
for (const t of b.Tracks())
if (net === undefined || t.GetNetname() === net) {
c.Remove(t);
n++;
}
});
return `Removed ${n} tracks and vias${net ? ` of ${net}` : ''}.`;
}
function deleteZone(api: PcbScriptApi, args: Record<string, unknown>): string {
const net = String(args.net ?? '');
const layer = args.layer === undefined ? undefined : String(args.layer);
let n = 0;
commit(api, 'Delete zone', (c, b) => {
for (const z of b.Zones())
if (
z.GetNetname() === net &&
(layer === undefined || layerName(z.GetFirstLayer()) === layer)
) {
c.Remove(z);
n++;
}
});
if (!n) throw new Error(`no zone for ${net}${layer ? ` on ${layer}` : ''}`);
return `Removed ${n} zone${n === 1 ? '' : 's'}.`;
}
/** A through via (F.Cu to B.Cu) on a net, at the board's current via size. */
function addVia(api: PcbScriptApi, args: Record<string, unknown>): string {
const netName = String(args.net ?? '');
const at = { x: nm(args.x), y: nm(args.y) };
commit(api, 'Add via', (c, b) => {
const net = b.FindNet(netName);
if (!net) throw new Error(`no net ${netName}`);
const ds = b.GetDesignSettings();
const v = new PCB_VIA(b);
v.SetPosition(at);
v.SetViaType(VIATYPE.THROUGH);
v.SetLayerPair(PCB_LAYER_ID.F_Cu, PCB_LAYER_ID.B_Cu);
v.SetWidth(
PADSTACK.ALL_LAYERS,
args.size !== undefined ? nm(args.size) : ds.GetCurrentViaSize(),
);
v.SetDrill(args.drill !== undefined ? nm(args.drill) : ds.GetCurrentViaDrill());
v.SetNetCode(net.GetNetCode());
c.Add(v);
});
return `Via on ${netName} at ${mm(at.x)},${mm(at.y)}. Route to it with route from/to "@${mm(at.x)},${mm(at.y)}".`;
}
/** [data] KiCad's MountingHole library: the plain (unplated) hole per screw. */
const MOUNTING_HOLE: Record<string, string> = {
M2: 'MountingHole:MountingHole_2.2mm_M2',
'M2.5': 'MountingHole:MountingHole_2.7mm_M2.5',
M3: 'MountingHole:MountingHole_3.2mm_M3',
M4: 'MountingHole:MountingHole_4.3mm_M4',
};
async function addMountingHole(api: PcbScriptApi, args: Record<string, unknown>): Promise<string> {
const size = String(args.size ?? 'M3');
const libId = MOUNTING_HOLE[size];
if (!libId) throw new Error(`size is one of ${Object.keys(MOUNTING_HOLE).join(', ')}`);
const fp = await api.loadFootprint(libId);
if (!fp) throw new Error(`could not load ${libId}`);
let ref = '';
commit(api, 'Add mounting hole', (c, b) => {
let n = 1;
while (b.FindFootprintByReference(`H${n}`)) n++;
ref = `H${n}`;
fp.SetParent(b);
fp.SetReference(ref);
fp.SetPosition({ x: nm(args.x), y: nm(args.y) });
// Not in the schematic, and must survive Update PCB from Schematic.
fp.SetBoardOnly(true);
c.Add(fp);
});
return `${ref} (${size}) at ${args.x},${args.y}.`;
}
/** Move, turn, resize or hide a footprint's reference or value text. */
function editText(api: PcbScriptApi, args: Record<string, unknown>): string {
const ref = String(args.ref ?? '');
const which = args.field === 'value' ? 'value' : 'reference';
commit(api, 'Edit footprint text', (c, b) => {
const fp = b.FindFootprintByReference(ref);
if (!fp) throw new Error(`no footprint ${ref}`);
c.Modify(fp);
const t = which === 'value' ? fp.Value() : fp.Reference();
if (args.x !== undefined && args.y !== undefined)
t.SetPosition({ x: nm(args.x), y: nm(args.y) });
if (args.rot !== undefined) t.SetTextAngle(new EDA_ANGLE(Number(args.rot)));
if (args.size !== undefined) t.SetTextSize({ x: nm(args.size), y: nm(args.size) });
if (args.visible !== undefined) t.SetVisible(Boolean(args.visible));
});
return `Edited ${ref}'s ${which} text.`;
}
function findPad(board: BOARD, name: string): PAD {
const dot = name.lastIndexOf('.');
const fp = board.FindFootprintByReference(name.slice(0, dot));
const pad = fp?.FindPadByNumber(name.slice(dot + 1));
if (!pad) throw new Error(`no pad ${name}`);
return pad;
}
/** The copper side a pad can be routed from: its own for SMD, F.Cu for through-hole. */
const padLayer = (board: BOARD, pad: PAD) =>
pad.IsOnLayer(board.GetLayerID('F.Cu')) ? 'F.Cu' : 'B.Cu';
/** A route end: `REF.PAD`, or `@x,y` (mm) for a via or a track point. */
function endpoint(board: BOARD, spec: string): { at: { x: number; y: number }; pad?: PAD } {
const m = /^@(-?[\d.]+),(-?[\d.]+)$/.exec(spec);
if (m) return { at: { x: nm(m[1]), y: nm(m[2]) } };
const pad = findPad(board, spec);
return { at: pad.GetPosition(), pad };
}
async function route(api: PcbScriptApi, args: Record<string, unknown>): Promise<string> {
const board = api.board();
if (!board) throw new Error('no board open');
const a = endpoint(board, String(args.from ?? ''));
const b = endpoint(board, String(args.to ?? ''));
const layer = String(
args.layer ?? (a.pad ? padLayer(board, a.pad) : b.pad ? padLayer(board, b.pad) : 'F.Cu'),
);
// Both ends must take a track on `layer`: a top-only SMD pad cannot start
// or end a B.Cu route; that needs a via.
const layerId = board.GetLayerID(layer);
for (const [what, end] of [
['start', a],
['target', b],
] as const)
if (end.pad && !end.pad.IsOnLayer(layerId))
throw new Error(
`the ${what} pad ${padName(end.pad)} is not on ${layer}; route on its layer, or add_via beside it and route to the via`,
);
const through = ((args.through ?? []) as unknown[]).map((p) => endpoint(board, String(p)).at);
const r = await api.route(a.at, b.at, layer, through);
if (!r.ok) throw new Error(`${args.from} -> ${args.to}: ${r.reason}`);
return `Routed ${args.from} -> ${args.to} on ${layer}${through.length ? ` through ${through.length} point${through.length === 1 ? '' : 's'}` : ''}.`;
}
/** Every unrouted connection of a net, along the ratsnest's own pairs. */
async function routeNet(api: PcbScriptApi, args: Record<string, unknown>): Promise<string> {
const board = api.board();
if (!board) throw new Error('no board open');
const net = String(args.net ?? '');
const pairs: {
a: { x: number; y: number };
b: { x: number; y: number };
label: string;
layer: string;
}[] = [];
board.GetConnectivity().RunOnUnconnectedEdges((e) => {
const s = e.GetSourceNode();
const t = e.GetTargetNode();
const sp = s?.Parent();
if (!s || !t || !sp || sp.GetNetname() !== net) return true;
const layer =
args.layer !== undefined
? String(args.layer)
: sp instanceof PAD
? padLayer(board, sp)
: 'F.Cu';
pairs.push({ a: s.Pos(), b: t.Pos(), label: `${describe(sp)}-${describe(t.Parent())}`, layer });
return true;
});
if (!pairs.length) return `${net}: nothing to route.`;
const failed: string[] = [];
let done = 0;
for (const p of pairs) {
const r = await api.route(p.a, p.b, p.layer);
if (r.ok) done++;
else failed.push(`${p.label}: ${r.reason}`);
}
return `${net}: routed ${done} of ${pairs.length}.${failed.length ? `\n${failed.join('\n')}` : ''}`;
}
/**
* The board as a picture, through File > Plot's own path: PCB_PLOTTER to SVG
* per layer in the theme's colours (fit to the board, so every layer shares
* one frame), stacked back to front on the theme background and rasterised.
* The editor's canvas cannot be read back: it draws through WebGL.
*/
/** The picture's layers, back to front. */
const PICTURE_LAYERS = [
PCB_LAYER_ID.B_Cu,
PCB_LAYER_ID.F_Cu,
PCB_LAYER_ID.F_SilkS,
PCB_LAYER_ID.Edge_Cuts,
];
/** File > Plot to SVG, one document per layer of PICTURE_LAYERS, theme colours. */
export function plotPictureLayers(board: BOARD): { svgs: string[]; colors: COLOR_SETTINGS } {
const layers = [
PCB_LAYER_ID.B_Cu,
PCB_LAYER_ID.F_Cu,
PCB_LAYER_ID.F_SilkS,
PCB_LAYER_ID.Edge_Cuts,
];
const params = new PCB_PLOT_PARAMS();
params.assign(board.GetPlotOptions());
params.SetFormat(PLOT_FORMAT.SVG);
params.SetPlotFrameRef(false);
params.SetSvgFitPageToBoard(true);
params.SetBlackAndWhite(false);
params.SetMirror(false);
params.SetNegative(false);
params.SetAutoScale(false);
params.SetScale(1);
params.SetDrillMarksType(DRILL_MARKS.FULL_DRILL_SHAPE);
params.SetLayerSelection(new LSET(layers));
const mgr = PgmOrNull()?.GetSettingsManager();
const cfg = mgr?.GetAppSettings<{ m_ColorTheme: string }>('pcbnew');
const colors = mgr
? mgr.GetColorSettings(cfg ? cfg.m_ColorTheme : DEFAULT_THEME)
: new COLOR_SETTINGS();
params.SetColorSettings(colors);
const svgs: string[] = [];
new PCB_PLOTTER(board, new Reporter(), params).Plot('', layers, [], false, (_name, bytes) => {
svgs.push(new TextDecoder().decode(bytes));
});
return { svgs, colors };
}
async function boardPicture(board: BOARD): Promise<string> {
const { svgs, colors } = plotPictureLayers(board);
if (!svgs.length) throw new Error('the plotter wrote nothing');
const images = await Promise.all(
svgs.map(async (svg) => {
const img = new Image();
img.src = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' }));
await img.decode();
return img;
}),
);
const first = images[0] as HTMLImageElement;
const w = 1600;
const h = Math.max(1, Math.round((w * first.naturalHeight) / Math.max(1, first.naturalWidth)));
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('no 2D canvas');
ctx.fillStyle = toCss(colors.GetColor(LAYER_PCB_BACKGROUND));
ctx.fillRect(0, 0, w, h);
for (const img of images) {
ctx.globalAlpha = 0.85;
ctx.drawImage(img, 0, 0, w, h);
URL.revokeObjectURL(img.src);
}
return canvas.toDataURL('image/png').slice('data:image/png;base64,'.length);
}
export function pcbBridge(api: PcbScriptApi): AiBridge {
const read = () => {
const b = api.board();
return b ? readBoard(b) : '(no board open)';
};
const safe =
(note: string, fn: (args: Record<string, unknown>) => string | Promise<string>) =>
async (args: Record<string, unknown>): Promise<ToolOutput> => {
try {
const text = await fn(args);
return { text, note: `${note}: ${text.split('\n')[0]}` };
} catch (e) {
return {
text: (e as Error).message,
isError: true,
note: `${note} failed: ${(e as Error).message}`,
};
}
};
const tools: Record<string, (args: Record<string, unknown>) => Promise<ToolOutput>> = {
update_pcb_from_schematic: safe('updated the PCB from the schematic', async () => {
const r = await api.updateFromSchematic();
if (!r.ok) throw new Error(r.report);
return `${r.report || 'No changes.'}\n\n${read()}`;
}),
read_board: async () => ({ text: read(), note: 'read the board' }),
set_outline: safe('board outline', (a) => setOutline(api, a)),
place: safe('placed', (a) => place(api, a)),
add_zone: safe('zone', (a) => addZone(api, a)),
fill_zones: safe('filled zones', () => {
api.fillZones();
return 'Zones filled.';
}),
run_drc: safe('DRC', () => runDrc(api)),
route: safe('route', (a) => route(api, a)),
unroute: safe('unrouted', (a) => unroute(api, a)),
add_via: safe('via', (a) => addVia(api, a)),
add_mounting_hole: safe('mounting hole', (a) => addMountingHole(api, a)),
edit_text: safe('text', (a) => editText(api, a)),
delete_zone: safe('deleted zone', (a) => deleteZone(api, a)),
undo_board: safe('undid', () => {
const frame = api.frame();
if (!frame) throw new Error('no board open');
if (frame.GetUndoCommandCount() <= 0) throw new Error('nothing to undo');
frame.RestoreCopyFromUndoList();
return 'Undid the last board edit.';
}),
// Internal: the app bridge's view_3d opens the 3D frame through here.
open_3d: safe('open 3D', () => {
if (!api.show3D) throw new Error('this editor has no 3D viewer');
api.show3D();
return 'Opening the 3D viewer.';
}),
route_net: safe('route net', (a) => routeNet(api, a)),
view_board: async () => {
const b = api.board();
if (!b) return { text: 'No board is open.', isError: true, note: 'no board to look at' };
try {
const png = await boardPicture(b);
return {
text: 'The board (plotted: B.Cu, F.Cu, F.Silkscreen, Edge.Cuts).',
imagePng: png,
note: 'looked at the board',
};
} catch (e) {
return {
text: `could not picture the board: ${(e as Error).message}`,
isError: true,
note: 'board picture failed',
};
}
},
};
return { kind: 'pcb', read, run: (name, args) => tools[name]?.(args) ?? null };
}
+45
View File
@@ -0,0 +1,45 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
/**
* The wire format between the chat pane and the AI agent server (a separate program the pane
* talks to over HTTP). The server keeps its own copy of these types; change both together.
*/
export interface ChatRequest {
/** The Claude Code session to continue; absent on the first turn. */
sessionId?: string;
message: string;
/** Pictures the user attached (base64, no data: prefix). */
images?: { mediaType: string; data: string }[];
model?: string;
}
/** One NDJSON line sent to the chat pane. */
export type ChatEvent =
| { type: 'text'; text: string }
/** What the model is doing while nothing visible streams: thinking, writing a tool call. */
| { type: 'status'; text: string }
| { type: 'session'; sessionId: string; model?: string }
/** One model call's tokens, as it ends; no cost (the CLI prices the turn). */
| { type: 'usage-live'; input: number; output: number; cacheRead: number; cacheWrite: number }
| {
type: 'usage';
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
costUsd: number;
}
| { type: 'error'; message: string }
/** The model called a tool: the tab runs it and posts /tool-result. */
| { type: 'tool'; id: string; name: string; args: Record<string, unknown> }
| { type: 'done' };
/** What the tab posts back for a tool call. */
export interface ToolResult {
id: string;
text: string;
isError?: boolean;
/** A picture for the model (PNG, base64). */
imagePng?: string;
}
+1154
View File
File diff suppressed because it is too large Load Diff
+441
View File
@@ -0,0 +1,441 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
/**
* zsch's hierarchy lines, run on the live model (KiCad's own classes) through the frame:
*
* sheet "NAME" FILE @x,y w,h a new sheet on the sheet being edited (SCH_DRAWING_TOOLS::DrawSheet)
* in "NAME" | in root the lines after it edit that sheet (a path: "Power/Reg")
* port NAME DIR REF.PIN | @x,y a hierarchical label in the sheet being edited, on a pin or a point,
* turned as KiCad turns a label placed there (AutoRotateItem)
* pins "NAME" a sheet pin for every hierarchical label inside that sheet
* (SCH_DRAWING_TOOLS::AutoPlaceAllSheetPins)
*
* and, on the parent, a `net` line names a sheet pin as SHEET.PIN: the net's label goes on it.
*
* Every edit is one KiCad does from its own tools; the edits come back to the window as one undo
* step (SchScriptApi.editLive). Positions are mm on the 50 mil grid, as in the rest of zsch.
*/
import { schIUScale } from '@ziroeda/common/eda_units.js';
import { IS_MOVING, IS_NEW } from '@ziroeda/common/eda_item_flags.js';
import { parseColor4d } from '@ziroeda/common/gal/color4d.js';
import { FIELD_T } from '@ziroeda/common/template_fieldnames.js';
import type { VECTOR2I } from '@ziroeda/kimath/src/math/vector2.js';
import { currentEeschemaSettings } from '@ziroeda/eeschema/eeschema_settings.js';
import type { SCH_EDIT_FRAME } from '@ziroeda/eeschema/sch_edit_frame.js';
import { AUTOPLACE_ALGO } from '@ziroeda/eeschema/sch_item.js';
import { SCH_COMMIT } from '@ziroeda/eeschema/sch_commit.js';
import {
LABEL_FLAG_SHAPE,
SCH_HIERLABEL,
SCH_LABEL,
type SCH_LABEL_BASE,
SPIN_STYLE,
} from '@ziroeda/eeschema/sch_label.js';
import type { SCH_SCREEN } from '@ziroeda/eeschema/sch_screen.js';
import { SCH_SHEET } from '@ziroeda/eeschema/sch_sheet.js';
import { SHEET_SIDE } from '@ziroeda/eeschema/sch_sheet_pin.js';
import type { SCH_SHEET_PATH } from '@ziroeda/eeschema/sch_sheet_path.js';
import { SCH_SYMBOL } from '@ziroeda/eeschema/sch_symbol.js';
import { SCH_DRAWING_TOOLS } from '@ziroeda/eeschema/tools/sch_drawing_tools.js';
const IU_PER_MM = 10000;
/** KiCad's default schematic grid, 50 mil. */
const GRID = 12700;
const toIU = (s: string) => Math.round((Number.parseFloat(s) * IU_PER_MM) / GRID) * GRID;
const mm = (iu: number) => {
const v = Math.round((iu / IU_PER_MM) * 100) / 100;
return Number.isInteger(v) ? `${v}` : v.toFixed(2).replace(/0+$/, '');
};
const unquote = (s: string) => s.replace(/^"(.*)"$/, '$1');
/** zsch's port directions, to KiCad's label shapes. */
export const PORT_SHAPES: Readonly<Record<string, LABEL_FLAG_SHAPE>> = {
in: LABEL_FLAG_SHAPE.L_INPUT,
out: LABEL_FLAG_SHAPE.L_OUTPUT,
bidi: LABEL_FLAG_SHAPE.L_BIDI,
tri: LABEL_FLAG_SHAPE.L_TRISTATE,
passive: LABEL_FLAG_SHAPE.L_UNSPECIFIED,
};
const SHAPE_NAMES = new Map(Object.entries(PORT_SHAPES).map(([k, v]) => [v, k]));
/** One hierarchy line, parsed; `at` is the sheet being edited when it runs. */
export type HierOp =
| {
kind: 'sheet';
name: string;
file: string;
at: { x: number; y: number };
end: { x: number; y: number };
}
| {
kind: 'port';
name: string;
shape: LABEL_FLAG_SHAPE;
pin?: string;
at?: { x: number; y: number };
}
| { kind: 'pins'; sheet: string }
| { kind: 'sheetnet'; name: string; pin: string };
const POINT = /^@(-?[\d.]+),(-?[\d.]+)$/;
/** Parse a hierarchy line's tokens (after the keyword), or throw what is wrong with it. */
export function parseHierLine(kw: string, tokens: string[]): HierOp {
if (kw === 'sheet') {
const [name, file, at, size] = tokens;
const m = POINT.exec(at ?? '');
const z = /^w?([\d.]+)[,x]h?([\d.]+)$/.exec(size ?? '');
if (!name || !file || !m || !z) throw new Error('sheet needs "NAME" FILE.kicad_sch @x,y w,h');
const f = unquote(file);
if (!/^[^/\\]+\.kicad_sch$/.test(f))
throw new Error('sheet FILE must be a plain NAME.kicad_sch');
const x = toIU(m[1] ?? '0');
const y = toIU(m[2] ?? '0');
return {
kind: 'sheet',
name: unquote(name),
file: f,
at: { x, y },
end: { x: x + toIU(z[1] ?? '0'), y: y + toIU(z[2] ?? '0') },
};
}
if (kw === 'port') {
const [name, dir, where] = tokens;
const shape = dir === undefined ? undefined : PORT_SHAPES[dir];
if (!name || shape === undefined || !where)
throw new Error(`port needs NAME ${Object.keys(PORT_SHAPES).join('|')} REF.PIN or @x,y`);
const m = POINT.exec(where);
if (m) return { kind: 'port', name, shape, at: { x: toIU(m[1] ?? '0'), y: toIU(m[2] ?? '0') } };
if (!where.includes('.')) throw new Error('port needs a REF.PIN or @x,y to sit on');
return { kind: 'port', name, shape, pin: where };
}
if (kw === 'pins') {
const [sheet] = tokens;
if (!sheet) throw new Error('pins needs "SHEETNAME"');
return { kind: 'pins', sheet: unquote(sheet) };
}
throw new Error(`unknown keyword ${kw}`);
}
/** The root's path. */
function rootPath(aFrame: SCH_EDIT_FRAME): SCH_SHEET_PATH {
return (
aFrame
.Schematic()
.Hierarchy()
.find((p) => p.size() === 1) ?? aFrame.GetCurrentSheet()
);
}
/** The names from the root down to \a aPath's sheet ("" for the root). */
export function sheetPathName(aPath: SCH_SHEET_PATH): string {
const names: string[] = [];
for (let i = 1; i < aPath.size(); i++) names.push(aPath.at(i)!.GetName());
return names.join('/');
}
/** The path named "A/B" below the root (or "root"), or null. */
export function findSheetPath(aFrame: SCH_EDIT_FRAME, aName: string): SCH_SHEET_PATH | null {
if (aName === 'root' || aName === '') return rootPath(aFrame);
return (
aFrame
.Schematic()
.Hierarchy()
.find((p) => p.size() > 1 && sheetPathName(p) === aName) ?? null
);
}
/** The items of class \a aClass on \a aScreen (the ai package does not see KICAD_T). */
function itemsOf<T>(aScreen: SCH_SCREEN, aClass: abstract new (...args: never[]) => T): T[] {
return [...aScreen.Items()].filter((i): i is T & typeof i => i instanceof aClass) as T[];
}
/** The sheet named \a aName placed on \a aScreen. */
function sheetOn(aScreen: SCH_SCREEN, aName: string): SCH_SHEET | null {
for (const sheet of itemsOf(aScreen, SCH_SHEET)) if (sheet.GetName() === aName) return sheet;
return null;
}
/** The connection point of REF.PIN (number or name) on the sheet \a aPath shows. */
function pinPoint(aPath: SCH_SHEET_PATH, aRef: string): { x: number; y: number } | string {
const dot = aRef.lastIndexOf('.');
const ref = aRef.slice(0, dot);
const pin = aRef.slice(dot + 1);
const screen = aPath.LastScreen()!;
for (const symbol of itemsOf(screen, SCH_SYMBOL)) {
if (symbol.GetRef(aPath, false) !== ref) continue;
const pins = symbol.GetPins(aPath);
const hit =
pins.find((p) => p.GetNumber() === pin) ??
pins.find((p) => p.GetName() === pin || p.GetShownName() === pin);
if (hit) return hit.GetPosition();
return `no pin ${aRef}. Its pins: ${pins.map((p) => `${p.GetNumber()}=${p.GetName() || '~'}`).join(' ')}`;
}
return `no part ${ref} on this sheet`;
}
/** The file of the sheet \a aPathName and the names of the sheets placed on it, or null. */
export function sheetFileAndSheets(
aFrame: SCH_EDIT_FRAME,
aPathName: string,
): { file: string; sheets: Set<string> } | null {
const path = findSheetPath(aFrame, aPathName);
const screen = path?.LastScreen();
if (!screen) return null;
return {
file: screen.GetFileName(),
sheets: new Set(itemsOf(screen, SCH_SHEET).map((s) => s.GetName())),
};
}
/**
* `SCH_DRAWING_TOOLS::DrawSheet`'s two clicks without the cursor: the sheet from its top-left
* \a aPos to \a aEnd, given the name and file the sheet properties dialog would have been given
* (the file linked through ChangeSheetFile, as EditSheetProperties does), on the next free page,
* added to the current screen in one commit. Null when the file change was refused.
*/
export async function drawSheet(
aFrame: SCH_EDIT_FRAME,
aTools: SCH_DRAWING_TOOLS,
aPos: VECTOR2I,
aEnd: VECTOR2I,
aName: string,
aFileName: string,
): Promise<SCH_SHEET | null> {
const cfg = currentEeschemaSettings();
const sheet = new SCH_SHEET(aFrame.GetCurrentSheet().Last(), aPos);
sheet.SetScreen(null);
sheet.GetField(FIELD_T.SHEET_NAME)!.SetText(aName);
sheet.GetField(FIELD_T.SHEET_FILENAME)!.SetText(aFileName);
sheet.SetFlags(IS_NEW | IS_MOVING);
sheet.SetBorderWidth(schIUScale.milsToIU(cfg.drawing.default_line_thickness));
sheet.SetBorderColor(parseColor4d(cfg.drawing.default_sheet_border_color));
sheet.SetBackgroundColor(parseColor4d(cfg.drawing.default_sheet_background_color));
aTools.sizeSheet(sheet, aEnd);
const hierarchy = aFrame.Schematic().Hierarchy();
const instance = aFrame.GetCurrentSheet().Clone();
instance.push_back(sheet);
// Find the next available page number by checking all existing page numbers
const usedPageNumbers = new Set<number>();
for (const path of hierarchy) {
const pageNum = Number.parseInt(path.GetPageNumber(), 10);
if (`${pageNum}` === path.GetPageNumber().trim() && pageNum > 0) usedPageNumbers.add(pageNum);
}
let nextAvailable = 1;
while (usedPageNumbers.has(nextAvailable)) nextAvailable++;
instance.SetPageNumber(`${nextAvailable}`);
// EditSheetProperties: the dialog's file name goes through ChangeSheetFile.
if (!(await aFrame.ChangeSheetFile(sheet, aFileName))) return null;
sheet.ClearFlags(IS_NEW | IS_MOVING);
sheet.AutoplaceFields(aFrame.GetScreen(), AUTOPLACE_ALGO.AUTOPLACE_AUTO);
const commit = new SCH_COMMIT(aFrame);
// We need to manually add the sheet to the screen otherwise annotation will not be able to find
// the sheet and its symbols to annotate.
aFrame.AddToScreen(sheet, aFrame.GetScreen());
commit.Added(sheet, aFrame.GetScreen());
// Refresh the hierarchy so the new sheet and its symbols are found during annotation.
aFrame.Schematic().RefreshHierarchy();
commit.Push('Draw Sheet');
return sheet;
}
/**
* `SCH_DRAWING_TOOLS::createNewLabel( aPosition, LAYER_HIERLABEL, … )` with the text and shape
* the label properties dialog would have been given; the caller places it (TwoClickPlace's
* second click). The tool remembers the choices as the dialog makes it.
*/
export function newHierLabel(
aFrame: SCH_EDIT_FRAME,
aTools: SCH_DRAWING_TOOLS,
aPosition: VECTOR2I,
aText: string,
aShape: LABEL_FLAG_SHAPE,
): SCH_LABEL_BASE {
const settings = aFrame.Schematic().Settings();
const labelItem = new SCH_HIERLABEL(aPosition);
labelItem.SetShape(aTools.m_lastGlobalLabelShape);
labelItem.SetAutoRotateOnPlacement(aTools.m_lastAutoLabelRotateOnPlacement);
// The normal parent is the current screen for these labels, set by SCH_SCREEN::Append()
// but it is also used during placement for SCH_HIERLABEL before beeing appended
labelItem.SetParent(aFrame.GetScreen());
labelItem.SetTextSize({ x: settings.m_DefaultTextSize, y: settings.m_DefaultTextSize });
// Must be after SetTextSize()
labelItem.SetBold(aTools.m_lastTextBold);
labelItem.SetItalic(aTools.m_lastTextItalic);
labelItem.SetSpinStyle(aTools.m_lastTextOrientation);
labelItem.SetFlags(IS_NEW | IS_MOVING);
// DIALOG_LABEL_PROPERTIES: the text and shape it would have been given.
labelItem.SetText(aText);
labelItem.SetShape(aShape);
aTools.m_lastTextBold = labelItem.IsBold();
aTools.m_lastTextItalic = labelItem.IsItalic();
aTools.m_lastTextOrientation = labelItem.GetSpinStyle();
aTools.m_lastGlobalLabelShape = labelItem.GetShape();
aTools.m_lastAutoLabelRotateOnPlacement = labelItem.AutoRotateOnPlacement();
return labelItem;
}
/**
* Run \a aOps on the sheet \a aPathName ("" or "root" for the root), in order, on the live frame.
* Returns the screens changed, or throws with every line that failed (nothing is changed then:
* the caller's editLive discards a thrown edit with the live model rebuilt from the window).
*/
export async function runHierOps(
aFrame: SCH_EDIT_FRAME,
aPathName: string,
aOps: readonly { line: string; op: HierOp }[],
): Promise<SCH_SCREEN[]> {
const schematic = aFrame.Schematic();
// A copy: SetCurrentSheet assigns into the schematic's own path (*m_currentSheet = aPath).
const before = schematic.CurrentSheet().Clone();
const path = findSheetPath(aFrame, aPathName);
if (!path) throw new Error(`in ${aPathName}: no such sheet`);
const tools = new SCH_DRAWING_TOOLS(aFrame);
const changed = new Set<SCH_SCREEN>();
const errors: string[] = [];
schematic.SetCurrentSheet(path);
try {
for (const { line, op } of aOps) {
// Every op works on the sheet the batch is editing, whatever an earlier op entered.
schematic.SetCurrentSheet(path);
const screen = path.LastScreen()!;
try {
if (op.kind === 'sheet') {
if (sheetOn(screen, op.name)) throw new Error(`a sheet ${op.name} is already here`);
const sheet = await drawSheet(aFrame, tools, op.at, op.end, op.name, op.file);
if (!sheet) throw new Error(`sheet ${op.file} could not be used`);
changed.add(screen);
changed.add(sheet.GetScreen()!);
} else if (op.kind === 'port') {
const at = op.at ?? pinPoint(path, op.pin ?? '');
if (typeof at === 'string') throw new Error(at);
const label = newHierLabel(aFrame, tools, at, op.name, op.shape);
// TwoClickPlace's second click: AutoRotateItem on a connectable item, then the commit.
label.SetAutoRotateOnPlacement(true);
label.ClearFlags();
aFrame.AutoRotateItem(screen, label);
const commit = new SCH_COMMIT(aFrame);
aFrame.AddToScreen(label, screen);
commit.Added(label, screen);
commit.Push('Place Label');
changed.add(screen);
} else if (op.kind === 'pins') {
const sheet = sheetOn(screen, op.sheet);
if (!sheet) throw new Error(`no sheet ${op.sheet} on this sheet`);
if (!tools.autoPlaceSheetPins(sheet))
throw new Error(
`no new hierarchical labels found in ${op.sheet}: add port lines inside it first`,
);
changed.add(screen);
} else {
// A net's label on a sheet pin: the side tells the label which way to face.
const dot = op.pin.lastIndexOf('.');
const sheet = sheetOn(screen, op.pin.slice(0, dot));
const pin = sheet?.GetPins().find((p) => p.GetText() === op.pin.slice(dot + 1));
if (!sheet || !pin)
throw new Error(
sheet
? `no pin ${op.pin}. Its pins: ${
sheet
.GetPins()
.map((p) => p.GetText())
.join(' ') || '(none: run pins first)'
}`
: `no sheet ${op.pin.slice(0, dot)} here`,
);
const label = new SCH_LABEL(pin.GetPosition(), op.name);
label.SetTextSize({
x: schematic.Settings().m_DefaultTextSize,
y: schematic.Settings().m_DefaultTextSize,
});
const side = pin.GetSide();
label.SetSpinStyle(
new SPIN_STYLE(
side === SHEET_SIDE.LEFT
? SPIN_STYLE.LEFT
: side === SHEET_SIDE.RIGHT
? SPIN_STYLE.RIGHT
: side === SHEET_SIDE.TOP
? SPIN_STYLE.UP
: SPIN_STYLE.BOTTOM,
),
);
const commit = new SCH_COMMIT(aFrame);
aFrame.AddToScreen(label, screen);
commit.Added(label, screen);
commit.Push('Place Label');
changed.add(screen);
}
} catch (e) {
errors.push(`${line}: ${(e as Error).message}`);
}
}
} finally {
schematic.SetCurrentSheet(before);
}
if (errors.length) throw new Error(errors.join('\n'));
return [...changed];
}
/**
* The hierarchy as zsch, from the live model: every sheet with its file and page, and the sheets
* placed on \a aPathName's sheet with their pins.
*/
export function readHierarchy(aFrame: SCH_EDIT_FRAME, aPathName: string): string {
const lines: string[] = [];
const all = aFrame.Schematic().Hierarchy();
if (all.length > 1) {
lines.push('; hierarchy (page, sheet, file):');
for (const p of all)
lines.push(
`; ${p.GetPageNumber()} ${p.size() === 1 ? 'root' : JSON.stringify(sheetPathName(p))} ${p.LastScreen()?.GetFileName().replace(/^.*\//, '') ?? ''}`,
);
}
const path = findSheetPath(aFrame, aPathName);
if (!path) return lines.join('\n');
const screen = path.LastScreen()!;
for (const sheet of itemsOf(screen, SCH_SHEET)) {
const pos = sheet.GetPosition();
const size = sheet.GetSize();
lines.push(
`sheet ${JSON.stringify(sheet.GetName())} ${sheet.GetFileName()} @${mm(pos.x)},${mm(pos.y)} ${mm(size.x)},${mm(size.y)}`,
);
const pins = sheet.GetPins();
if (pins.length)
lines.push(
`; pins: ${pins.map((p) => `${p.GetText()}(${SHAPE_NAMES.get(p.GetShape()) ?? '?'})`).join(' ')}`,
);
}
for (const label of itemsOf(screen, SCH_HIERLABEL)) {
const pos = label.GetPosition();
lines.push(
`port ${label.GetText()} ${SHAPE_NAMES.get(label.GetShape()) ?? 'passive'} @${mm(pos.x)},${mm(pos.y)}`,
);
}
return lines.join('\n');
}
+169
View File
@@ -0,0 +1,169 @@
/**
* What the AI cannot see in a netlist: where things sit on the sheet.
*
* - `partSize`: a symbol's body with its pins, so placements can be spaced.
* - `overlaps`: parts, their fields, labels and power symbols that collide
* (reported as text after every edit, so layout is fixed without a picture).
* - `strays`: labels on nothing and wires with a loose end. A netlist view
* lists only what connects, so these were invisible - and undeletable -
* while ERC complained about them.
*
* Geometry is the editor's own: `symbolBodyBBox` (the autoplacer's body box),
* `symbolFieldBoxes` (what selection picks) and `labelBox`.
*/
import {
type BBox,
type LibSymbol,
type SchLabel,
type SchLine,
type SchSymbol,
type Schematic,
enumeratePins,
labelBox,
refId,
schSymbolLibraryName,
symbolBodyBBox,
symbolFieldBoxes,
} from '@ziroeda/eeschema';
type Pt = { x: number; y: number };
const IU_PER_MM = 10000;
export const mm = (iu: number) => String(Math.round((iu / IU_PER_MM) * 100) / 100);
const at = (p: Pt) => `@${mm(p.x)},${mm(p.y)}`;
const key = (p: Pt) => `${p.x},${p.y}`;
const field = (s: SchSymbol, k: string) => s.fields.find((f) => f.key === k)?.value;
const reference = (s: SchSymbol) => field(s, 'Reference') ?? '?';
export function libMap(doc: Schematic): Map<string, LibSymbol> {
return new Map(doc.libSymbols.map((l) => [l.libId, l]));
}
/** A part's body and pins, w x h in mm. */
export function partSize(sym: SchSymbol, lib: LibSymbol | undefined): string {
const b = symbolBodyBBox(sym, lib);
return `${mm(b.maxX - b.minX)}x${mm(b.maxY - b.minY)}`;
}
/** Something on the sheet that takes room, and whose it is. */
interface Placed {
what: string;
owner: string;
box: BBox;
}
/**
* [ours] How far two boxes must cross to count: a touch along an edge, or
* the hairline a text's pen width adds, is not a collision.
*/
const MIN_OVERLAP = 0.2 * IU_PER_MM;
function crosses(a: BBox, b: BBox): boolean {
const w = Math.min(a.maxX, b.maxX) - Math.max(a.minX, b.minX);
const h = Math.min(a.maxY, b.maxY) - Math.max(a.minY, b.minY);
return w > MIN_OVERLAP && h > MIN_OVERLAP;
}
function placedItems(doc: Schematic): Placed[] {
const libs = libMap(doc);
const out: Placed[] = [];
for (const s of doc.symbols) {
const lib = libs.get(schSymbolLibraryName(s));
const ref = reference(s);
const power = lib?.isPower === true || ref.startsWith('#');
// A power symbol is named by its rail, not its #PWR reference.
const name = power ? `power ${field(s, 'Value') ?? ref}` : ref;
out.push({ what: name, owner: ref, box: symbolBodyBBox(s, lib, { includePins: false }) });
if (power) continue;
for (const f of symbolFieldBoxes(s, lib)) {
out.push({
what: `${ref} ${f.key.toLowerCase()} "${f.shown}"`,
owner: ref,
box: { minX: f.box.x, minY: f.box.y, maxX: f.box.x + f.box.w, maxY: f.box.y + f.box.h },
});
}
}
doc.labels.forEach((l, i) => {
if (l.kind === 'text') return;
out.push({ what: `label ${l.text} ${at(l.at)}`, owner: `label${i}`, box: labelBox(l) });
});
return out;
}
/** Collisions between different owners, at most `limit` of them. */
export function overlaps(doc: Schematic, limit = 15): string[] {
const items = placedItems(doc);
const out: string[] = [];
for (let i = 0; i < items.length && out.length < limit; i++)
for (let j = i + 1; j < items.length && out.length < limit; j++) {
const a = items[i] as Placed;
const b = items[j] as Placed;
if (a.owner === b.owner || !crosses(a.box, b.box)) continue;
out.push(`overlap: ${a.what} / ${b.what}`);
}
return out;
}
/** Whether `p` lies on segment a-b (axis-aligned or not), ends included. */
function onSegment(p: Pt, a: Pt, b: Pt): boolean {
const cross = (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
if (cross !== 0) return false;
return (
p.x >= Math.min(a.x, b.x) &&
p.x <= Math.max(a.x, b.x) &&
p.y >= Math.min(a.y, b.y) &&
p.y <= Math.max(a.y, b.y)
);
}
export interface Stray {
/** The editor id, for deletion. */
id: string;
text: string;
}
/** Labels connected to nothing and wires with an end that touches nothing. */
export function strays(doc: Schematic): Stray[] {
const pinsAt = new Set(enumeratePins(doc, libMap(doc)).map((p) => key(p.at)));
const wires = doc.lines.map((l, i) => ({ l, i })).filter(({ l }) => l.kind === 'wire');
const ncAt = new Set(doc.noConnects.map((n) => key(n.at)));
const labelAt = new Set(doc.labels.filter((l) => l.kind !== 'text').map((l) => key(l.at)));
/** An end is held by a pin, a no-connect, or any other wire touching it. */
const held = (p: Pt, self: number) =>
pinsAt.has(key(p)) ||
ncAt.has(key(p)) ||
wires.some(({ l, i }) => i !== self && onSegment(p, l.start, l.end));
const out: Stray[] = [];
doc.labels.forEach((l: SchLabel, i) => {
if (l.kind === 'text') return;
if (pinsAt.has(key(l.at)) || wires.some(({ l: w }) => onSegment(l.at, w.start, w.end))) return;
out.push({ id: refId('label', l.uuid, i), text: `stray label ${l.text} ${at(l.at)}` });
});
for (const { l, i } of wires) {
const loose = [l.start, l.end].filter((e) => !held(e, i) && !labelAt.has(key(e)));
if (loose.length)
out.push({
id: refId('line', (l as SchLine).uuid, i),
text: `stray wire ${at(l.start)} ${at(l.end)} (loose end ${loose.map(at).join(' ')})`,
});
}
return out;
}
/** An editor item id as the AI reads it: a label by name and place, a wire by its ends. */
export function itemName(doc: Schematic, id: string): string | undefined {
for (let i = 0; i < doc.labels.length; i++) {
const l = doc.labels[i] as SchLabel;
if (refId('label', l.uuid, i) === id) return `label ${l.text} ${at(l.at)}`;
}
for (let i = 0; i < doc.lines.length; i++) {
const l = doc.lines[i] as SchLine;
if (refId('line', l.uuid, i) === id) return `wire ${at(l.start)} ${at(l.end)}`;
}
for (let i = 0; i < doc.noConnects.length; i++) {
const n = doc.noConnects[i];
if (n && refId('noconnect', n.uuid, i) === id) return `no-connect ${at(n.at)}`;
}
return undefined;
}
+11
View File
@@ -0,0 +1,11 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"rootDir": ".",
"jsx": "react-jsx",
"types": ["vite/client", "node"],
"lib": ["ES2022", "DOM", "DOM.Iterable"]
},
"include": ["."],
"exclude": ["node_modules"]
}
+75
View File
@@ -0,0 +1,75 @@
{
"$schema": "https://biomejs.dev/schemas/2.5.3/schema.json",
"vcs": {
"enabled": true,
"clientKind": "git",
"useIgnoreFile": true
},
"files": {
"includes": [
"**",
"!designer/public",
"!designer/src/assets",
"!bitmaps_png/sources",
"!qa/data",
"!**/dist",
"!common/newstroke_font.ts",
"!designer/src/render/gl/vendor",
"!libs/kimath/src/thirdparty/vendor",
"!external/wx/jpeg/imagjpeg_wasm.js",
"!docs/email-templates"
]
},
"formatter": {
"enabled": true,
"indentStyle": "space",
"indentWidth": 2,
"lineWidth": 100
},
"javascript": {
"formatter": {
"quoteStyle": "single",
"semicolons": "always",
"trailingCommas": "all",
"arrowParentheses": "always"
}
},
"assist": {
"actions": {
"source": {
"organizeImports": "off"
}
}
},
"linter": {
"enabled": true,
"rules": {
"preset": "recommended",
"style": {
"noNonNullAssertion": "off",
"noDescendingSpecificity": "warn"
},
"suspicious": {
"noTemplateCurlyInString": "off",
"useIterableCallbackReturn": "warn",
"noArrayIndexKey": "warn"
},
"correctness": {
"useExhaustiveDependencies": "warn"
},
"a11y": "off"
}
},
"overrides": [
{
"includes": ["common/gal/opengl/**"],
"linter": {
"rules": {
"correctness": {
"useHookAtTopLevel": "off"
}
}
}
}
]
}
+122
View File
@@ -0,0 +1,122 @@
# bitmap2component/ against KiCad's `bitmap2component/`
The rule is `gerbview/STRUCTURE.md`'s and `pcbnew/STRUCTURE.md`'s: every file
sits where KiCad keeps it, under KiCad's name, engine **and** screens; only
divergences are recorded, once, here. Reference:
`/home/akshay/kicad-reference/bitmap2component` (10.0.5). There is no `src/`:
the sources sit beside `package.json`, as KiCad's `.cpp` files sit beside
`CMakeLists.txt`.
Conventions carried over from `common/STRUCTURE.md`: a unit is a `.cpp` and
its header; a dialog's `_base.cpp` (wxFormBuilder) folds into the `.tsx` that
draws it; a screen with an engine half is `<name>.ts` (testable without a DOM)
plus `<name>_ui.tsx`.
## The 7 KiCad units — all here, none remaining
`CMakeLists.txt` builds seven `.cpp` files (plus `common/single_top.cpp`,
which `common/STRUCTURE.md` has as n/a). All seven have a home.
| KiCad unit | status | ours / note |
|---|---|---|
| `bitmap2component` (+ `.h`) | here | `bitmap2component.ts`: `OUTPUT_FMT_ID`, `BITMAPCONV_INFO`, `BezierToPolyline`. Writes KiCad's bytes exactly, bar the uuids and the generator token (below) |
| `bitmap2cmp_panel` (+ `.h`) | here | `bitmap2cmp_panel.ts`: `IMAGE_SIZE`, `BITMAP2CMP_PANEL`, `DROP_FILE` — the controls are fields holding what the wx control holds, so the handlers read field text as the C++ does. `IMAGE_SIZE`'s members are defined in `bitmap2cmp_frame.cpp`; the class is declared in `bitmap2cmp_panel.h`, so it lives here |
| `bitmap2cmp_panel_base` (+ `.h`, `.fbp`) | here | folded into `bitmap2cmp_panel_ui.tsx` (the layout, and the three `OnPaint*` handlers) and `bitmap2cmp_panel.css` (the sizer borders) |
| `bitmap2cmp_frame` (+ `.h`) | here | `bitmap2cmp_frame.ts`: `BITMAP2CMP_FRAME` on `EDA_BASE_FRAME` — title, open, the four exports, settings, its `TOOL_MANAGER`. The `wxFrame` half is `bitmap2cmp_frame_ui.tsx` + `bitmap2cmp_frame.css`: `doReCreateMenuBar`, the status bar, the message boxes the frame asks for through `BITMAP2CMP_FRAME_UI`, the About dialog and `m_fileHistory`. What only the program has — `Pgm()`'s settings manager and language, the file dialog (the account's chooser), Preferences, the hotkey list, the way home — comes in as `BITMAP2CMP_APP` |
| `bitmap2cmp_control` (+ `.h`) | here | `bitmap2cmp_control.ts`: `BITMAP2CMP_CONTROL`, `ACTIONS::open` → `OnLoadFile`. The header's `Close()` is declared and never defined upstream; absent |
| `bitmap2cmp_settings` (+ `.h`) | here | `bitmap2cmp_settings.ts`: `BITMAP2CMP_SETTINGS`, its seven PARAMs (`FromJson` / `ToJson`), schema version 1 and the 0 → 1 `last_mod_layer` migration. The JSON store is the app's `bitmap2component` slice, whose defaults now come from this class. `MigrateFromLegacy` (a KiCad 5 wxConfig) is n/a |
| `bitmap2cmp_main` | here | `bitmap2cmp_main.ts`: the `BMP2CMP` kiface's `CreateKiWindow` — the settings object, then the frame. `KIFACE_GETTER`, `OnKifaceStart` and `IfaceOrAddress` are DSO plumbing (n/a, as `kiface_base` is in `common/STRUCTURE.md`) |
Non-source files: `CMakeLists.txt` is `package.json`; `bitmap2component.icns`
(the macOS bundle icon) is n/a — the launcher tile uses
`icon_bitmap2component` from `common/bitmaps_list.ts`.
## KiCad's `thirdparty/potrace` — `libs/potrace`
`bitmap2component` links `potrace`, KiCad's vendored potracelib 1.15. It is a
thirdparty library, so it is `libs/potrace` (as `thirdparty/zint` and
`thirdparty/rectpack2d` are `libs/zint` and `libs/rectpack2d`), mirroring
`src/` and `include/`: `curve`, `decompose`, `trace`, `potracelib`, and the
`auxiliary`, `bitmap` and `lists` headers. Only the library half: `bitmap_io`,
`greymap` and `render` belong to the potrace command-line program and nothing
in KiCad calls them; `progress.h` is not ported because KiCad sets no
progress callback. A scanline is a byte per pixel rather than packed 64-bit
words; `include/bitmap.ts` says why that changes no result.
It is pinned **bit for bit** against KiCad's own C, compiled unmodified
(`qa/probes/potrace_trace_probe.cpp`, `potrace_oracle_gen.py`):
`qa/unittests/libs/potrace/potrace_oracle.test.ts`.
## Ours with no KiCad unit
- `wx.ts` — the wxWidgets calls the panel stands on (`wxImage::LoadFile`'s
result per format, `ConvertToGreyscale`, `GetOptionInt`, `wxBitmap`'s depth,
`wxString::ToDouble`), each measured on this machine's wxGTK 3.2
(`qa/probes/wximage_greyscale_probe.cpp`, `wximage_transparency_probe.cpp`).
The toolkit, kept beside its one caller as `gerbview/libc.ts` keeps the C
library.
- `index.ts` — the package barrel.
- `designer/src/editors/image/ImageConverter.tsx` + `bitmap2cmpSettings.ts` —
not this package's: the program's side of `BITMAP2CMP_APP`, i.e. `Pgm()`
(the settings slice through the shared manager, which syncs it to the
account) and `KIWAY`. KiCad's counterpart is `common/pgm_base.cpp` and
`kicad/`, which is what `designer/` is.
## Deliberate divergences
- **Generator.** `(generator "ziroeda") (generator_version "1.0")` where KiCad
writes `"bitmap2component"` / `"10.0"`: we must not wear KiCad's program
names (`common/generator.ts`). Every other byte is KiCad's, including the
frozen `(version 20221018)` / `20220914` / `20220228` dialect, which our own
readers take (`bitmap2component.test.ts`, last block).
- **No directories, and a save is a download.** `m_mruPath` and the dialogs'
start paths are gone. Export offers `<image name>.<ext>` where KiCad's save
dialog starts empty.
- **Clipboard.** `wxTheClipboard->Open()` failing is the browser refusing the
write, which is only known after the fact; the message is the same.
- **A browser decode.** A canvas stores premultiplied alpha, so a
half-transparent pixel's colour comes back rounded and a fully transparent
one's black. `binarize` never reads a pixel whose alpha fails its cut, so
only the Greyscale page can show the difference.
- **Language.** `ShowChangedLanguage` rebuilds the panel for a new
translation; the app has one language, so it is not ported.
## Divergences the port fixed
Each was found by porting the C++ unit and re-deriving the expectation from
it, or by asking wx on this machine — never by re-baselining.
- **Tracing was the JS potrace, not KiCad's.** It scanned from row 0 where
potrace scans from row `h - 1`, marked holes `'+'` and built no path tree;
outlines were grouped by nesting parity and fractured with earcut's bridge.
A traced ring came out 6 + 5 segments against KiCad's 7 and −5, and curves
were flattened adaptively where `BezierToPolyline` samples at a fixed
epsilon. Now potracelib, KiCad's grouping loop and `SHAPE_POLY_SET`
(Simplify, BooleanSubtract, NormalizeAreaOutlines, Fracture): every vertex
matches KiCad's `SHAPE_POLY_SET` (`poly_oracle.json`, from the installed
`pcbnew` Python module), and the KiCad-written files match byte for byte,
point order included.
- **The output was restyled** (tabs, `(hide yes)`, modern version tokens)
because the footprint reader could not take a bare `hide`; it can now, so
the bytes are KiCad's.
- **A 72 DPI PNG reads 71 PPI.** wx turns `pHYs` into `trunc( ppm / 100 )`
per cm, and KiCad `KiROUND`s that times 2.54; ours computed 72. A unitless
`pHYs` or JFIF density is taken as DPI (ours fell back to 300).
- **Greyscale rounds half away from zero** (`wxRound`); a `Uint8ClampedArray`
rounds half to even, and 6 601 colours differed.
- **A GIF's transparent colour is a mask**, which `OpenProjectFiles` paints
white, so Negative traces it black.
- **Re-locking the ratio re-reads the field.** `OnSizeChangeX` parses the
text: a 24 px image at "2.0" mm exports at 304 DPI, not the 300 the
unrounded size gave.
- **A drop loads through the panel only** (`m_panel->OpenProjectFiles`):
no title, status text or history entry. Open Recent changes neither title
nor status bar either.
- **An unknown `last_format`** checks Footprint with the Layer choice grey
(`Enable( cfg->m_LastFormat == FOOTPRINT_FMT )`).
- **`%.1f` / `%.2f`** round ties to even on the exact binary value
(`0.25` is `0.2`); `toFixed` gave `0.3`.
- **Invented:** WebP and "any image/*" in the file dialog (KiCad offers
png / jpg / jpeg / bmp / gif, and wx has no WebP handler); a load switching
to the Black & White page; "Loading…", "Exported …" and "Copied …" status
texts; `window.alert` for the "Errors" box (it is a `wxMessageBox`).
+47
View File
@@ -0,0 +1,47 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `bitmap2component/bitmap2cmp_control.cpp` + `.h`: `BITMAP2CMP_CONTROL`, the
* frame's one tool. It answers `ACTIONS::open` (File > Open..., Ctrl+O) by
* asking the frame for an image, as the Load Source Image button does.
*
* The header also declares `Close()`, which the `.cpp` never defines and
* nothing binds; it is absent here too.
*/
import { ACTIONS } from '@ziroeda/common/tool/actions.js';
import { RESET_REASON } from '@ziroeda/common/tool/tool_base.js';
import type { TOOL_EVENT } from '@ziroeda/common/tool/tool_event.js';
import { TOOL_INTERACTIVE } from '@ziroeda/common/tool/tool_interactive.js';
import type { BITMAP2CMP_FRAME } from './bitmap2cmp_frame.js';
export class BITMAP2CMP_CONTROL extends TOOL_INTERACTIVE {
private m_frame: BITMAP2CMP_FRAME | null;
constructor() {
super('bitmap2cmp.Control');
this.m_frame = null;
}
/** @copydoc TOOL_INTERACTIVE::Init() */
override Init(): boolean {
this.Reset(RESET_REASON.MODEL_RELOAD);
return true;
}
/** @copydoc TOOL_INTERACTIVE::Reset() */
Reset(_aReason: RESET_REASON): void {
this.m_frame = this.getEditFrame<BITMAP2CMP_FRAME>();
}
// biome-ignore lint/correctness/useYield: Open never waits; a handler is still a coroutine
*Open(_aEvent: TOOL_EVENT) {
void this.m_frame!.OnLoadFile();
return 0;
}
/** Set up handlers for various events. */
protected setTransitions(): void {
this.Go(this.Open, ACTIONS.open.MakeEvent());
}
}
+47
View File
@@ -0,0 +1,47 @@
/* The Image Converter frame, BITMAP2CMP_FRAME's window: the window itself
and its status bar. The panel inside it is
bitmap2component/bitmap2cmp_panel.css.
Every font and colour comes from the shared GTK control-theme tokens in
common/widgets/shell.css. */
.imgc-frame {
/* This frame's status bar is 10px taller than every other frame's, because
BITMAP2CMP_FRAME is one of only two in KiCad that gets a plain
wxStatusBar rather than a KISTATUSBAR. Measured, and explained, at the
.ze-statusbar rule near the bottom of this file. */
--statusbar-height: 33px;
display: flex;
flex-direction: column;
height: 100vh;
background: var(--chrome-bg);
color: var(--chrome-fg);
font-family: var(--ui-font-family);
font-size: var(--ui-font-size);
line-height: var(--ui-line-height);
}
/* The status bar is the shared KiStatusBar (.ze-statusbar in ui/shell.css) -
the widget, the panes and the colours are all the shared ones. What this
frame does NOT share is the HEIGHT, and the difference is real and measured.
BITMAP2CMP_FRAME calls plain CreateStatusBar( 1, wxSTB_SIZEGRIP, wxID_ANY )
(bitmap2component/bitmap2cmp_frame.cpp:181) and does not override
OnCreateStatusBar, so it is one of only two frames in KiCad that get a plain
wxStatusBar instead of a KISTATUSBAR. Measured off a real bitmap2component
window at 1920x1200, column x=600: content (39,39,39) to y=1165, a (24,24,24)
rule at y=1166, bar (44,44,44) from y=1167 to 1199 -> 33px, against the
project manager's 23. The 24px this file used to force was closer to right
than the shared 23; both were wrong.
See --statusbar-height in ui/shell.css for why the two differ and for the
list of explanations that have already been disproved. Do not unify them.
Also local: the frame is a flex column and a native status bar never
shrinks, so its flex-basis has to be pinned. */
.imgc-frame > .ze-statusbar {
flex: none;
}
/* The About box is common/dialog_about's DIALOG_ABOUT, the one every frame
opens; nothing about it is stated here. */
+264
View File
@@ -0,0 +1,264 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `bitmap2component/bitmap2cmp_frame.cpp` + `.h`: `BITMAP2CMP_FRAME`, the
* Image Converter's window, less the window: the file names it remembers,
* the title, the open and the four exports, its settings and its tools.
*
* The window is `designer/src/editors/image/ImageConverter.tsx`, which
* builds the menu bar (`doReCreateMenuBar`), the status bar and the dialogs,
* and supplies them here as `BITMAP2CMP_FRAME_UI`. `IMAGE_SIZE`'s members,
* which this `.cpp` defines, are with the class in `bitmap2cmp_panel.ts`.
*
* Two things a browser cannot do the C's way:
* - no directories: `m_mruPath` and the dialogs' start path are gone, and a
* file is its name;
* - a save is a download, so there is no file dialog to type a name into.
* The name offered is the source image's, with the format's extension
* (`EnsureFileExtension` / `SetExt`), where KiCad's dialog starts empty.
*/
import { COMMON_CONTROL } from '@ziroeda/common/tool/common_control.js';
import { ABOUT_TITLES } from '@ziroeda/common/eda_base_frame_about_titles.js';
import { KIWAY_PLAYER } from '@ziroeda/common/kiway_player.js';
import { unityScale } from '@ziroeda/common/eda_units.js';
import { FRAME_T } from '@ziroeda/common/frame_type.js';
import { TOOL_MANAGER } from '@ziroeda/common/tool/tool_manager.js';
import {
drawingSheetWildcard,
imageFileWildcard,
kicadFootprintFileWildcard,
kicadSymbolLibWildcard,
psFileWildcard,
} from '@ziroeda/common/wildcards_and_files_ext.js';
import type { ChooserFilter } from '@ziroeda/wx/filedlg.js';
import { BITMAP2CMP_CONTROL } from './bitmap2cmp_control.js';
import {
BITMAP2CMP_PANEL,
DROP_FILE,
type BITMAP2CMP_PANEL_UI,
type IMAGE_FILE,
} from './bitmap2cmp_panel.js';
import type { BITMAP2CMP_SETTINGS } from './bitmap2cmp_settings.js';
import {
DRAWING_SHEET_FMT,
FOOTPRINT_FMT,
POSTSCRIPT_FMT,
SYMBOL_FMT,
type OUTPUT_FMT_ID,
type STRING_BUFFER,
} from './bitmap2component.js';
/** The window's services: the panel's, plus the frame's own dialogs and bars. */
export interface BITMAP2CMP_FRAME_UI extends BITMAP2CMP_PANEL_UI {
/**
* `wxFileDialog( ..., wxFD_OPEN | wxFD_FILE_MUST_EXIST )`: the chosen image,
* read and decoded, or null for Cancel.
*/
ChooseImageFile(aTitle: string, aFilters: readonly ChooserFilter[]): Promise<IMAGE_FILE | null>;
/** Write `aText` as the file `aName` (a download); false when it could not be created. */
SaveFile(
aTitle: string,
aFilters: readonly ChooserFilter[],
aName: string,
aText: string,
): boolean;
/** `SetTitle`. */
SetTitle(aTitle: string): void;
/** `SetStatusText`, the one field of `CreateStatusBar( 1, ... )`. */
SetStatusText(aText: string): void;
/** `EDA_BASE_FRAME::UpdateFileHistory`: record the file under Open Recent. */
UpdateFileHistory(aFile: IMAGE_FILE): void;
/** `Close( false )`. */
Close(): void;
}
/** `wxFileName( aPath ).GetName()`: the name without its extension. */
function stem(aName: string): string {
const base = aName.slice(aName.lastIndexOf('/') + 1);
const dot = base.lastIndexOf('.');
return dot > 0 ? base.slice(0, dot) : base;
}
/** `wxFileName( aPath ).GetFullName()`. */
function fullName(aName: string): string {
return aName.slice(aName.lastIndexOf('/') + 1);
}
/** One export: the file dialog's title and wildcard, and the extension it forces. [data] */
interface EXPORT_SPEC {
title: string;
filters: () => readonly ChooserFilter[];
ext: string;
format: OUTPUT_FMT_ID;
}
const EXPORTS: Record<'wks' | 'ps' | 'sym' | 'mod', EXPORT_SPEC> = {
wks: {
title: 'Create Drawing Sheet File',
filters: () => [drawingSheetWildcard()],
ext: 'kicad_wks',
format: DRAWING_SHEET_FMT,
},
ps: {
title: 'Create PostScript File',
filters: () => [psFileWildcard()],
ext: 'ps',
format: POSTSCRIPT_FMT,
},
sym: {
title: 'Create Symbol Library',
filters: () => [kicadSymbolLibWildcard()],
ext: 'kicad_sym',
format: SYMBOL_FMT,
},
mod: {
title: 'Create Footprint Library',
filters: () => [kicadFootprintFileWildcard()],
ext: 'kicad_mod',
format: FOOTPRINT_FMT,
},
};
export class BITMAP2CMP_FRAME extends KIWAY_PLAYER {
private m_panel: BITMAP2CMP_PANEL;
private m_dropTarget: DROP_FILE;
private m_ui: BITMAP2CMP_FRAME_UI;
private m_config: BITMAP2CMP_SETTINGS;
private m_srcFileName = '';
private m_outFileName = '';
constructor(aUi: BITMAP2CMP_FRAME_UI, aConfig: BITMAP2CMP_SETTINGS) {
super(FRAME_T.FRAME_BM2CMP, unityScale, 'mm');
this.m_ui = aUi;
this.m_config = aConfig;
this.m_aboutTitle = ABOUT_TITLES.imageConverter;
this.m_panel = new BITMAP2CMP_PANEL(this, aUi);
this.m_dropTarget = new DROP_FILE(this.m_panel, aUi);
this.LoadSettings(this.config());
this.m_toolManager = new TOOL_MANAGER();
this.m_toolManager.SetEnvironment(null, null, null, this.config(), this);
// Register tools
this.m_toolManager.RegisterTool(new COMMON_CONTROL());
this.m_toolManager.RegisterTool(new BITMAP2CMP_CONTROL());
this.m_toolManager.InitTools();
}
override config(): BITMAP2CMP_SETTINGS {
return this.m_config;
}
GetPanel(): BITMAP2CMP_PANEL {
return this.m_panel;
}
/** The DROP_FILE the three notebook pages share. */
GetDropTarget(): DROP_FILE {
return this.m_dropTarget;
}
/** Event handler for the wxID_EXIT and wxID_CLOSE events. */
OnExit(): void {
// Just generate a wxCloseEvent
this.m_ui.Close();
}
override GetToolCanvas(): unknown {
return this.m_panel.GetCurrentPage();
}
/** `OnFileHistory`: an Open Recent row; `aFile` is its image. */
OnFileHistory(aFile: IMAGE_FILE | null): void {
if (aFile) {
this.OpenProjectFiles([aFile]);
this.m_ui.Refresh();
}
}
/** The window title: "<file> — Image Converter", or the bare frame name. */
GetTitle(): string {
let title = '';
if (this.m_srcFileName) title = `${fullName(this.m_srcFileName)} — `;
title += 'Image Converter';
return title;
}
UpdateTitle(): void {
this.m_ui.SetTitle(this.GetTitle());
}
override LoadSettings(aCfg: BITMAP2CMP_SETTINGS): void {
this.m_srcFileName = aCfg.m_BitmapFileName;
this.m_outFileName = aCfg.m_ConvertedFileName;
this.m_panel.LoadSettings(aCfg);
}
override SaveSettings(aCfg: BITMAP2CMP_SETTINGS): void {
aCfg.m_BitmapFileName = this.m_srcFileName;
aCfg.m_ConvertedFileName = this.m_outFileName;
this.m_panel.SaveSettings(aCfg);
}
/** Load Source Image, File > Open (`ACTIONS::open` through BITMAP2CMP_CONTROL). */
async OnLoadFile(): Promise<void> {
const file = await this.m_ui.ChooseImageFile('Choose Image', [imageFileWildcard()]);
if (!file) return;
if (!this.OpenProjectFiles([file])) return;
this.m_ui.SetStatusText(file.name);
this.UpdateTitle();
this.m_ui.Refresh();
}
OpenProjectFiles(aFileSet: IMAGE_FILE[]): boolean {
this.m_srcFileName = aFileSet[0]!.name;
if (this.m_panel.OpenProjectFiles(aFileSet)) {
this.m_ui.UpdateFileHistory(aFileSet[0]!);
return true;
}
return false;
}
private export(aSpec: EXPORT_SPEC): void {
const name = `${stem(this.m_srcFileName) || 'LOGO'}.${aSpec.ext}`;
this.m_outFileName = name;
const buffer: STRING_BUFFER = { value: '' };
this.m_panel.ExportToBuffer(buffer, aSpec.format);
if (!this.m_ui.SaveFile(aSpec.title, aSpec.filters(), name, buffer.value))
this.m_ui.MessageBox(`File '${name}' could not be created.`);
}
/** Generate a file suitable to be copied into a drawing sheet (.kicad_wks) file */
ExportDrawingSheetFormat(): void {
this.export(EXPORTS.wks);
}
/** Generate a postscript file */
ExportPostScriptFormat(): void {
this.export(EXPORTS.ps);
}
/** Generate a schematic library which contains one component: the logo */
ExportEeschemaFormat(): void {
this.export(EXPORTS.sym);
}
/** Generate a footprint in S expr format */
ExportPcbnewFormat(): void {
this.export(EXPORTS.mod);
}
}
+356
View File
@@ -0,0 +1,356 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* The Image Converter's window: the `wxFrame` half of `BITMAP2CMP_FRAME`
* (`bitmap2component/bitmap2cmp_frame.cpp`) - the menu bar
* `doReCreateMenuBar` builds, the status bar, the message boxes and the About
* dialog.
*
* What only the program has comes in as {@link BITMAP2CMP_APP}: upstream
* `Pgm()` (the settings manager, the language), `KIWAY` (the way home to the
* project manager) and the toolkit's own dialogs - the file dialog, which here
* is the account's file chooser, and Preferences. The Help menu and
* Preferences... run through COMMON_CONTROL on the frame's tool manager.
*/
import { type JSX, type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { MenuBar, type Menu, type MenuItem } from '@ziroeda/wx/menu_ui.js';
import { MessageDialogOk, MessageDialogYesNo } from '@ziroeda/common/dialogs/dialog_message.js';
import type { MessageDialogIcon, YesNoResult } from '@ziroeda/common/confirm_types.js';
import {
FileHistory,
MISSING_FILE_EXTENDED,
missingFileMessage,
openRecentMenuItem,
} from '@ziroeda/common/file_history.js';
import { useFileHistory } from '@ziroeda/common/use_file_history.js';
import { setLanguageMenuItem } from '@ziroeda/common/eda_base_frame_language_menu.js';
import { standardHelpMenu } from '@ziroeda/common/eda_base_frame_help_menu.js';
import { ShowAboutDialog } from '@ziroeda/common/dialog_about/AboutDialog_main.js';
import { KiStatusBar } from '@ziroeda/common/widgets/kistatusbar.js';
import { useMenuHotkeys } from '@ziroeda/common/tool/use_menu_hotkeys.js';
import { addQuit } from '@ziroeda/common/tool/action_menu.js';
import { ACTIONS } from '@ziroeda/common/tool/actions.js';
import { imageFileWildcard } from '@ziroeda/common/wildcards_and_files_ext.js';
import type { KIWAY } from '@ziroeda/common/kiway.js';
import type { ChooserFilter } from '@ziroeda/wx/filedlg.js';
import type { BITMAP2CMP_FRAME, BITMAP2CMP_FRAME_UI } from './bitmap2cmp_frame.js';
import { CreateKiWindow } from './bitmap2cmp_main.js';
import type { IMAGE_FILE } from './bitmap2cmp_panel.js';
import { Bitmap2cmpPanel, readImageFile } from './bitmap2cmp_panel_ui.js';
import { BITMAP2CMP_SETTINGS, type BITMAP2CMP_SETTINGS_JSON } from './bitmap2cmp_settings.js';
import './bitmap2cmp_panel.css';
import './bitmap2cmp_frame.css';
/** One Open Recent row: the name FILE_HISTORY shows, and the image to reload. */
export interface RecentImage {
name: string;
/** The image bytes as a data URL. */
data: string;
}
/**
* A data URL longer than this is not kept in the history: localStorage's quota
* is per origin, and one large image would push every other slice out.
*/
export const RECENT_MAX_DATA = 1_500_000;
/**
* What the Image Converter's window asks of the program it runs in.
*/
export interface BITMAP2CMP_APP {
/** The way back to the project manager, drawn at the left of the menu bar. */
homeLink: ReactNode;
/** `Pgm()`'s settings manager: `bitmap2component.json`, read and written. */
LoadSettings(): Partial<BITMAP2CMP_SETTINGS_JSON>;
SaveSettings(aJson: BITMAP2CMP_SETTINGS_JSON): void;
/** `COMMON_SETTINGS::m_System.file_history_size`. */
fileHistorySize: number;
/** `Pgm().GetLanguage` / `SetLanguage`, the Preferences menu's language list. */
language: string;
SetLanguage(aLabel: string): void;
/**
* The file dialog: the chosen files, or none. `aFallback` is run when the
* program has no picker to offer and a plain `<input type=file>` must ask.
*/
OpenFileDialog(aFilters: readonly ChooserFilter[], aFallback: () => void): Promise<File[]>;
/** The `accept` attribute for that fallback input. */
AcceptAttribute(aFilters: readonly ChooserFilter[]): string;
/** `EDA_BASE_FRAME::ShowPreferences( wxEmptyString, wxEmptyString )`: the dialog. */
Preferences(aOnClose: () => void): ReactNode;
/** `Kiway()`: what COMMON_CONTROL asks of the program - Quit, the other editors. */
kiway: KIWAY;
}
const bytesToDataUrl = (bytes: Uint8Array, type: string): string => {
let bin = '';
for (let i = 0; i < bytes.length; i += 0x8000)
bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
return `data:${type || 'image/png'};base64,${btoa(bin)}`;
};
/** A message box waiting for OK, or a question waiting for an answer. */
type Modal =
| { kind: 'ok'; message: string; caption?: string }
| {
kind: 'yesno';
message: string;
caption: string;
icon: MessageDialogIcon;
defaultButton: YesNoResult;
resolve: (r: YesNoResult) => void;
};
export function Bitmap2cmpFrameWindow({
app,
onExitToHome,
}: {
app: BITMAP2CMP_APP;
onExitToHome: () => void;
}): JSX.Element {
const fileInputRef = useRef<HTMLInputElement>(null);
/** The `<input>` fallback of the file dialog reports here. */
const pendingPick = useRef<((f: IMAGE_FILE | null) => void) | null>(null);
const [version, setVersion] = useState(0);
const [title, setTitle] = useState('Image Converter');
// KiCad's status bar starts empty and shows the loaded file (OnLoadFile).
const [status, setStatus] = useState('');
const [modals, setModals] = useState<Modal[]>([]);
const [aboutOpen, setAboutOpen] = useState(false);
const [prefsOpen, setPrefsOpen] = useState(false);
// BITMAP2CMP_FRAME's `m_fileHistory`, allocated once the way
// `EDA_BASE_FRAME::LoadSettings` (eda_base_frame.cpp:1282-1286) allocates it,
// from the user's `system.file_history_size`.
//
// It does not follow the account, and upstream is the reason:
// `SETTINGS_MANAGER::ResetToDefaults` (settings_manager.cpp:106-124) lifts the
// history out, resets the rest and puts it back - KiCad is drawing the line
// itself, the history is not one of the settings. Ours holds bytes rather
// than paths, up to RECENT_MAX_DATA a row; if recent images should ever
// follow the account they belong in the content-addressed blob store with
// hashes in the slice, not in a settings row.
const [recentImages] = useState(
() =>
new FileHistory<RecentImage>({
storageKey: 'ziroeda.bitmap2cmp.recent',
maxFiles: app.fileHistorySize,
}),
);
const recent = useFileHistory(recentImages);
/**
* The window's services, as BITMAP2CMP_FRAME / BITMAP2CMP_PANEL call them.
* Every one is a state setter or a stable ref, so the object is built once.
*/
const ui = useMemo<BITMAP2CMP_FRAME_UI>(
() => ({
MessageBox: (message, caption) => setModals((m) => [...m, { kind: 'ok', message, caption }]),
AskYesNo: (message, caption, icon, defaultButton) =>
new Promise<YesNoResult>((resolve) =>
setModals((m) => [
...m,
{ kind: 'yesno', message, caption, icon, defaultButton, resolve },
]),
),
SetClipboardText: async (text) => {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
return false;
}
},
Refresh: () => setVersion((v) => v + 1),
ChooseImageFile: async (_title, filters) => {
const files = await app.OpenFileDialog(filters, () => fileInputRef.current?.click());
if (files.length > 0) return readImageFile(files[0]!);
// The <input> fallback answers through its change handler; a cancel
// there is never reported, and the next pick replaces this one.
return new Promise<IMAGE_FILE | null>((resolve) => {
pendingPick.current = resolve;
});
},
SaveFile: (_title, _filters, name, text) => {
const url = URL.createObjectURL(new Blob([text], { type: 'text/plain' }));
const a = document.createElement('a');
a.href = url;
a.download = name;
a.click();
URL.revokeObjectURL(url);
return true;
},
SetTitle: setTitle,
SetStatusText: setStatus,
UpdateFileHistory: (file) => {
const data = bytesToDataUrl(file.bytes, '');
if (data.length <= RECENT_MAX_DATA)
recentImages.addFileToHistory({ name: file.name, data });
},
Close: onExitToHome,
}),
[onExitToHome, app, recentImages],
);
// bitmap2cmp_main.cpp's CreateKiWindow: the settings object, then the frame.
const [frame] = useState<BITMAP2CMP_FRAME>(() => CreateKiWindow(ui, app.LoadSettings()));
// What COMMON_CONTROL reaches through the frame: ShowPreferences, the About
// dialog, and the program's KIWAY.
useEffect(() => {
frame.SetPreferencesPresenter(() => setPrefsOpen(true));
frame.SetAboutPresenter(() => setAboutOpen(true));
frame.SetKiway(app.kiway);
return () => {
frame.SetPreferencesPresenter(null);
frame.SetAboutPresenter(null);
frame.SetKiway(null);
};
}, [frame, app.kiway]);
// SaveSettings: KiCad writes the settings once, from the frame destructor.
// A tab has no destructor, so every change is written; the slice ignores a
// save that changes nothing.
// biome-ignore lint/correctness/useExhaustiveDependencies: `version` is the trigger; the frame is read, not a dependency that changes
useEffect(() => {
const cfg = new BITMAP2CMP_SETTINGS();
frame.SaveSettings(cfg);
app.SaveSettings(cfg.ToJson());
}, [version]);
const onPick = (e: React.ChangeEvent<HTMLInputElement>): void => {
const f = e.target.files?.[0];
e.target.value = '';
const resolve = pendingPick.current;
pendingPick.current = null;
if (!resolve) return;
if (f) void readImageFile(f).then(resolve);
else resolve(null);
};
/**
* EDA_BASE_FRAME::GetFileFromHistory: a row whose file is gone gets the
* "File '%s' was not found." question and opens nothing whatever the answer.
* Our rows carry their own bytes, so "gone" means the data URL did not
* survive storage.
*/
const openRecent = useCallback(
async (index: number) => {
const r = recentImages.getFileFromHistory(index, {
exists: (e) => e.data.length > 0,
confirmRemove: (e) =>
window.confirm(`${missingFileMessage(e.name)}\n${MISSING_FILE_EXTENDED}`),
});
if (!r) return;
const blob = await (await fetch(r.data)).blob();
frame.OnFileHistory(await readImageFile(new File([blob], r.name, { type: blob.type })));
},
[frame, recentImages],
);
// doReCreateMenuBar: File (Open... / Open Recent / Quit), Preferences
// (Preferences... / language list), then the standard Help menu.
const openRecentItem: MenuItem = openRecentMenuItem({
files: recent,
onOpen: (i) => void openRecent(i),
onClear: () => recentImages.clearFileHistory(),
});
const menus: Menu[] = [
{
label: 'File',
items: [
// ACTIONS::open, which BITMAP2CMP_CONTROL::Open answers.
{
label: 'Open...',
shortcut: 'Ctrl+O',
action: () => frame.GetToolManager()?.RunAction(ACTIONS.open),
},
openRecentItem,
{ sep: true },
// `fileMenu->AddQuit( _( "Image Converter" ) )`: bitmap2component has
// no kiface of its own to close into, so it is always Quit.
addQuit('Image Converter', () => frame.OnExit()),
],
},
{
label: 'Preferences',
items: [
// ACTIONS::openPreferences, which COMMON_CONTROL::OpenPreferences answers.
{
label: 'Preferences...',
shortcut: 'Ctrl+,',
action: () => frame.GetToolManager()?.RunAction(ACTIONS.openPreferences),
},
{ sep: true },
setLanguageMenuItem({
current: app.language,
onSelect: (label) => app.SetLanguage(label),
}),
],
},
// AddStandardHelpMenu: ACTION_MENU( false, commonControl ).
standardHelpMenu({ RunAction: (a) => frame.GetToolManager()?.RunAction(a) }),
];
// The menus are the whole of this frame's keyboard: Ctrl+O, Ctrl+`,`,
// Ctrl+Alt+Q and Ctrl+F1 are dispatched from the rows that declare them.
useMenuHotkeys(menus, 'image');
const modal = modals[0];
const closeModal = (): void => setModals((m) => m.slice(1));
return (
<div className="imgc-frame ze-app">
<MenuBar menus={menus} leftSlot={app.homeLink} title={title} />
<input
ref={fileInputRef}
type="file"
accept={app.AcceptAttribute([imageFileWildcard()])}
style={{ display: 'none' }}
onChange={onPick}
/>
<Bitmap2cmpPanel
panel={frame.GetPanel()}
dropTarget={frame.GetDropTarget()}
version={version}
/>
{/* CreateStatusBar( 1, wxSTB_SIZEGRIP ) - one field, the loaded file. */}
<KiStatusBar>
<span className="cell grow">{status}</span>
</KiStatusBar>
{modal?.kind === 'ok' && (
<MessageDialogOk caption={modal.caption} message={modal.message} onClose={closeModal} />
)}
{modal?.kind === 'yesno' && (
<MessageDialogYesNo
caption={modal.caption}
message={modal.message}
icon={modal.icon}
defaultButton={modal.defaultButton}
onResult={(r) => {
modal.resolve(r);
closeModal();
}}
/>
)}
{prefsOpen && app.Preferences(() => setPrefsOpen(false))}
{/* ShowAboutDialog( this ), with the frame's m_aboutTitle. */}
{aboutOpen && (
<ShowAboutDialog title={frame.m_aboutTitle} onClose={() => setAboutOpen(false)} />
)}
</div>
);
}
+30
View File
@@ -0,0 +1,30 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `bitmap2component/bitmap2cmp_main.cpp`: the `BMP2CMP` KIFACE. What it does
* beyond DSO plumbing (`KIFACE_GETTER`, `OnKifaceStart`, `IfaceOrAddress`,
* which a page has no use for) is `CreateKiWindow`: make the settings object,
* then the frame over it.
*
* `RegisterSettings` hands the object to the settings manager so it is loaded
* from and saved to `bitmap2component.json`; here the window does that with
* the app's `bitmap2component` slice, so the caller passes the stored JSON in.
*/
import { BITMAP2CMP_FRAME, type BITMAP2CMP_FRAME_UI } from './bitmap2cmp_frame.js';
import { BITMAP2CMP_SETTINGS, type BITMAP2CMP_SETTINGS_JSON } from './bitmap2cmp_settings.js';
/** `kiface( "BMP2CMP", KIWAY::FACE_BMP2CMP )`. [data] */
export const BMP2CMP_KIFACE_NAME = 'BMP2CMP';
/**
* `IFACE::CreateKiWindow`: `InitSettings( new BITMAP2CMP_SETTINGS )`, loaded
* from `aStored`, then `new BITMAP2CMP_FRAME`.
*/
export function CreateKiWindow(
aUi: BITMAP2CMP_FRAME_UI,
aStored: Partial<BITMAP2CMP_SETTINGS_JSON>,
): BITMAP2CMP_FRAME {
const settings = new BITMAP2CMP_SETTINGS().FromJson(aStored);
return new BITMAP2CMP_FRAME(aUi, settings);
}
+437
View File
@@ -0,0 +1,437 @@
/* BITMAP2CMP_PANEL's window (bitmap2cmp_panel_ui.tsx).
Every control metric, font and colour in here comes from the shared GTK
control-theme tokens in common/widgets/shell.css - the same way wxWidgets
takes them from the GTK theme once and every KiCad launcher inherits the
identical result. Nothing below re-states a number that belongs to the
theme.
What IS stated below is the arrangement BITMAP2CMP_PANEL_BASE specifies for
this panel alone: which groups exist and in what order, the width of the
right column, where the stretch spacer goes, and the wxFormBuilder border on
each sizer item. Those cite bitmap2cmp_panel_base.cpp and belong to no other
editor. The frame around it (the window, its status bar) is
designer/src/editors/image/imageConverter.css. */
.imgc-body {
display: flex;
flex: 1;
min-height: 0;
}
/* --- left preview notebook --- */
/* bMainSizer->Add( m_Notebook, 1, wxEXPAND|wxBOTTOM|wxLEFT, 10 )
(bitmap2cmp_panel_base.cpp:30): the notebook is inset 10 px from the window's
left and bottom edges, with the window background showing through, and GTK
draws its own 1 px frame around it. */
.imgc-notebook {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
/* [data] wxBOTTOM|wxLEFT, 10 — bitmap2cmp_panel_base.cpp:30 writes 10,
not two --wx-border 5s, so it is upstream's number and stays. */
margin: 0 0 10px 10px;
border: 1px solid var(--ctl-border);
}
/* The wxNotebook tab strip. A GTK notebook draws no tab cards: the strip is
flat and the selected tab carries an accent bar in place of the strip's
bottom border, which is what the real bitmap2component window shows. */
.imgc-tabs {
display: flex;
gap: 0;
padding: 0;
height: var(--tab-strip-height);
flex: none;
background: var(--chrome-bg);
border-bottom: 1px solid var(--ctl-border);
}
.imgc-tab {
display: flex;
align-items: center;
padding: 0 var(--tab-pad-x);
cursor: default;
background: transparent;
border: none;
border-bottom: var(--tab-underline) solid transparent;
border-radius: 0;
color: inherit;
font: inherit;
/* The accent bar replaces the strip's own bottom border rather than stacking
under it: the tab hangs 1 px past the strip so its bottom edge lands on the
border row, exactly where KiCad's bar is. Any more than that and the next
element paints over it. */
margin-bottom: -1px;
}
.imgc-tab.active {
border-bottom-color: var(--chrome-active);
}
/* The notebook's three pages. BITMAP2CMP_PANEL_BASE builds three separate
wxScrolledWindows (bitmap2cmp_panel_base.cpp:21,24,27) and AddPage()s one
each, so every page keeps its own scroll position and switching tabs does not
move or reset the others. All three stay in the layout, stacked in one grid
cell, because a page removed from the box tree loses its scroll offset.
(SetScrollRate(5,5) only sets wx's scroll *unit*, the step a scrollbar click
moves by; a browser already scrolls by pixel, so there is nothing to port.) */
.imgc-pages {
flex: 1;
min-height: 0;
min-width: 0;
display: grid;
grid-template: 1fr / 1fr;
}
.imgc-view {
grid-area: 1 / 1;
min-width: 0;
min-height: 0;
overflow: auto;
/* KiCad's pages are plain flat scrolled windows, with no backdrop of their
own behind the bitmap. */
background: var(--panel-bg);
visibility: hidden;
}
.imgc-view.active {
visibility: visible;
}
/* wxDC::DrawBitmap( bmp, 0, 0 ) inside a scrolled window whose virtual size is
the image's own w x h (bitmap2cmp_panel.cpp:231-233): the preview is drawn
1:1 at the top-left and the user scrolls to the rest. Never scale it -- a
resampled 1-bit image greys out and drops single-pixel strokes, which reads
as a bad conversion when the traced geometry is exact. */
.imgc-canvas {
display: block;
image-rendering: pixelated;
}
/* --- right control column --- */
/* bMainSizer->Add( brightSizer, 0, wxEXPAND|wxALL, 5 ) plus the wxALL 5 that
every item inside brightSizer carries: 10 px from the column's edge to the
first group, and 10 px between any two items. Measured on the real window:
the column is 277 px of content and the group boxes inside it are 257 px. */
.imgc-side {
flex: none;
width: 277px;
overflow-y: auto;
padding: calc(2 * var(--wx-border));
background: var(--chrome-bg);
display: flex;
flex-direction: column;
gap: calc(2 * var(--wx-border));
}
/* A GTK frame: square, one hairline, and the label straddling the top edge at
its very left. The label is NOT bold - measuring ink density in the real
window put "Options" at 0.203 against "Negative" at 0.235, i.e. the same
weight - and the frame carries no padding of its own, because in wx every
child inside it brings its own wxFormBuilder border instead. */
.imgc-group {
border: 1px solid var(--ctl-border);
border-radius: 0;
padding: 0;
margin: 0;
min-inline-size: 0;
flex-shrink: 0;
display: flex;
flex-direction: column;
}
.imgc-group legend {
padding: 0;
margin-left: -1px;
font-weight: normal;
}
/* brightSizer->Add( 0, 0, 1, wxEXPAND ) (bitmap2cmp_panel_base.cpp:79) sits
between the Load Source Image button and the Output Size box, so all the
slack in the column opens up THERE and the four lower groups plus both export
buttons stay flush with the bottom edge. */
.imgc-spacer {
flex: 1 1 0;
}
/* The Output Format box is the column's other stretchy item
(bitmap2cmp_panel_base.cpp:198, proportion 1), so it shares the slack with
the spacer half and half; its radio buttons stay at the top of the box. */
.imgc-group.imgc-format {
flex-grow: 1;
justify-content: flex-start;
}
/* Image Information: a 4-column wxFlexGridSizer whose cells each carry a 5 px
border (bitmap2cmp_panel_base.cpp:47-88). One row is therefore one GtkLabel
tall with 5 px under it, which is the 23 px pitch the real window measures. */
.imgc-info {
display: grid;
grid-template-columns: auto 1fr 1fr auto;
padding: var(--wx-border);
gap: var(--wx-border);
align-items: center;
}
.imgc-info .k {
padding-right: var(--wx-border);
}
/* A wxFlexGridSizer cell is left-aligned; only wxALIGN_RIGHT would move it. */
.imgc-info .v {
text-align: left;
font-variant-numeric: tabular-nums;
}
/* Output Size row. bSizerRes: the label carries wxRIGHT|wxLEFT 5 and each of
the three controls wxRIGHT 5, and the sizer itself wxBOTTOM 5
(bitmap2cmp_panel_base.cpp:113-134). */
.imgc-sizerow {
display: flex;
align-items: center;
padding: 0 var(--wx-border) var(--wx-border);
gap: var(--wx-border);
}
.imgc-sizerow .lbl {
padding-left: var(--wx-border);
}
/* m_layerLabel is indented 28 px, not the usual 5
(bitmap2cmp_panel_base.cpp:177), so it hangs under the Footprint radio's
label rather than under its button. */
.imgc-layerrow {
display: flex;
align-items: center;
padding-left: 28px; /* [data] bitmap2cmp_panel_base.cpp:177 */
padding-right: var(--wx-border);
gap: var(--wx-border);
}
/* m_layerLabel->Enable( m_rbFootprint->GetValue() ) (bitmap2cmp_panel.cpp:571):
the label greys with its control. */
.imgc-layerrow.disabled .lbl {
color: var(--ctl-fg-disabled);
}
/* Text fields and combos are the same height as a button, which is what makes a
mixed row line up. m_UnitSizeX/Y SetMinSize( 60, -1 ) and m_PixelUnit
SetMinSize( 80, -1 ), all three at sizer proportion 0, so the row packs left
and the slack stays on the right.
These rules carry .imgc-panel, and the entries carry `ze-bare`, purely to get
out from under the shell's blanket entry rule: that one is deliberately built
at (0,5,1) and documents `ze-bare` as its opt-out. Without both, the shell
paints these fields --chrome-bg2 with a 3 px radius and the GTK field metrics
below never reach the screen. */
.imgc-panel .imgc-input {
background: var(--field-bg);
color: var(--chrome-fg);
border: 1px solid var(--ctl-border);
border-radius: var(--ctl-radius);
height: var(--ctl-height);
padding: 0 var(--field-pad-x);
font: inherit;
flex: none;
}
/* The three controls of the Output Size row, at the widths
bitmap2cmp_panel_base.cpp:112,118,126 give them. */
.imgc-sizerow .imgc-input {
width: 60px;
font-variant-numeric: tabular-nums;
}
/* The Layer and unit combos are the shared `Combo` (ui/Combo.tsx), and NOTHING
about how they look is restated here. They used to share `.imgc-input`'s rule,
which painted them the entry interior `--field-bg`; a combo is a GTK *button*
and takes `--ctl-face` (Yaru: `button { background-image: image(#373737) }`
against an entry's #282828, and a real bitmap2component samples rgb(55,55,55)
inside the Layer combo). Because the local rule was (0,2,0) it silently beat
`.ze-combo`'s (0,1,0), so fixing the widget centrally changed nothing here —
which is exactly why the look now lives in one place and this file keeps only
the LAYOUT bitmap2cmp_panel_base gives this panel: sizer proportion and the
SetMinSize widths. Layout is the panel's business; looks are the widget's. */
.imgc-panel .imgc-select {
flex: none;
}
.imgc-sizerow .imgc-select {
width: 80px;
}
/* Only an entry takes a focus ring, and at 70% alpha: Yaru gives
`entry:focus { border-color: rgba(239, 134, 97, 0.7) }` and gives `button` no
:focus rule at all. A combo is a button, so it is not listed here — the
keyboard rectangle it does get lives on `.ze-combo:focus-visible`. */
.imgc-panel .imgc-input:focus {
outline: 1px solid var(--field-focus-border);
}
/* m_layerCtrl is the one control here at sizer proportion 1. */
.imgc-panel .imgc-select.grow {
flex: 1;
width: auto;
}
/* GTK greys a disabled control by colour, not by fading the whole widget: the
background and border stay put and only the text changes. */
.imgc-panel .imgc-input:disabled {
color: var(--ctl-fg-disabled);
opacity: 1;
}
/* Options. The label carries wxRIGHT|wxLEFT 5, the slider
wxBOTTOM|wxLEFT|wxRIGHT 5 and the checkbox wxBOTTOM|wxRIGHT|wxLEFT 5
(bitmap2cmp_panel_base.cpp:144-156). */
.imgc-thresh-label {
padding: 0 var(--wx-border);
}
/* wxSL_LABELS (bitmap2cmp_panel_base.cpp:150): GTK draws the current value
centred ABOVE the thumb and the two range ends, 0 and 100, at the ends of the
track BELOW it, each on its own label line. --slider-thumb-size is the
browser's range thumb; the thumb centre travels only between half a thumb in
from each end, which is what the second term of the calc() corrects for. */
.imgc-slider {
/* [data] `wxBOTTOM|wxLEFT|wxRIGHT, 5` on the slider
(bitmap2cmp_panel_base.cpp:150); the padding is the shared rule's. */
margin-bottom: var(--wx-border);
}
/* The threshold slider is the shared wxSlider - see ui/Slider.tsx and the
`.ze-slider` rules in shell.css. Everything that used to stand here was a
copy of that control scoped to `.imgc-frame`, so no other launcher could
reach it; the colour picker asked for the same slider and got a bare range
input. Only the box AROUND it is this panel's, and that is above. */
/* GtkCheckButton / GtkRadioButton: a 22 px row with a 16 px indicator that
carries a 4 px margin either side. */
.imgc-check,
.imgc-radio {
display: flex;
align-items: center;
height: var(--check-row);
cursor: default;
}
.imgc-panel .imgc-check input,
.imgc-panel .imgc-radio input {
appearance: none;
flex: none;
width: var(--check-size);
height: var(--check-size);
margin: 0 var(--check-margin);
box-sizing: border-box;
background: var(--check-face);
border: 1px solid var(--ctl-border);
border-radius: var(--check-radius);
}
.imgc-panel .imgc-radio input {
border-radius: 50%;
}
.imgc-panel .imgc-check input:checked,
.imgc-panel .imgc-radio input:checked {
background: var(--chrome-active);
border-color: var(--chrome-active);
}
/* The check mark and the radio dot GTK draws inside the accent square. */
.imgc-panel .imgc-check input:checked::after {
content: "";
display: block;
/* [art] the tick's own geometry. GTK draws check-symbolic.svg here, so there
is no metric to copy — only the ink is shared, as --check-mark. */
width: 4px; /* [art] */
height: 8px; /* [art] */
margin: 1px auto 0; /* [art] */
border: solid var(--check-mark);
border-width: 0 2px 2px 0; /* [art] */
transform: rotate(45deg);
}
.imgc-panel .imgc-radio input:checked::after {
content: "";
display: block;
/* [art] as above, for bullet-symbolic.svg. */
width: 6px; /* [art] */
height: 6px; /* [art] */
margin: 4px auto; /* [art] */
border-radius: 50%;
background: var(--check-mark);
}
/* wxALL 5 on m_aspectRatioCheckbox; wxBOTTOM|wxRIGHT|wxLEFT 5 on
m_checkNegative (bitmap2cmp_panel_base.cpp:135,156). */
.imgc-group > .imgc-check {
margin: 0 var(--wx-border) var(--wx-border);
}
.imgc-sizerow + .imgc-check {
margin-top: var(--wx-border);
}
/* Output Format: wxFlexGridSizer( 5, 1, 2, 0 ), so a 2 px gap between rows, and
then the per-row wxFormBuilder borders on top of it
(bitmap2cmp_panel_base.cpp:161-193). Row 3 - the Layer row - is the one added
with no border at all. */
.imgc-formats {
display: flex;
flex-direction: column;
gap: 2px; /* [data] wxFlexGridSizer( 5, 1, 2, 0 ) — the vgap is upstream's */
padding: 0 var(--wx-border);
}
.imgc-formats > :nth-child(1) {
margin-bottom: var(--wx-border); /* wxBOTTOM|wxRIGHT, 5 */
}
.imgc-formats > :nth-child(2) {
margin-top: var(--wx-border); /* wxTOP|wxRIGHT, 5 */
}
.imgc-formats > :nth-child(4) {
margin: var(--wx-border) 0; /* wxTOP|wxBOTTOM|wxRIGHT, 5 */
}
.imgc-formats > :nth-child(5) {
margin-top: var(--wx-border); /* wxTOP|wxRIGHT, 5 */
}
/* Buttons */
.imgc-panel .imgc-btn {
background: var(--ctl-face);
color: var(--chrome-fg);
border: 1px solid var(--ctl-border);
border-radius: var(--ctl-radius);
height: var(--ctl-height);
padding: 0 var(--ctl-pad-x);
font: inherit;
cursor: default;
flex: none;
}
.imgc-panel .imgc-btn:hover:not(:disabled) {
background: var(--chrome-hover);
}
.imgc-btn.block {
width: 100%;
}
.imgc-panel .imgc-btn:disabled {
background: var(--ctl-face-disabled);
color: var(--ctl-fg-disabled);
cursor: default;
}
/* m_buttonExportClipboard is added wxBOTTOM|wxRIGHT|wxLEFT - no wxTOP - so it
sits 5 px under Export to File, half the column's usual 10
(bitmap2cmp_panel_base.cpp:205). */
.imgc-btn.block + .imgc-btn.block {
margin-top: calc(-1 * var(--wx-border));
}
+826
View File
@@ -0,0 +1,826 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `bitmap2component/bitmap2cmp_panel.cpp` + `.h`: `IMAGE_SIZE`,
* `BITMAP2CMP_PANEL` and `DROP_FILE` — the panel's behaviour, with no DOM.
* `bitmap2cmp_panel_ui.tsx` draws it (the `_base.cpp` layout and the three
* paint handlers).
*
* The wx controls the C++ reads and writes are fields here holding what the
* control holds: `m_UnitSizeX` is the text in the field, `m_PixelUnit` the
* selected index, and so on. A handler reads the field text, exactly as
* `OnSizeChangeX` reads `m_UnitSizeX->GetValue()`, which is why a value that
* only exists at the field's precision is what the export uses after, say,
* toggling the ratio lock.
*
* `IMAGE_SIZE`'s members are defined in `bitmap2cmp_frame.cpp`; the class is
* declared in this unit's header, so it lives here.
*/
import type { EdaUnits } from '@ziroeda/common/eda_units.js';
import { fixed } from '@ziroeda/common/plotters/fmt.js';
import { Reporter } from '@ziroeda/common/reporter.js';
import type { MessageDialogIcon, YesNoResult } from '@ziroeda/common/confirm_types.js';
import { KiROUND } from '@ziroeda/kimath/src/math/util.js';
import { BM_PUT, bm_new } from '@ziroeda/potrace';
import type { BITMAP2CMP_FRAME } from './bitmap2cmp_frame.js';
import type { BITMAP2CMP_SETTINGS } from './bitmap2cmp_settings.js';
import {
BITMAPCONV_INFO,
DRAWING_SHEET_FMT,
FOOTPRINT_FMT,
POSTSCRIPT_FMT,
SYMBOL_FMT,
SYMBOL_PASTE_FMT,
type OUTPUT_FMT_ID,
type STRING_BUFFER,
} from './bitmap2component.js';
import {
WX_IMAGE,
wxALPHA_OPAQUE,
wxBitmapDepth,
wxIMAGE_OPTION_RESOLUTIONUNIT,
wxIMAGE_OPTION_RESOLUTIONX,
wxIMAGE_OPTION_RESOLUTIONY,
wxImageResolution,
} from '@ziroeda/wx/wx_image.js';
import { wxStringToDouble } from '@ziroeda/wx/wxstring.js';
/** the image DPI used in formats that do not define a DPI [data] */
export const DEFAULT_DPI = 300;
const INT_MIN = -2147483648;
const INT_MAX = 2147483647;
/**
* `static_cast<int>( double )` on x86-64 (`cvttsd2si`): truncation, and the
* "integer indefinite" INT_MIN for NaN or anything out of range.
*/
function cvtInt(v: number): number {
return Number.isFinite(v) && v > INT_MIN - 1 && v < INT_MAX + 1 ? Math.trunc(v) + 0 : INT_MIN;
}
/**
* `KiROUND( v )` to an `int` (`math/util.h`): `std::llround` (LLONG_MIN for a
* NaN or an infinity on x86-64), clamped to the int range.
*/
function KiROUNDInt(v: number): number {
if (!Number.isFinite(v)) return INT_MIN;
return Math.min(INT_MAX, Math.max(INT_MIN, KiROUND(v)));
}
export class IMAGE_SIZE {
/** The units for m_outputSize (mm, inch, dpi) */
private m_unit: EdaUnits;
/**
* The size in m_unit of the output image, depending on the user settings.
* Set to the initial image size.
*/
private m_outputSize: number;
/** The image DPI if specified in file, or 0 if unknown */
private m_originalDPI: number;
/** The original image size read from file, in pixels */
private m_originalSizePixels: number;
constructor() {
this.m_outputSize = 0.0;
this.m_originalDPI = DEFAULT_DPI;
this.m_originalSizePixels = 0;
this.m_unit = 'mm';
}
/** The copy KiCad's value semantics make on every assignment. */
Clone(): IMAGE_SIZE {
const c = new IMAGE_SIZE();
c.m_unit = this.m_unit;
c.m_outputSize = this.m_outputSize;
c.m_originalDPI = this.m_originalDPI;
c.m_originalSizePixels = this.m_originalSizePixels;
return c;
}
/**
* Set the unit used for m_outputSize, and convert the old m_outputSize value
* to the value in new unit.
*/
SetUnit(aUnit: EdaUnits): void {
if (aUnit === this.m_unit) return;
// Convert m_outputSize to mm:
let size_mm: number;
if (this.m_unit === 'mm') {
size_mm = this.m_outputSize;
} else if (this.m_unit === 'in') {
size_mm = this.m_outputSize * 25.4;
} else {
// m_outputSize is the DPI, not an image size
// the image size is m_originalSizePixels / m_outputSize (in inches)
if (this.m_outputSize) size_mm = (this.m_originalSizePixels / this.m_outputSize) * 25.4;
else size_mm = 0;
}
// Convert m_outputSize to new value:
if (aUnit === 'mm') {
this.m_outputSize = size_mm;
} else if (aUnit === 'in') {
this.m_outputSize = size_mm / 25.4;
} else {
if (size_mm) this.m_outputSize = (this.m_originalSizePixels / size_mm) * 25.4;
else this.m_outputSize = 0;
}
this.m_unit = aUnit;
}
SetOriginalDPI(aDPI: number): void {
this.m_originalDPI = aDPI;
}
SetOriginalSizePixels(aPixels: number): void {
this.m_originalSizePixels = aPixels;
}
GetOriginalSizePixels(): number {
return this.m_originalSizePixels;
}
GetOutputSize(): number {
return this.m_outputSize;
}
SetOutputSize(aSize: number, aUnit: EdaUnits): void {
this.m_outputSize = aSize;
this.m_unit = aUnit;
}
/** Set the m_outputSize value from the m_originalSizePixels and the selected unit */
SetOutputSizeFromInitialImageSize(): void {
// Safety-check to guarantee no divide-by-zero
this.m_originalDPI = Math.max(1, this.m_originalDPI);
// Set the m_outputSize value from the m_originalSizePixels and the selected unit
if (this.m_unit === 'mm')
this.m_outputSize = (this.GetOriginalSizePixels() / this.m_originalDPI) * 25.4;
else if (this.m_unit === 'in')
this.m_outputSize = this.GetOriginalSizePixels() / this.m_originalDPI;
else this.m_outputSize = this.m_originalDPI;
}
/**
* @return the pixels per inch value to build the output image. It is used by
* potrace to build the polygonal image. An `int`: the division truncates.
*/
GetOutputDPI(): number {
let outputDPI: number;
if (this.m_unit === 'mm')
outputDPI = cvtInt(this.GetOriginalSizePixels() / (this.m_outputSize / 25.4));
else if (this.m_unit === 'in')
outputDPI = cvtInt(this.GetOriginalSizePixels() / this.m_outputSize);
else outputDPI = KiROUNDInt(this.m_outputSize);
// Zero is not a DPI, and may cause divide-by-zero errors...
outputDPI = Math.max(1, outputDPI);
return outputDPI;
}
}
/** `m_PixelUnit`'s choices, appended in the constructor. [data] */
export const PIXEL_UNIT_CHOICES = ['mm', 'Inch', 'DPI'] as const;
/** `m_layerCtrl`'s choices (`bitmap2cmp_panel_base.cpp`). [data] */
export const LAYER_CHOICES = [
'F.Cu',
'F.Silkscreen',
'F.Mask',
'User.Drawings',
'User.Comments',
'User.Eco1',
'User.Eco2',
'F.Fab',
] as const;
/** The notebook pages, in `AddPage` order. [data] */
export const NOTEBOOK_PAGES = [
'Original Picture',
'Greyscale Picture',
'Black && White Picture',
] as const;
/**
* The wx services the panel calls as globals: `wxMessageBox`,
* `KICAD_MESSAGE_DIALOG::ShowModal`, `wxTheClipboard`. The frame's window
* supplies them.
*/
export interface BITMAP2CMP_PANEL_UI {
/** `wxMessageBox( aMessage, aCaption )`; the caption defaults to "Message". */
MessageBox(aMessage: string, aCaption?: string): void;
/** A modal yes/no question; resolves with the button pressed. */
AskYesNo(
aMessage: string,
aCaption: string,
aIcon: MessageDialogIcon,
aDefault: YesNoResult,
): Promise<YesNoResult>;
/** `wxTheClipboard->Open()` .. `SetData( wxTextDataObject )` .. `Close()`: false when it cannot open. */
SetClipboardText(aText: string): Promise<boolean>;
/** `Refresh()`: the panel's controls changed. */
Refresh(): void;
}
/** A file handed to `OpenProjectFiles`: its name and its bytes, which wxImage::LoadFile reads. */
export interface IMAGE_FILE {
/** The full name, as the file chooser or the drop gives it. */
name: string;
/** The file's bytes. */
bytes: Uint8Array;
}
export class BITMAP2CMP_PANEL {
private m_parentFrame: BITMAP2CMP_FRAME;
private m_ui: BITMAP2CMP_PANEL_UI;
/* ---- the controls (BITMAP2CMP_PANEL_BASE), as the values they hold ---- */
/** `m_Notebook`: the selected page; "Black && White Picture" is added selected. */
m_NotebookSelection = 2;
/** `m_SizeXValue`, `m_SizeYValue`, `m_InputXValueDPI`, `m_InputYValueDPI`, `m_BPPValue`: "0000" until an image loads. */
m_SizeXValue = '0000';
m_SizeYValue = '0000';
m_InputXValueDPI = '0000';
m_InputYValueDPI = '0000';
m_BPPValue = '0000';
/** `m_UnitSizeX`, `m_UnitSizeY`: the field text. The base class starts both at "300". */
m_UnitSizeX = '300';
m_UnitSizeY = '300';
/** `m_PixelUnit`: the selected index (mm, Inch, DPI). */
m_PixelUnit = 0;
/** `m_aspectRatioCheckbox`. */
m_aspectRatioCheckbox = false;
/** `m_sliderThreshold`: 0 .. 100, 50 in the base class. */
m_sliderThreshold = 50;
readonly m_sliderThresholdMax = 100;
/** `m_checkNegative`. */
m_checkNegative = false;
/** `m_rbSymbol`, `m_rbFootprint`, `m_rbPostscript`, `m_rbWorksheet`: the first is checked in a fresh group. */
m_rbSymbol = true;
m_rbFootprint = false;
m_rbPostscript = false;
m_rbWorksheet = false;
/** `m_layerLabel->Enable()` / `m_layerCtrl->Enable()`. */
m_layerEnabled = true;
/** `m_layerCtrl`: the selected index. */
m_layerCtrl = 0;
/** `m_buttonExportFile->Enable()` / `m_buttonExportClipboard->Enable()`. */
m_buttonExportFileEnabled = true;
m_buttonExportClipboardEnabled = true;
/* ---- BITMAP2CMP_PANEL's own members ---- */
m_Pict_Image: WX_IMAGE | null = null;
/** `m_Pict_Bitmap`: the image, and its depth as `wxBitmap` reports it. */
m_Pict_Bitmap: { image: WX_IMAGE; depth: number } | null = null;
m_Greyscale_Image: WX_IMAGE | null = null;
m_Greyscale_Bitmap: WX_IMAGE | null = null;
m_NB_Image: WX_IMAGE | null = null;
m_BN_Bitmap: WX_IMAGE | null = null;
private m_outputSizeX = new IMAGE_SIZE();
private m_outputSizeY = new IMAGE_SIZE();
private m_negative: boolean;
private m_aspectRatio: number;
constructor(aParent: BITMAP2CMP_FRAME, aUi: BITMAP2CMP_PANEL_UI) {
this.m_parentFrame = aParent;
this.m_ui = aUi;
this.m_negative = false;
this.m_aspectRatio = 1.0;
// for( const wxString& unit : { _( "mm" ), _( "Inch" ), _( "DPI" ) } ) m_PixelUnit->Append( unit );
this.m_outputSizeX.SetUnit(this.getUnitFromSelection());
this.m_outputSizeY.SetUnit(this.getUnitFromSelection());
this.m_outputSizeX.SetOutputSize(0, this.getUnitFromSelection());
this.m_outputSizeY.SetOutputSize(0, this.getUnitFromSelection());
this.m_UnitSizeX = this.formatOutputSize(this.m_outputSizeX.GetOutputSize());
this.m_UnitSizeY = this.formatOutputSize(this.m_outputSizeY.GetOutputSize());
this.m_buttonExportFileEnabled = false;
this.m_buttonExportClipboardEnabled = false;
}
GetCurrentPage(): number {
return this.m_NotebookSelection;
}
LoadSettings(cfg: BITMAP2CMP_SETTINGS): void {
if (cfg.m_Units >= 0 && cfg.m_Units < PIXEL_UNIT_CHOICES.length) this.m_PixelUnit = cfg.m_Units;
this.m_sliderThreshold = Math.min(this.m_sliderThresholdMax, Math.max(0, cfg.m_Threshold));
this.m_negative = cfg.m_Negative;
this.m_checkNegative = cfg.m_Negative;
this.m_aspectRatio = 1.0;
this.m_aspectRatioCheckbox = true;
this.m_rbSymbol = this.m_rbFootprint = this.m_rbPostscript = this.m_rbWorksheet = false;
switch (cfg.m_LastFormat) {
case SYMBOL_FMT:
case SYMBOL_PASTE_FMT:
this.m_rbSymbol = true;
break;
case POSTSCRIPT_FMT:
this.m_rbPostscript = true;
break;
case DRAWING_SHEET_FMT:
this.m_rbWorksheet = true;
break;
default: // FOOTPRINT_FMT
this.m_rbFootprint = true;
break;
}
this.m_layerEnabled = cfg.m_LastFormat === FOOTPRINT_FMT;
if (cfg.m_LastLayer >= 0 && cfg.m_LastLayer < LAYER_CHOICES.length)
this.m_layerCtrl = cfg.m_LastLayer;
}
SaveSettings(cfg: BITMAP2CMP_SETTINGS): void {
cfg.m_Threshold = this.m_sliderThreshold;
cfg.m_Negative = this.m_checkNegative;
cfg.m_LastFormat = this.getOutputFormat();
cfg.m_LastLayer = this.m_layerCtrl;
cfg.m_Units = this.m_PixelUnit;
}
/** `OnLoadFile`: the Load Source Image button. */
OnLoadFile(): void {
void this.m_parentFrame.OnLoadFile();
}
/**
* `OpenProjectFiles( aFileSet )`: load the first file, fill in the image
* information, build the greyscale and black & white images.
*/
OpenProjectFiles(aFileSet: IMAGE_FILE[]): boolean {
this.m_Pict_Image = null;
const file = aFileSet[0]!;
const image = new WX_IMAGE();
if (!image.LoadFile(file.bytes)) {
// LoadFile has its own UI, no need for further failure notification here
this.m_ui.MessageBox(
`Unknown image data format.\nFailed to load image from file "${file.name}".`,
'Error',
);
return false;
}
this.m_Pict_Image = image;
this.m_Pict_Bitmap = { image, depth: wxBitmapDepth(image) };
// Determine image resolution in DPI (does not existing in all formats).
// the resolution can be given in bit per inches or bit per cm in file
let imageDPIx = image.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONX);
let imageDPIy = image.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONY);
if (imageDPIx > 1 && imageDPIy > 1) {
if (
image.GetOptionInt(wxIMAGE_OPTION_RESOLUTIONUNIT) ===
wxImageResolution.wxIMAGE_RESOLUTION_CM
) {
imageDPIx = KiROUNDInt(imageDPIx * 2.54);
imageDPIy = KiROUNDInt(imageDPIy * 2.54);
}
} else {
// fallback to a default value (DEFAULT_DPI)
imageDPIx = imageDPIy = DEFAULT_DPI;
}
this.m_InputXValueDPI = String(imageDPIx);
this.m_InputYValueDPI = String(imageDPIy);
const h = image.GetHeight();
const w = image.GetWidth();
this.m_aspectRatio = w / h;
this.m_outputSizeX.SetOriginalDPI(imageDPIx);
this.m_outputSizeX.SetOriginalSizePixels(w);
this.m_outputSizeY.SetOriginalDPI(imageDPIy);
this.m_outputSizeY.SetOriginalSizePixels(h);
// Update display to keep aspect ratio
this.OnSizeChangeX();
this.updateImageInfo();
this.m_Greyscale_Image = image.ConvertToGreyscale();
if (image.HasMask()) {
for (let x = 0; x < w; x++) {
for (let y = 0; y < h; y++) {
if (
image.GetRed(x, y) === image.GetMaskRed() &&
image.GetGreen(x, y) === image.GetMaskGreen() &&
image.GetBlue(x, y) === image.GetMaskBlue()
) {
this.m_Greyscale_Image.SetRGB(x, y, 255, 255, 255);
}
}
}
}
if (this.m_negative) this.negateGreyscaleImage();
this.m_Greyscale_Bitmap = this.m_Greyscale_Image.Copy();
this.m_NB_Image = this.m_Greyscale_Image.Copy();
this.binarize(this.m_sliderThreshold / this.m_sliderThresholdMax);
this.m_buttonExportFileEnabled = true;
this.m_buttonExportClipboardEnabled = true;
this.m_outputSizeX.SetOutputSizeFromInitialImageSize();
this.m_UnitSizeX = this.formatOutputSize(this.m_outputSizeX.GetOutputSize());
this.m_outputSizeY.SetOutputSizeFromInitialImageSize();
this.m_UnitSizeY = this.formatOutputSize(this.m_outputSizeY.GetOutputSize());
return true;
}
GetOutputSizeX(): IMAGE_SIZE {
return this.m_outputSizeX.Clone();
}
GetOutputSizeY(): IMAGE_SIZE {
return this.m_outputSizeY.Clone();
}
SetOutputSize(aSizeX: IMAGE_SIZE, aSizeY: IMAGE_SIZE): void {
this.m_outputSizeX = aSizeX.Clone();
this.m_outputSizeY = aSizeY.Clone();
this.updateImageInfo();
this.m_UnitSizeX = this.formatOutputSize(this.m_outputSizeX.GetOutputSize());
this.m_UnitSizeY = this.formatOutputSize(this.m_outputSizeY.GetOutputSize());
}
/** return a string giving the output size, according to the selected unit */
formatOutputSize(aSize: number): string {
if (this.getUnitFromSelection() === 'mm') return fixed(aSize, 1);
else if (this.getUnitFromSelection() === 'in') return fixed(aSize, 2);
else return String(KiROUNDInt(aSize));
}
private updateImageInfo(): void {
// Note: the image resolution text controls are not modified here, to avoid a race between
// text change when entered by user and a text change if it is modified here.
if (this.m_Pict_Bitmap) {
this.m_SizeXValue = String(this.m_Pict_Bitmap.image.GetWidth());
this.m_SizeYValue = String(this.m_Pict_Bitmap.image.GetHeight());
this.m_BPPValue = String(this.m_Pict_Bitmap.depth);
}
}
/** @return the EDA_UNITS from the m_PixelUnit choice */
getUnitFromSelection(): EdaUnits {
switch (this.m_PixelUnit) {
case 1:
return 'in';
case 2:
return 'unscaled';
default:
return 'mm';
}
}
/** `m_UnitSizeX`'s wxEVT_COMMAND_TEXT_UPDATED: the user typed `aText`. */
SetUnitSizeXText(aText: string): void {
this.m_UnitSizeX = aText;
this.OnSizeChangeX();
this.m_ui.Refresh();
}
/** `m_UnitSizeY`'s wxEVT_COMMAND_TEXT_UPDATED. */
SetUnitSizeYText(aText: string): void {
this.m_UnitSizeY = aText;
this.OnSizeChangeY();
this.m_ui.Refresh();
}
OnSizeChangeX(): void {
const new_size = wxStringToDouble(this.m_UnitSizeX);
if (new_size !== null) {
if (this.m_aspectRatioCheckbox) {
let calculatedY = new_size / this.m_aspectRatio;
if (this.getUnitFromSelection() === 'unscaled') {
// for units in DPI, keeping aspect ratio cannot use m_AspectRatioLocked.
// just re-scale the other dpi
const ratio = new_size / this.m_outputSizeX.GetOutputSize();
calculatedY = this.m_outputSizeY.GetOutputSize() * ratio;
}
this.m_outputSizeY.SetOutputSize(calculatedY, this.getUnitFromSelection());
this.m_UnitSizeY = this.formatOutputSize(this.m_outputSizeY.GetOutputSize());
}
this.m_outputSizeX.SetOutputSize(new_size, this.getUnitFromSelection());
}
this.updateImageInfo();
}
OnSizeChangeY(): void {
const new_size = wxStringToDouble(this.m_UnitSizeY);
if (new_size !== null) {
if (this.m_aspectRatioCheckbox) {
let calculatedX = new_size * this.m_aspectRatio;
if (this.getUnitFromSelection() === 'unscaled') {
// for units in DPI, keeping aspect ratio cannot use m_AspectRatioLocked.
// just re-scale the other dpi
const ratio = new_size / this.m_outputSizeX.GetOutputSize();
calculatedX = this.m_outputSizeX.GetOutputSize() * ratio;
}
this.m_outputSizeX.SetOutputSize(calculatedX, this.getUnitFromSelection());
this.m_UnitSizeX = this.formatOutputSize(this.m_outputSizeX.GetOutputSize());
}
this.m_outputSizeY.SetOutputSize(new_size, this.getUnitFromSelection());
}
this.updateImageInfo();
}
/** `m_PixelUnit`'s wxEVT_COMMAND_CHOICE_SELECTED. */
OnSizeUnitChange(aSelection: number): void {
this.m_PixelUnit = aSelection;
this.m_outputSizeX.SetUnit(this.getUnitFromSelection());
this.m_outputSizeY.SetUnit(this.getUnitFromSelection());
this.updateImageInfo();
this.m_UnitSizeX = this.formatOutputSize(this.m_outputSizeX.GetOutputSize());
this.m_UnitSizeY = this.formatOutputSize(this.m_outputSizeY.GetOutputSize());
this.m_ui.Refresh();
}
/** `m_aspectRatioCheckbox`'s wxEVT_COMMAND_CHECKBOX_CLICKED. */
ToggleAspectRatioLock(aChecked: boolean): void {
this.m_aspectRatioCheckbox = aChecked;
if (this.m_aspectRatioCheckbox) {
// Force display update when aspect ratio is locked
this.OnSizeChangeX();
}
this.m_ui.Refresh();
}
/** aThreshold = 0.0 (black level) to 1.0 (white level) */
private binarize(aThreshold: number): void {
const grey = this.m_Greyscale_Image;
const nb = this.m_NB_Image;
if (!grey || !nb) return;
// unsigned char threshold = aThreshold * 255; unsigned char alpha_thresh = 0.7 * threshold;
const threshold = Math.trunc(aThreshold * 255);
const alpha_thresh = Math.trunc(0.7 * threshold);
for (let y = 0; y < grey.GetHeight(); y++) {
for (let x = 0; x < grey.GetWidth(); x++) {
let pixel = grey.GetGreen(x, y);
const alpha = grey.HasAlpha() ? grey.GetAlpha(x, y) : wxALPHA_OPAQUE;
if (pixel < threshold && alpha > alpha_thresh) pixel = 0;
else pixel = 255;
nb.SetRGB(x, y, pixel, pixel, pixel);
}
}
this.m_BN_Bitmap = nb.Copy();
}
private negateGreyscaleImage(): void {
const grey = this.m_Greyscale_Image;
if (!grey) return;
for (let y = 0; y < grey.GetHeight(); y++) {
for (let x = 0; x < grey.GetWidth(); x++) {
const pixel = ~grey.GetGreen(x, y) & 0xff;
grey.SetRGB(x, y, pixel, pixel, pixel);
}
}
}
/** `m_checkNegative`'s wxEVT_COMMAND_CHECKBOX_CLICKED. */
OnNegativeClicked(aChecked: boolean): void {
this.m_checkNegative = aChecked;
if (this.m_checkNegative !== this.m_negative) {
this.negateGreyscaleImage();
this.m_Greyscale_Bitmap = this.m_Greyscale_Image ? this.m_Greyscale_Image.Copy() : null;
this.binarize(this.m_sliderThreshold / this.m_sliderThresholdMax);
this.m_negative = this.m_checkNegative;
}
this.m_ui.Refresh();
}
/** `m_sliderThreshold`'s wxEVT_SCROLL_CHANGED / wxEVT_SCROLL_THUMBTRACK. */
OnThresholdChange(aValue: number): void {
this.m_sliderThreshold = aValue;
this.binarize(this.m_sliderThreshold / this.m_sliderThresholdMax);
this.m_ui.Refresh();
}
/** The Export to File... button. */
OnExportToFile(): void {
switch (this.getOutputFormat()) {
case SYMBOL_FMT:
case SYMBOL_PASTE_FMT:
void this.m_parentFrame.ExportEeschemaFormat();
break;
case FOOTPRINT_FMT:
void this.m_parentFrame.ExportPcbnewFormat();
break;
case POSTSCRIPT_FMT:
void this.m_parentFrame.ExportPostScriptFormat();
break;
case DRAWING_SHEET_FMT:
void this.m_parentFrame.ExportDrawingSheetFormat();
break;
}
}
getOutputFormat(): OUTPUT_FMT_ID {
if (this.m_rbSymbol) return SYMBOL_FMT;
else if (this.m_rbPostscript) return POSTSCRIPT_FMT;
else if (this.m_rbWorksheet) return DRAWING_SHEET_FMT;
else return FOOTPRINT_FMT;
}
/** The Export to Clipboard button. */
async OnExportToClipboard(): Promise<void> {
const buffer: STRING_BUFFER = { value: '' };
const format =
this.getOutputFormat() === SYMBOL_FMT ? SYMBOL_PASTE_FMT : this.getOutputFormat();
this.ExportToBuffer(buffer, format);
// Write buffer to the clipboard
if (!(await this.m_ui.SetClipboardText(buffer.value)))
this.m_ui.MessageBox('Unable to export to the Clipboard');
}
/**
* generate a export data of the current bitmap.
* @param aOutput is a string buffer to fill with data
* @param aFormat is the format to generate
*/
ExportToBuffer(aOutput: STRING_BUFFER, aFormat: OUTPUT_FMT_ID): void {
const nb = this.m_NB_Image;
const w = nb ? nb.GetWidth() : 0;
const h = nb ? nb.GetHeight() : 0;
// Create a potrace bitmap
const potrace_bitmap = bm_new(w, h);
if (!potrace_bitmap) {
this.m_ui.MessageBox('Error allocating memory for potrace bitmap');
return;
}
/* fill the bitmap with data */
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const pixel = nb!.GetGreen(x, y);
BM_PUT(potrace_bitmap, x, y, pixel ? 0 : 1);
}
}
let layer = 'F.SilkS';
if (aFormat === FOOTPRINT_FMT) {
switch (this.m_layerCtrl) {
case 0:
layer = 'F.Cu';
break;
case 1:
layer = 'F.SilkS';
break;
case 2:
layer = 'F.Mask';
break;
case 3:
layer = 'Dwgs.User';
break;
case 4:
layer = 'Cmts.User';
break;
case 5:
layer = 'Eco1.User';
break;
case 6:
layer = 'Eco2.User';
break;
case 7:
layer = 'F.Fab';
break;
}
}
const reporter = new Reporter();
const converter = new BITMAPCONV_INFO(aOutput, reporter);
converter.ConvertBitmap(
potrace_bitmap,
aFormat,
this.m_outputSizeX.GetOutputDPI(),
this.m_outputSizeY.GetOutputDPI(),
layer,
);
if (reporter.hasMessage())
this.m_ui.MessageBox(reporter.lines.map((l) => l.message).join('\n'), 'Errors');
}
/** A radio button's wxEVT_COMMAND_RADIOBUTTON_SELECTED: `aFormat`'s button was chosen. */
SelectFormat(aFormat: OUTPUT_FMT_ID): void {
this.m_rbSymbol = aFormat === SYMBOL_FMT;
this.m_rbFootprint = aFormat === FOOTPRINT_FMT;
this.m_rbPostscript = aFormat === POSTSCRIPT_FMT;
this.m_rbWorksheet = aFormat === DRAWING_SHEET_FMT;
this.OnFormatChange();
this.m_ui.Refresh();
}
private OnFormatChange(): void {
this.m_layerEnabled = this.m_rbFootprint;
}
/** `m_layerCtrl`'s selection. */
SetLayerSelection(aIndex: number): void {
this.m_layerCtrl = aIndex;
this.m_ui.Refresh();
}
/** `m_Notebook`'s page selection (the notebook has no handler of its own). */
SetNotebookSelection(aPage: number): void {
this.m_NotebookSelection = aPage;
this.m_ui.Refresh();
}
}
/** `DROP_FILE`'s question. [data] */
export const REPLACE_LOADED_FILE_CAPTION = 'Replace Loaded File?';
export const REPLACE_LOADED_FILE_MESSAGE =
'There is already a file loaded. Do you want to replace it?';
/**
* `DROP_FILE`: the drop target on each of the three notebook pages. Asks
* before replacing a loaded image (`wxYES_NO | wxICON_QUESTION |
* wxYES_DEFAULT`), then opens the dropped files.
*/
export class DROP_FILE {
private m_panel: BITMAP2CMP_PANEL;
private m_ui: BITMAP2CMP_PANEL_UI;
constructor(panel: BITMAP2CMP_PANEL, aUi: BITMAP2CMP_PANEL_UI) {
this.m_panel = panel;
this.m_ui = aUi;
}
async OnDropFiles(filenames: IMAGE_FILE[]): Promise<boolean> {
// If a file is already loaded
if (this.m_panel.GetOutputSizeX().GetOriginalSizePixels() !== 0) {
const replace = await this.m_ui.AskYesNo(
REPLACE_LOADED_FILE_MESSAGE,
REPLACE_LOADED_FILE_CAPTION,
'question',
'yes',
);
if (replace === 'no') return false;
}
/* m_panel->OpenProjectFiles( fNameVec ): the panel's, not the frame's, so
* a dropped file is neither the frame's m_srcFileName nor in its history. */
this.m_panel.OpenProjectFiles(filenames);
this.m_ui.Refresh();
return true;
}
}
+311
View File
@@ -0,0 +1,311 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `BITMAP2CMP_PANEL`'s window: `bitmap2cmp_panel_base.cpp` (wxFormBuilder)
* and the three `OnPaint*` handlers of `bitmap2cmp_panel.cpp`. Everything it
* shows is a field of the `BITMAP2CMP_PANEL` it is given, and every control
* calls that panel's handler; nothing is decided here.
*
* Its stylesheet is `bitmap2cmp_panel.css`, which the window that hosts it
* imports (the package does not compile CSS).
*/
import { CheckBox, RadioButton, TextCtrl } from '@ziroeda/wx/controls.js';
import { Fragment, type JSX, useEffect, useRef } from 'react';
import { Slider } from '@ziroeda/common/widgets/slider.js';
import { Combo } from '@ziroeda/wx/combobox.js';
import {
LAYER_CHOICES,
NOTEBOOK_PAGES,
PIXEL_UNIT_CHOICES,
type BITMAP2CMP_PANEL,
type DROP_FILE,
type IMAGE_FILE,
} from './bitmap2cmp_panel.js';
import {
DRAWING_SHEET_FMT,
FOOTPRINT_FMT,
POSTSCRIPT_FMT,
SYMBOL_FMT,
type OUTPUT_FMT_ID,
} from './bitmap2component.js';
import type { WX_IMAGE } from '@ziroeda/wx/wx_image.js';
/** The Output Format radios, in `fgSizer2` order, with the Layer row after Footprint. [data] */
const FORMATS: { id: OUTPUT_FMT_ID; label: string }[] = [
{ id: SYMBOL_FMT, label: 'Symbol (.kicad_sym file)' },
{ id: FOOTPRINT_FMT, label: 'Footprint (.kicad_mod file)' },
{ id: POSTSCRIPT_FMT, label: 'Postscript (.ps file)' },
{ id: DRAWING_SHEET_FMT, label: 'Drawing Sheet (.kicad_wks file)' },
];
/** `m_sliderThreshold->SetToolTip(...)`. [data] */
const THRESHOLD_TOOLTIP =
'Adjust the level to convert the greyscale picture to a black and white picture.';
/**
* Read a file the browser hands over (the file dialog or a drop) into what
* `OpenProjectFiles` takes: its name and its bytes, which wxImage::LoadFile decodes.
*/
export async function readImageFile(aFile: Blob & { name: string }): Promise<IMAGE_FILE> {
return { name: aFile.name, bytes: new Uint8Array(await aFile.arrayBuffer()) };
}
/**
* A page's wxEVT_PAINT handler: `PrepareDC` then `DrawBitmap( bmp, 0, 0,
* !!bmp.GetMask() )`. The canvas is sized to the bitmap itself, never to the
* pane, so the preview is 1:1 and the pane scrolls. A masked pixel, and an
* alpha one, show the page through.
*/
function paintPage(cv: HTMLCanvasElement | null, bmp: WX_IMAGE | null): void {
if (!cv || !bmp || !bmp.IsOk()) return;
const w = bmp.GetWidth();
const h = bmp.GetHeight();
const data = new ImageData(w, h);
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const i = (y * w + x) * 4;
const r = bmp.GetRed(x, y);
const g = bmp.GetGreen(x, y);
const b = bmp.GetBlue(x, y);
const masked =
bmp.HasMask() &&
r === bmp.GetMaskRed() &&
g === bmp.GetMaskGreen() &&
b === bmp.GetMaskBlue();
data.data[i] = r;
data.data[i + 1] = g;
data.data[i + 2] = b;
data.data[i + 3] = masked ? 0 : bmp.HasAlpha() ? bmp.GetAlpha(x, y) : 255;
}
}
cv.width = data.width;
cv.height = data.height;
cv.getContext('2d')?.putImageData(data, 0, 0);
}
export interface Bitmap2cmpPanelProps {
panel: BITMAP2CMP_PANEL;
/** The DROP_FILE installed on all three pages. */
dropTarget: DROP_FILE;
/** Bumped by the panel's `Refresh()`, so this re-renders. */
version: number;
}
export function Bitmap2cmpPanel({ panel, dropTarget, version }: Bitmap2cmpPanelProps): JSX.Element {
// One canvas per notebook page, mirroring the three wxScrolledWindows and
// the three bitmaps (m_Pict_Bitmap / m_Greyscale_Bitmap / m_BN_Bitmap) that
// BITMAP2CMP_PANEL keeps alive at once. Each page then scrolls on its own.
const originalCanvasRef = useRef<HTMLCanvasElement>(null);
const greyscaleCanvasRef = useRef<HTMLCanvasElement>(null);
const bwCanvasRef = useRef<HTMLCanvasElement>(null);
const pict = panel.m_Pict_Bitmap?.image ?? null;
const greyscale = panel.m_Greyscale_Bitmap;
const bw = panel.m_BN_Bitmap;
// OnPaintInit / OnPaintGreyscale / OnPaintBW each draw their own bitmap at
// (0, 0) into their own page; a threshold change rebuilds only m_BN_Bitmap,
// a Negative click m_Greyscale_Bitmap and m_BN_Bitmap. `version` is not read:
// the bitmaps are the dependencies, and a handler replaces the object when
// it rebuilds one.
useEffect(() => {
paintPage(originalCanvasRef.current, pict);
}, [pict]);
useEffect(() => {
paintPage(greyscaleCanvasRef.current, greyscale);
}, [greyscale]);
useEffect(() => {
paintPage(bwCanvasRef.current, bw);
}, [bw]);
const onDrop = (e: React.DragEvent): void => {
e.preventDefault();
const files = [...(e.dataTransfer.files ?? [])];
if (files.length === 0) return;
void (async () => {
const read = await Promise.all(files.map((f) => readImageFile(f)));
await dropTarget.OnDropFiles(read);
})();
};
const loaded = pict !== null;
const canvases = [originalCanvasRef, greyscaleCanvasRef, bwCanvasRef];
return (
<div className="imgc-body imgc-panel" data-version={version}>
{/* bMainSizer: the notebook, then brightSizer */}
<div className="imgc-notebook">
{/* The notebook has no page-change handler at all
(bitmap2cmp_panel_base.cpp connects paint, buttons, fields and
radios - never the notebook), so a tab click only selects a page. */}
<div className="imgc-tabs" role="tablist">
{NOTEBOOK_PAGES.map((label, i) => (
<button
key={label}
type="button"
role="tab"
aria-selected={panel.m_NotebookSelection === i}
className={`imgc-tab${panel.m_NotebookSelection === i ? ' active' : ''}`}
onClick={() => panel.SetNotebookSelection(i)}
>
{/* wx's mnemonic escape: "&&" is a literal "&" */}
{label.replaceAll('&&', '&')}
</button>
))}
</div>
<div className="imgc-pages" onDragOver={(e) => e.preventDefault()} onDrop={onDrop}>
{/* All three pages stay mounted, as AddPage() keeps all three
wxScrolledWindows alive; only the selected one is visible, and
each holds its own scroll offset across a tab switch. Before a
file is loaded they are blank: KiCad paints no placeholder. */}
{canvases.map((ref, i) => (
<div
key={NOTEBOOK_PAGES[i]}
className={`imgc-view${panel.m_NotebookSelection === i ? ' active' : ''}`}
>
{loaded && <canvas ref={ref} className="imgc-canvas" />}
</div>
))}
</div>
</div>
{/* brightSizer, group by group */}
<div className="imgc-side">
<fieldset className="imgc-group">
<legend>Image Information</legend>
<div className="imgc-info">
<span className="k">Image size:</span>
<span className="v">{panel.m_SizeXValue}</span>
<span className="v">{panel.m_SizeYValue}</span>
<span className="u">pixels</span>
<span className="k">Image PPI:</span>
<span className="v">{panel.m_InputXValueDPI}</span>
<span className="v">{panel.m_InputYValueDPI}</span>
<span className="u">PPI</span>
{/* Three cells then fgSizerInfo->Add( 0, 0, ... ), so "bits" is
in column 3 and the empty cell trails it. */}
<span className="k">BPP:</span>
<span className="v">{panel.m_BPPValue}</span>
<span className="u">bits</span>
<span />
</div>
</fieldset>
<button type="button" className="imgc-btn block" onClick={() => panel.OnLoadFile()}>
Load Source Image
</button>
{/* brightSizer->Add( 0, 0, 1, wxEXPAND ) */}
<div className="imgc-spacer" />
<fieldset className="imgc-group">
<legend>Output Size</legend>
<div className="imgc-sizerow">
<span className="lbl">Size:</span>
<TextCtrl
value={panel.m_UnitSizeX}
onChange={(aValue) => panel.SetUnitSizeXText(aValue)}
className="imgc-input ze-bare"
/>
<TextCtrl
value={panel.m_UnitSizeY}
onChange={(aValue) => panel.SetUnitSizeYText(aValue)}
className="imgc-input ze-bare"
/>
<Combo
className="imgc-select"
value={String(panel.m_PixelUnit)}
onChange={(v) => panel.OnSizeUnitChange(Number(v))}
options={PIXEL_UNIT_CHOICES.map((label, i) => ({ value: String(i), label }))}
/>
</div>
<CheckBox
label="Lock height / width ratio"
checked={panel.m_aspectRatioCheckbox}
className="imgc-check"
onChange={(aChecked) => panel.ToggleAspectRatioLock(aChecked)}
/>
</fieldset>
<fieldset className="imgc-group">
<legend>Options</legend>
<span className="imgc-thresh-label">Black / white threshold:</span>
<Slider
className="imgc-slider"
min={0}
max={panel.m_sliderThresholdMax}
labels
value={panel.m_sliderThreshold}
title={THRESHOLD_TOOLTIP}
onChange={(v) => panel.OnThresholdChange(v)}
/>
<CheckBox
label="Negative"
checked={panel.m_checkNegative}
className="imgc-check"
onChange={(aChecked) => panel.OnNegativeClicked(aChecked)}
/>
</fieldset>
<fieldset className="imgc-group imgc-format">
<legend>Output Format</legend>
{/* fgSizer2 is a wxFlexGridSizer( 5, 1, 2, 0 ): five sibling rows,
the Layer row third. They must stay siblings, because each row's
wxFormBuilder border differs and the stylesheet addresses them
by position. */}
<div className="imgc-formats">
{FORMATS.map((f) => (
<Fragment key={f.id}>
<RadioButton
label={f.label}
name="imgc-format"
checked={panel.getOutputFormat() === f.id}
className="imgc-radio"
onChange={() => panel.SelectFormat(f.id)}
/>
{f.id === FOOTPRINT_FMT && (
<div className={`imgc-layerrow${panel.m_layerEnabled ? '' : ' disabled'}`}>
<span className="lbl">Layer:</span>
<Combo
className="imgc-select grow"
value={String(panel.m_layerCtrl)}
disabled={!panel.m_layerEnabled}
onChange={(v) => panel.SetLayerSelection(Number(v))}
options={LAYER_CHOICES.map((label, i) => ({ value: String(i), label }))}
/>
</div>
)}
</Fragment>
))}
</div>
</fieldset>
<button
type="button"
className="imgc-btn block"
onClick={() => panel.OnExportToFile()}
disabled={!panel.m_buttonExportFileEnabled}
>
Export to File...
</button>
<button
type="button"
className="imgc-btn block"
onClick={() => void panel.OnExportToClipboard()}
disabled={!panel.m_buttonExportClipboardEnabled}
>
Export to Clipboard
</button>
</div>
</div>
);
}
+109
View File
@@ -0,0 +1,109 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `bitmap2component/bitmap2cmp_settings.h` + `.cpp`: `BITMAP2CMP_SETTINGS`,
* the Image Converter's app settings (`bitmap2component.json`).
*
* As `gerbview/gerbview_settings.ts` is, this is the in-memory object the
* frame and panel read. The JSON side is the app's `bitmap2component` slice
* (`designer/src/prefs/settings.ts`), keyed by the PARAM paths below; the
* frame builds one of these from it (`FromJson`) and writes it back
* (`ToJson`), as the PARAMs load and store it.
*
* `MigrateFromLegacy` reads a KiCad 5 wxConfig, which a browser has never had:
* n/a. The schema migration 0 → 1 is ported (`migrateLastModLayer`) for the
* same file KiCad would migrate, a version-0 `bitmap2component.json`.
*/
import { APP_SETTINGS_BASE } from '@ziroeda/common/settings/app_settings.js';
/** "Update the schema version whenever a migration is required" [data] */
export const bitmap2cmpSchemaVersion = 1;
/** The JSON shape the seven PARAMs read and write. */
export interface BITMAP2CMP_SETTINGS_JSON {
bitmap_file_name: string;
converted_file_name: string;
units: number;
threshold: number;
negative: boolean;
last_format: number;
last_mod_layer: number;
}
export class BITMAP2CMP_SETTINGS extends APP_SETTINGS_BASE {
/** `bitmap_file_name`, "". */
m_BitmapFileName = '';
/** `converted_file_name`, "". */
m_ConvertedFileName = '';
/** `units`, 0. */
m_Units = 0;
/** `threshold`, 50. */
m_Threshold = 50;
/** `negative`, false. */
m_Negative = false;
/** `last_format`, 0 (`SYMBOL_FMT`). */
m_LastFormat = 0;
/** `last_mod_layer`, 0. */
m_LastLayer = 0;
constructor() {
super('bitmap2component', bitmap2cmpSchemaVersion);
}
/** `getLegacyFrameName()`: the KiCad 5 wxConfig prefix. [data] */
getLegacyFrameName(): string {
return 'Bmconverter_';
}
/** The PARAMs' load: each member from its JSON path, its default when absent. */
FromJson(aJson: Partial<BITMAP2CMP_SETTINGS_JSON>): this {
const d = new BITMAP2CMP_SETTINGS();
this.m_BitmapFileName = aJson.bitmap_file_name ?? d.m_BitmapFileName;
this.m_ConvertedFileName = aJson.converted_file_name ?? d.m_ConvertedFileName;
this.m_Units = aJson.units ?? d.m_Units;
this.m_Threshold = aJson.threshold ?? d.m_Threshold;
this.m_Negative = aJson.negative ?? d.m_Negative;
this.m_LastFormat = aJson.last_format ?? d.m_LastFormat;
this.m_LastLayer = aJson.last_mod_layer ?? d.m_LastLayer;
return this;
}
/** The PARAMs' store. */
ToJson(): BITMAP2CMP_SETTINGS_JSON {
return {
bitmap_file_name: this.m_BitmapFileName,
converted_file_name: this.m_ConvertedFileName,
units: this.m_Units,
threshold: this.m_Threshold,
negative: this.m_Negative,
last_format: this.m_LastFormat,
last_mod_layer: this.m_LastLayer,
};
}
}
/**
* `registerMigration( 0, 1, ... )`: "Version 1 introduced a new layer (F.Cu),
* and changed the ordering to be consistent with PCBNew." The old
* `last_mod_layer` in, the new one out; an unknown value is `default: case 0`.
*/
export function migrateLastModLayer(aOld: number): number {
switch (aOld) {
case 1:
return 2;
case 2:
return 7;
case 3:
return 3;
case 4:
return 4;
case 5:
return 5;
case 6:
return 6;
default:
return 1;
}
}
+514
View File
@@ -0,0 +1,514 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `bitmap2component/bitmap2component.cpp` + `.h`: `BITMAPCONV_INFO`, which
* traces a 1-bit bitmap with potrace and writes the result as a symbol
* library, a footprint, a PostScript file or a drawing sheet — byte for byte
* the text KiCad writes, bar two things:
*
* - `(generator ...)` / `(generator_version ...)` name us, not
* `bitmap2component` / KiCad's version (`common/generator.ts` says why);
* - the uuids are fresh, as `KIID()` makes them.
*
* The file-format versions are KiCad's own frozen ones, `(version 20221018)`
* for the footprint, `20220914` for the symbol library and `20220228` for the
* drawing sheet: bitmap2component hardcodes them, and pcbnew, eeschema and
* pl_editor all read that dialect.
*/
import { SHAPE_POLY_SET } from '@ziroeda/kimath/src/geometry/shape_poly_set.js';
import type { SHAPE_LINE_CHAIN } from '@ziroeda/kimath/src/geometry/shape_line_chain.js';
import { KiROUND, toInt } from '@ziroeda/kimath/src/math/util.js';
import { PCB_IU_PER_MM, PL_IU_PER_MM, SCH_IU_PER_MM } from '@ziroeda/common/eda_units.js';
import { GENERATOR, GENERATOR_VERSION } from '@ziroeda/common/generator.js';
import { newKiid } from '@ziroeda/common/kiid.js';
import { fixed, formatG, shortest } from '@ziroeda/common/plotters/fmt.js';
import { RPT_SEVERITY_ERROR, type Reporter } from '@ziroeda/common/reporter.js';
import {
POTRACE_CORNER,
POTRACE_CURVETO,
POTRACE_STATUS_OK,
bm_free,
potrace_param_default,
potrace_param_free,
potrace_state_free,
potrace_trace,
type potrace_bitmap_t,
type potrace_dpoint_t,
type potrace_path_t,
} from '@ziroeda/potrace';
export enum OUTPUT_FMT_ID {
SYMBOL_FMT,
/** This does not include the header information */
SYMBOL_PASTE_FMT,
FOOTPRINT_FMT,
POSTSCRIPT_FMT,
DRAWING_SHEET_FMT,
}
export const { SYMBOL_FMT, SYMBOL_PASTE_FMT, FOOTPRINT_FMT, POSTSCRIPT_FMT, DRAWING_SHEET_FMT } =
OUTPUT_FMT_ID;
/** `std::string&`: the caller's buffer, which the converter appends to. */
export interface STRING_BUFFER {
value: string;
}
/**
* `strerror( errno )` after a failed allocation, the only way either
* potracelib call can fail here. [data: glibc's ENOMEM text]
*/
const ENOMEM_TEXT = 'Cannot allocate memory';
/** "The polygon outline thickness is fixed here to 0.01 ( 0.0 is the default thickness)" [data] */
const SCH_LINE_THICKNESS_MM = 0.01;
/**
* Helper class to handle useful info to convert a bitmap image to a polygonal
* object description.
*/
export class BITMAPCONV_INFO {
/** File format */
private m_Format: OUTPUT_FMT_ID;
private m_PixmapWidth: number;
/** the bitmap size in pixels */
private m_PixmapHeight: number;
private m_ScaleX: number;
/** the conversion scale */
private m_ScaleY: number;
/** the list of paths, from potrace (list of lines and bezier curves) */
private m_Paths: potrace_path_t | null;
/** The string used as cmp/footprint name */
private m_CmpName: string;
/** the buffer containing the conversion */
private m_Data: STRING_BUFFER;
private m_reporter: Reporter;
constructor(aData: STRING_BUFFER, aReporter: Reporter) {
this.m_Data = aData;
this.m_reporter = aReporter;
this.m_Format = POSTSCRIPT_FMT;
this.m_PixmapWidth = 0;
this.m_PixmapHeight = 0;
this.m_ScaleX = 1.0;
this.m_ScaleY = 1.0;
this.m_Paths = null;
this.m_CmpName = 'LOGO';
}
/**
* Run the conversion of the bitmap.
*/
ConvertBitmap(
aPotrace_bitmap: potrace_bitmap_t,
aFormat: OUTPUT_FMT_ID,
aDpi_X: number,
aDpi_Y: number,
aLayer: string,
): number {
// set tracing parameters, starting from defaults
const param = potrace_param_default();
if (!param) {
this.m_reporter.report(`Error allocating parameters: ${ENOMEM_TEXT}\n`, RPT_SEVERITY_ERROR);
return 1;
}
// For parameters: see http://potrace.sourceforge.net/potracelib.pdf
param.turdsize = 0; // area (in pixels) of largest path to be ignored. Potrace default is 2
param.opttolerance = 0.2; // curve optimization tolerance. Potrace default is 0.2
// convert the bitmap to curves
const st = potrace_trace(param, aPotrace_bitmap);
if (!st || st.status !== POTRACE_STATUS_OK) {
if (st) potrace_state_free(st);
potrace_param_free(param);
this.m_reporter.report(`Error tracing bitmap: ${ENOMEM_TEXT}\n`, RPT_SEVERITY_ERROR);
return 1;
}
this.m_PixmapWidth = aPotrace_bitmap.w;
this.m_PixmapHeight = aPotrace_bitmap.h; // the bitmap size in pixels
this.m_Paths = st.plist;
this.m_Format = aFormat;
switch (aFormat) {
case DRAWING_SHEET_FMT:
this.m_ScaleX = (PL_IU_PER_MM * 25.4) / aDpi_X; // the conversion scale from PPI to micron
this.m_ScaleY = (PL_IU_PER_MM * 25.4) / aDpi_Y; // Y axis is top to bottom
this.createOutputData();
break;
case POSTSCRIPT_FMT:
this.m_ScaleX = 1.0; // the conversion scale
this.m_ScaleY = this.m_ScaleX;
this.createOutputData();
break;
case SYMBOL_FMT:
case SYMBOL_PASTE_FMT:
this.m_ScaleX = (SCH_IU_PER_MM * 25.4) / aDpi_X; // the conversion scale from PPI to eeschema iu
this.m_ScaleY = (-SCH_IU_PER_MM * 25.4) / aDpi_Y; // Y axis is bottom to Top for components in libs
this.createOutputData();
break;
case FOOTPRINT_FMT:
this.m_ScaleX = (PCB_IU_PER_MM * 25.4) / aDpi_X; // the conversion scale from PPI to IU
this.m_ScaleY = (PCB_IU_PER_MM * 25.4) / aDpi_Y; // Y axis is top to bottom in Footprint Editor
this.createOutputData(aLayer);
break;
}
bm_free(aPotrace_bitmap);
potrace_state_free(st);
potrace_param_free(param);
return 0;
}
/**
* Function outputDataHeader: write to file the header depending on file format.
*/
private outputDataHeader(aBrdLayerName: string): void {
let Ypos = (this.m_PixmapHeight / 2.0) * this.m_ScaleY; // fields Y position in mm
let fieldSize: number; // fields text size in mm
switch (this.m_Format) {
case POSTSCRIPT_FMT:
this.m_Data.value += '%!PS-Adobe-3.0 EPSF-3.0\n';
this.m_Data.value += `%%BoundingBox: 0 0 ${this.m_PixmapWidth} ${this.m_PixmapHeight}\n`;
this.m_Data.value += 'gsave\n';
break;
case FOOTPRINT_FMT:
// fields text size = 1.5 mm
// fields text thickness = 1.5 / 5 = 0.3mm
this.m_Data.value +=
`(footprint "${this.m_CmpName}" (version 20221018) (generator "${GENERATOR}") (generator_version "${GENERATOR_VERSION}")\n` +
' (layer "F.Cu")\n';
this.m_Data.value += ' (attr board_only exclude_from_pos_files exclude_from_bom)\n';
this.m_Data.value +=
` (fp_text reference "G***" (at 0 0) (layer "${aBrdLayerName}")\n` +
' (effects (font (size 1.5 1.5) (thickness 0.3)))\n' +
` (uuid ${newKiid()})\n )\n`;
this.m_Data.value +=
` (fp_text value "${this.m_CmpName}" (at 0.75 0) (layer "${aBrdLayerName}") hide\n` +
' (effects (font (size 1.5 1.5) (thickness 0.3)))\n' +
` (uuid ${newKiid()})\n )\n`;
break;
case DRAWING_SHEET_FMT:
this.m_Data.value += `(kicad_wks (version 20220228) (generator "${GENERATOR}") (generator_version "${GENERATOR_VERSION}")\n`;
this.m_Data.value += ' (setup (textsize 1.5 1.5)(linewidth 0.15)(textlinewidth 0.15)\n';
this.m_Data.value +=
' (left_margin 10)(right_margin 10)(top_margin 10)(bottom_margin 10))\n';
this.m_Data.value += ' (polygon (name "") (pos 0 0) (linewidth 0.01)\n';
break;
case SYMBOL_FMT:
case SYMBOL_PASTE_FMT:
if (this.m_Format === SYMBOL_FMT)
this.m_Data.value += `(kicad_symbol_lib (version 20220914) (generator "${GENERATOR}") (generator_version "${GENERATOR_VERSION}")\n`;
// KI_FALLTHROUGH
fieldSize = 1.27; // fields text size in mm (= 50 mils)
Ypos /= SCH_IU_PER_MM;
Ypos += fieldSize / 2;
this.m_Data.value += ` (symbol "${this.m_CmpName}" (pin_names (offset 1.016)) (in_bom yes) (on_board yes)\n`;
this.m_Data.value +=
` (property "Reference" "#G" (at 0 ${formatG(-Ypos)} 0)\n` +
` (effects (font (size ${formatG(fieldSize)} ${formatG(fieldSize)})) hide)\n )\n`;
this.m_Data.value +=
` (property "Value" "${this.m_CmpName}" (at 0 ${formatG(Ypos)} 0)\n` +
` (effects (font (size ${formatG(fieldSize)} ${formatG(fieldSize)})) hide)\n )\n`;
this.m_Data.value +=
' (property "Footprint" "" (at 0 0 0)\n' +
` (effects (font (size ${formatG(fieldSize)} ${formatG(fieldSize)})) hide)\n )\n`;
this.m_Data.value +=
' (property "Datasheet" "" (at 0 0 0)\n' +
` (effects (font (size ${formatG(fieldSize)} ${formatG(fieldSize)})) hide)\n )\n`;
this.m_Data.value += ` (symbol "${this.m_CmpName}_0_0"\n`;
break;
}
}
/**
* Function outputDataEnd: write to file the last strings depending on file format.
*/
private outputDataEnd(): void {
switch (this.m_Format) {
case POSTSCRIPT_FMT:
this.m_Data.value += 'grestore\n';
this.m_Data.value += '%%EOF\n';
break;
case FOOTPRINT_FMT:
this.m_Data.value += ')\n';
break;
case DRAWING_SHEET_FMT:
this.m_Data.value += ' )\n)\n';
break;
case SYMBOL_PASTE_FMT:
this.m_Data.value += ' )\n'; // end symbol_0_0
this.m_Data.value += ' )\n'; // end symbol
break;
case SYMBOL_FMT:
this.m_Data.value += ' )\n'; // end symbol_0_0
this.m_Data.value += ' )\n'; // end symbol
this.m_Data.value += ')\n'; // end lib
break;
}
}
/**
* Function outputOnePolygon: write one polygon to output file. Polygon
* coordinates are expected scaled by the polygon extraction function.
*/
private outputOnePolygon(aPolygon: SHAPE_LINE_CHAIN, aBrdLayerName: string): void {
// write one polygon to output file.
// coordinates are expected in target unit.
let ii: number;
let jj: number;
let currpoint: { x: number; y: number };
const offsetX = KiROUND((this.m_PixmapWidth / 2.0) * this.m_ScaleX);
let offsetY = KiROUND((this.m_PixmapHeight / 2.0) * this.m_ScaleY);
const startpoint = aPolygon.CPoint(0);
switch (this.m_Format) {
case POSTSCRIPT_FMT:
offsetY = toInt(this.m_PixmapHeight * this.m_ScaleY);
this.m_Data.value += `newpath\n${startpoint.x} ${offsetY - startpoint.y} moveto\n`;
jj = 0;
for (ii = 1; ii < aPolygon.PointCount(); ii++) {
currpoint = aPolygon.CPoint(ii);
this.m_Data.value += ` ${currpoint.x} ${offsetY - currpoint.y} lineto`;
if (jj++ > 6) {
jj = 0;
this.m_Data.value += '\n';
}
}
this.m_Data.value += '\nclosepath fill\n';
break;
case FOOTPRINT_FMT:
this.m_Data.value += ' (fp_poly\n (pts\n';
for (ii = 0; ii < aPolygon.PointCount(); ii++) {
currpoint = aPolygon.CPoint(ii);
this.m_Data.value += ` (xy ${shortest((currpoint.x - offsetX) / PCB_IU_PER_MM)} ${shortest((currpoint.y - offsetY) / PCB_IU_PER_MM)})\n`;
}
// No need to close polygon
this.m_Data.value += ' )\n\n';
this.m_Data.value += ` (stroke (width ${fixed(0.0, 6)}) (type solid)) (fill solid) (layer "${aBrdLayerName}") (uuid ${newKiid()}))\n`;
break;
case DRAWING_SHEET_FMT:
this.m_Data.value += ' (pts';
// Internal units = micron, file unit = mm
jj = 1;
for (ii = 0; ii < aPolygon.PointCount(); ii++) {
currpoint = aPolygon.CPoint(ii);
this.m_Data.value += ` (xy ${fixed((currpoint.x - offsetX) / PL_IU_PER_MM, 3)} ${fixed((currpoint.y - offsetY) / PL_IU_PER_MM, 3)})`;
if (jj++ > 4) {
jj = 0;
this.m_Data.value += '\n ';
}
}
// Close polygon
this.m_Data.value += ` (xy ${fixed((startpoint.x - offsetX) / PL_IU_PER_MM, 3)} ${fixed((startpoint.y - offsetY) / PL_IU_PER_MM, 3)}) )\n`;
break;
case SYMBOL_FMT:
case SYMBOL_PASTE_FMT:
this.m_Data.value += ' (polyline\n (pts\n';
for (ii = 0; ii < aPolygon.PointCount(); ii++) {
currpoint = aPolygon.CPoint(ii);
this.m_Data.value += ` (xy ${fixed((currpoint.x - offsetX) / SCH_IU_PER_MM, 6)} ${fixed((currpoint.y - offsetY) / SCH_IU_PER_MM, 6)})\n`;
}
// Close polygon
this.m_Data.value += ` (xy ${fixed((startpoint.x - offsetX) / SCH_IU_PER_MM, 6)} ${fixed((startpoint.y - offsetY) / SCH_IU_PER_MM, 6)})\n`;
this.m_Data.value += ' )\n'; // end pts
this.m_Data.value +=
` (stroke (width ${formatG(SCH_LINE_THICKNESS_MM)}) (type default))\n` +
' (fill (type outline))\n';
this.m_Data.value += ' )\n'; // end polyline
break;
}
}
/**
* Creates the data specified by m_Format.
*/
private createOutputData(aLayer = 'F.SilkS'): void {
const cornersBuffer: potrace_dpoint_t[] = [];
// polyset_areas is a set of polygon to draw
const polyset_areas = new SHAPE_POLY_SET();
// polyset_holes is the set of holes inside polyset_areas outlines
const polyset_holes = new SHAPE_POLY_SET();
/* The layer name has meaning only for .kicad_mod files. For these files the
* header creates 2 invisible texts: value and ref (needed but not useful) on
* silk screen layer */
this.outputDataHeader('F.SilkS');
let main_outline = true;
/* draw each as a polygon with no hole. Bezier curves are approximated by a
* polyline */
let paths = this.m_Paths; // the list of paths
if (!this.m_Paths) {
this.m_reporter.report(
'No shape in black and white image to convert: no outline created.',
RPT_SEVERITY_ERROR,
);
}
while (paths !== null) {
const cnt = paths.curve.n;
const tag = paths.curve.tag;
const c = paths.curve.c;
let startpoint = c[cnt - 1]![2]!;
for (let i = 0; i < cnt; i++) {
switch (tag[i]) {
case POTRACE_CORNER:
cornersBuffer.push(c[i]![1]!);
cornersBuffer.push(c[i]![2]!);
startpoint = c[i]![2]!;
break;
case POTRACE_CURVETO:
BezierToPolyline(cornersBuffer, startpoint, c[i]![0]!, c[i]![1]!, c[i]![2]!);
startpoint = c[i]![2]!;
break;
}
}
// Store current path
if (main_outline) {
main_outline = false;
// build the current main polygon
polyset_areas.NewOutline();
for (const pt of cornersBuffer)
polyset_areas.Append(toInt(pt.x * this.m_ScaleX), toInt(pt.y * this.m_ScaleY));
} else {
// Add current hole in polyset_holes
polyset_holes.NewOutline();
for (const pt of cornersBuffer)
polyset_holes.Append(toInt(pt.x * this.m_ScaleX), toInt(pt.y * this.m_ScaleY));
}
cornersBuffer.length = 0;
// at the end of a group of a positive path and its negative children, fill.
if (paths.next === null || paths.next.sign === '+') {
polyset_areas.Simplify();
polyset_holes.Simplify();
polyset_areas.BooleanSubtract(polyset_holes);
// Ensure there are no self intersecting polygons
if (polyset_areas.NormalizeAreaOutlines()) {
// Convert polygon with holes to a unique polygon
polyset_areas.Fracture();
// Output current resulting polygon(s)
for (let ii = 0; ii < polyset_areas.OutlineCount(); ii++) {
const poly = polyset_areas.Outline(ii);
this.outputOnePolygon(poly, aLayer);
}
polyset_areas.RemoveAllContours();
polyset_holes.RemoveAllContours();
main_outline = true;
}
}
paths = paths.next;
}
this.outputDataEnd();
}
}
/** a helper function to calculate a square value */
function square(x: number): number {
return x * x;
}
/** a helper function to calculate a cube value */
function cube(x: number): number {
return x * x * x;
}
/**
* Render a Bezier curve: approximate it by small line segments, the interval
* size epsilon determined so that the distance between the true curve and its
* approximation does not exceed the desired accuracy delta. p1 is the
* starting point and is not emitted; p4 always is.
*/
export function BezierToPolyline(
aCornersBuffer: potrace_dpoint_t[],
p1: potrace_dpoint_t,
p2: potrace_dpoint_t,
p3: potrace_dpoint_t,
p4: potrace_dpoint_t,
): void {
const delta = 0.25; // desired accuracy, in pixels
/* let dd = maximal value of 2nd derivative over curve - this must occur at an
* endpoint. */
const dd0 = square(p1.x - 2 * p2.x + p3.x) + square(p1.y - 2 * p2.y + p3.y);
const dd1 = square(p2.x - 2 * p3.x + p4.x) + square(p2.y - 2 * p3.y + p4.y);
const dd = 6 * Math.sqrt(Math.max(dd0, dd1));
const e2 = 8 * delta <= dd ? (8 * delta) / dd : 1;
const epsilon = Math.sqrt(e2); // necessary interval size
for (let t = epsilon; t < 1; t += epsilon) {
aCornersBuffer.push({
x:
p1.x * cube(1 - t) +
3 * p2.x * square(1 - t) * t +
3 * p3.x * (1 - t) * square(t) +
p4.x * cube(t),
y:
p1.y * cube(1 - t) +
3 * p2.y * square(1 - t) * t +
3 * p3.y * (1 - t) * square(t) +
p4.y * cube(t),
});
}
aCornersBuffer.push(p4);
}
+13
View File
@@ -0,0 +1,13 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
/**
* The Image Converter, KiCad's `bitmap2component/`. The package barrel; the
* panel's view is `./bitmap2cmp_panel_ui.js`, imported by path so the engine
* can be loaded without React.
*/
export * from './bitmap2component.js';
export * from './bitmap2cmp_settings.js';
export * from './bitmap2cmp_panel.js';
export * from './bitmap2cmp_frame.js';
export * from './bitmap2cmp_control.js';
export * from './bitmap2cmp_main.js';
+23
View File
@@ -0,0 +1,23 @@
{
"name": "@ziroeda/bitmap2component",
"version": "0.0.0",
"description": "Image Converter mirroring KiCad's bitmap2component/: BITMAPCONV_INFO (trace and write symbol, footprint, PostScript, drawing sheet), IMAGE_SIZE, BITMAP2CMP_PANEL, BITMAP2CMP_FRAME, BITMAP2CMP_CONTROL, BITMAP2CMP_SETTINGS.",
"license": "GPL-3.0-or-later",
"type": "module",
"main": "./index.ts",
"types": "./index.ts",
"scripts": {
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@ziroeda/common": "workspace:*",
"@ziroeda/kimath": "workspace:*",
"@ziroeda/potrace": "workspace:*",
"@ziroeda/wx": "workspace:*",
"react": "^18.3.1"
},
"devDependencies": {
"@types/react": "^18.3.18",
"vite": "^6.0.7"
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"rootDir": ".",
"jsx": "react-jsx",
"types": ["vite/client"],
"lib": ["ES2022", "DOM", "DOM.Iterable"]
},
"include": ["."],
"exclude": ["node_modules"]
}
+50
View File
@@ -0,0 +1,50 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* KiCad's `bitmaps_png/`: the artwork, and `BITMAP_STORE`'s job of turning a
* name into something a widget can draw. KiCad compiles the SVGs into the
* binary and hands out `wxBitmapBundle`s; here they are files under
* `sources/<group>/` and the answer is a URL.
*
* `sources/toolbar/` is `bitmaps_png/sources/dark/` — the dark set only, since
* dark is our identity. The other groups are KiCad's dialog artwork
* (`calculator/`, `constraints/`, `teardrops/`, `tuning/`, `theme/`), the
* cursor PNGs (`cursors/`), and ours (`launcher/`, `manager/`).
*/
const URLS = import.meta.glob('./sources/*/*.{svg,png}', {
query: '?url',
import: 'default',
eager: true,
}) as Record<string, string>;
export type BitmapGroup =
| 'calculator'
| 'constraints'
| 'cursors'
| 'launcher'
| 'manager'
| 'teardrops'
| 'theme'
| 'toolbar'
| 'tuning';
/** The URL of `sources/<group>/<file>`, or undefined when no such bitmap exists. */
export function bitmapUrl(group: BitmapGroup, file: string): string | undefined {
return URLS[`./sources/${group}/${file}`];
}
/** `bitmapUrl( group, name + '.svg' )`. */
export function svgUrl(group: BitmapGroup, name: string): string | undefined {
return bitmapUrl(group, `${name}.svg`);
}
/** Every file name in a group, for the inventories that walk a set. */
export function bitmapNames(group: BitmapGroup): string[] {
const prefix = `./sources/${group}/`;
return Object.keys(URLS)
.filter((k) => k.startsWith(prefix))
.map((k) => k.slice(prefix.length));
}
export { default as kicadIconUrl } from './sources/icon_kicad.png';
+15
View File
@@ -0,0 +1,15 @@
{
"name": "@ziroeda/bitmaps_png",
"version": "0.0.0",
"description": "KiCad's bitmaps_png/: the vendored toolbar, cursor, calculator and dialog artwork, and the store that resolves a bitmap name to its URL.",
"license": "GPL-3.0-or-later",
"type": "module",
"main": "./index.ts",
"types": "./index.ts",
"scripts": {
"typecheck": "tsc --noEmit"
},
"devDependencies": {
"vite": "^6.0.7"
}
}
@@ -0,0 +1,312 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="76mm"
height="68mm"
viewBox="0 0 76.000002 68"
version="1.1"
id="svg8"
inkscape:version="1.0.2 (1.0.2+r75+1)"
sodipodi:docname="att_bridge.svg">
<defs
id="defs2" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="3.959798"
inkscape:cx="132.14104"
inkscape:cy="118.62885"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
showgrid="false"
inkscape:snap-global="false"
inkscape:window-width="2560"
inkscape:window-height="1371"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:document-rotation="0"
lock-margins="true"
fit-margin-top="2"
fit-margin-left="2"
fit-margin-right="2"
fit-margin-bottom="2" />
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
<cc:license
rdf:resource="http://creativecommons.org/licenses/by-sa/4.0/" />
</cc:Work>
<cc:License
rdf:about="http://creativecommons.org/licenses/by-sa/4.0/">
<cc:permits
rdf:resource="http://creativecommons.org/ns#Reproduction" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#Distribution" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#Notice" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#Attribution" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#DerivativeWorks" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#ShareAlike" />
</cc:License>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-14.520184,-93.461083)">
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 38.210597,130.27271 27.268295,-0.0334"
id="path875"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:#000090;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 48.660957,154.17826 h 6.437407"
id="path892"
inkscape:connector-curvature="0" />
<path
style="fill:#000090;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 49.836227,155.79648 h 4.098679"
id="path892-3"
inkscape:connector-curvature="0"
inkscape:transform-center-x="-0.1889881"
inkscape:transform-center-y="-0.66145834"
sodipodi:nodetypes="cc" />
<path
style="fill:#000090;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 50.840226,157.4265 h 1.960752"
id="path892-3-5"
inkscape:connector-curvature="0"
inkscape:transform-center-x="-0.1889881"
inkscape:transform-center-y="-0.66145834"
sodipodi:nodetypes="cc" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346;"
x="41.162865"
y="144.45956"
id="text941"><tspan
sodipodi:role="line"
id="tspan939"
x="41.162865"
y="144.45956"
style="stroke-width:0.115346;fill:#f4eff3;fill-opacity:1;">R2</tspan><tspan
sodipodi:role="line"
x="41.162865"
y="150.22687"
id="tspan961" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346;"
x="49.190071"
y="99.89592"
id="text941-6"><tspan
sodipodi:role="line"
id="tspan939-2"
x="49.190071"
y="99.89592"
style="stroke-width:0.115346;fill:#f4eff3;fill-opacity:1;">R1</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346;"
x="78.501251"
y="105.78497"
id="text941-9"><tspan
sodipodi:role="line"
id="tspan939-1"
x="78.501251"
y="105.78497"
style="stroke-width:0.115346;fill:#f4eff3;fill-opacity:1;">Z</tspan><tspan
sodipodi:role="line"
x="78.501251"
y="111.55228"
id="tspan961-2" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.264583"
x="85.422623"
y="114.53199"
id="text986" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:3.94956px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.0987391;"
x="82.11924"
y="106.95665"
id="text941-9-7"><tspan
sodipodi:role="line"
id="tspan939-1-0"
x="82.11924"
y="106.95665"
style="stroke-width:0.0987391;fill:#f4eff3;fill-opacity:1;">out</tspan><tspan
sodipodi:role="line"
x="82.11924"
y="111.8936"
id="tspan961-2-9" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346;"
x="18.240847"
y="105.49038"
id="text941-9-3"><tspan
sodipodi:role="line"
id="tspan939-1-6"
x="18.240847"
y="105.49038"
style="stroke-width:0.115346;fill:#f4eff3;fill-opacity:1;">Z</tspan><tspan
sodipodi:role="line"
x="18.240847"
y="111.25768"
id="tspan961-2-0" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:3.94956px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.0987391;"
x="21.858835"
y="106.66206"
id="text941-9-7-6"><tspan
sodipodi:role="line"
id="tspan939-1-0-2"
x="21.858835"
y="106.66206"
style="stroke-width:0.0987391;fill:#f4eff3;fill-opacity:1;">in</tspan><tspan
sodipodi:role="line"
x="21.858835"
y="111.59901"
id="tspan1041" /><tspan
sodipodi:role="line"
x="21.858835"
y="116.53596"
id="tspan961-2-9-6" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346;"
x="42.239479"
y="118.79475"
id="text941-9-3-1"><tspan
sodipodi:role="line"
id="tspan939-1-6-8"
x="42.239479"
y="118.79475"
style="stroke-width:0.115346;fill:#f4eff3;fill-opacity:1;">Z</tspan><tspan
sodipodi:role="line"
x="42.239479"
y="124.56205"
id="tspan961-2-0-7" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:3.94956px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.0987391;"
x="45.810219"
y="119.96642"
id="text941-9-7-6-9"><tspan
sodipodi:role="line"
id="tspan939-1-0-2-2"
x="45.810219"
y="119.96642"
style="stroke-width:0.0987391;fill:#f4eff3;fill-opacity:1;">0</tspan><tspan
sodipodi:role="line"
x="45.810219"
y="124.90337"
id="tspan1041-0" /><tspan
sodipodi:role="line"
x="45.810219"
y="129.84032"
id="tspan961-2-9-6-2" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346;"
x="55.174187"
y="118.76128"
id="text941-9-3-1-3"><tspan
sodipodi:role="line"
id="tspan939-1-6-8-7"
x="55.174187"
y="118.76128"
style="stroke-width:0.115346;fill:#f4eff3;fill-opacity:1;">Z</tspan><tspan
sodipodi:role="line"
x="55.174187"
y="124.52859"
id="tspan961-2-0-7-5" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:3.94956px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.0987391;"
x="58.697681"
y="119.93295"
id="text941-9-7-6-9-9"><tspan
sodipodi:role="line"
id="tspan939-1-0-2-2-2"
x="58.697681"
y="119.93295"
style="stroke-width:0.0987391;fill:#f4eff3;fill-opacity:1;">0</tspan><tspan
sodipodi:role="line"
x="58.697681"
y="124.8699"
id="tspan1041-0-2" /><tspan
sodipodi:role="line"
x="58.697681"
y="129.80685"
id="tspan961-2-9-6-2-8" /></text>
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 73.779844,103.90574 -16.75708,0.0868 -0.94205,2.14207 -1.4494,-4.23084 -1.54761,4.16175 -1.47351,-4.34433 -1.503892,4.26548 -1.486188,-4.33123 -1.011345,2.31728 -17.216173,-0.0765"
id="path60"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cccccccccc" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 65.184361,103.79329 0.03955,8.58335 2.14207,0.94205 -4.23084,1.44939 4.16175,1.54761 -4.34433,1.47351 4.26548,1.50389 -4.33123,1.48619 2.31728,1.01135 -0.0765,8.71171"
id="path195"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cccccccccc" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 38.631534,103.74605 0.03955,8.58335 2.14207,0.94205 -4.23084,1.44939 4.16175,1.54761 -4.34433,1.47351 4.26548,1.50389 -4.33123,1.48619 2.31728,1.01135 -0.0765,8.71171"
id="path197"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cccccccccc" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 52.002442,130.06264 0.03955,7.87464 2.14207,0.94205 -4.23084,1.44939 4.16175,1.54761 -4.34433,1.47351 4.26548,1.50389 -4.33123,1.48619 2.31728,1.01135 -0.02925,7.01082"
id="path199"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cccccccccc" />
</g>
<g
inkscape:groupmode="layer"
id="layer2"
inkscape:label="Layer 2"
transform="translate(-14.520184,-93.461083)">
<circle
style="fill:none;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="path827"
cx="75.426399"
cy="104.02554"
r="1.7533218" />
<circle
style="fill:none;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="path827-3"
cx="28.226622"
cy="103.88382"
r="1.7533218" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 13 KiB

+283
View File
@@ -0,0 +1,283 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="76mm"
height="42mm"
viewBox="0 0 76 42"
version="1.1"
id="svg8"
inkscape:version="1.0.2 (1.0.2+r75+1)"
sodipodi:docname="att_pi.svg"
inkscape:export-filename="/Users/jeff/kicad_dev/kicad/bitmaps_png/png_other/att_pi.png"
inkscape:export-xdpi="72.065102"
inkscape:export-ydpi="72.065102">
<defs
id="defs2" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="2.8284271"
inkscape:cx="1.4236148"
inkscape:cy="76.019395"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
showgrid="false"
inkscape:snap-global="false"
inkscape:window-width="2560"
inkscape:window-height="1371"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:document-rotation="0"
lock-margins="true"
fit-margin-top="1"
fit-margin-left="1"
fit-margin-right="1"
fit-margin-bottom="1" />
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
<cc:license
rdf:resource="http://creativecommons.org/licenses/by-sa/4.0/" />
</cc:Work>
<cc:License
rdf:about="http://creativecommons.org/licenses/by-sa/4.0/">
<cc:permits
rdf:resource="http://creativecommons.org/ns#Reproduction" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#Distribution" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#Notice" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#Attribution" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#DerivativeWorks" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#ShareAlike" />
</cc:License>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-14.716984,-94.402509)">
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 37.592366,103.41809 -0.04388,8.21478 2.196304,0.99627 -4.230842,1.4494 4.161747,1.54761 -4.344324,1.47351 4.157037,1.55811 -4.277011,1.43197 2.479939,0.95713 -0.108436,8.78231"
id="path858"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cccccccccc" />
<path
style="fill:#000090;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 34.308697,130.13628 h 6.437407"
id="path892"
inkscape:connector-curvature="0" />
<path
style="fill:#000090;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 35.483967,131.7545 h 4.098679"
id="path892-3"
inkscape:connector-curvature="0"
inkscape:transform-center-x="-0.1889881"
inkscape:transform-center-y="-0.66145834"
sodipodi:nodetypes="cc" />
<path
style="fill:#000090;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 36.487966,133.38452 h 1.960752"
id="path892-3-5"
inkscape:connector-curvature="0"
inkscape:transform-center-x="-0.1889881"
inkscape:transform-center-y="-0.66145834"
sodipodi:nodetypes="cc" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346;"
x="48.161472"
y="99.477455"
id="text941-6"><tspan
sodipodi:role="line"
id="tspan939-2"
x="48.161472"
y="99.477455"
style="stroke-width:0.115346;fill:#f4eff3;fill-opacity:1;">R2</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346;"
x="78.153008"
y="105.36651"
id="text941-9"><tspan
sodipodi:role="line"
id="tspan939-1"
x="78.153008"
y="105.36651"
style="stroke-width:0.115346;fill:#f4eff3;fill-opacity:1;">Z</tspan><tspan
sodipodi:role="line"
x="78.153008"
y="111.13381"
id="tspan961-2" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.264583"
x="85.422623"
y="114.53199"
id="text986" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:3.94956px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.0987391;"
x="81.770996"
y="106.53819"
id="text941-9-7"><tspan
sodipodi:role="line"
id="tspan939-1-0"
x="81.770996"
y="106.53819"
style="stroke-width:0.0987391;fill:#f4eff3;fill-opacity:1;">out</tspan><tspan
sodipodi:role="line"
x="81.770996"
y="111.47514"
id="tspan961-2-9" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346;"
x="16.409046"
y="105.07191"
id="text941-9-3"><tspan
sodipodi:role="line"
id="tspan939-1-6"
x="16.409046"
y="105.07191"
style="stroke-width:0.115346;fill:#f4eff3;fill-opacity:1;">Z</tspan><tspan
sodipodi:role="line"
x="16.409046"
y="110.83922"
id="tspan961-2-0" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:3.94956px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.0987391;"
x="20.027035"
y="106.24359"
id="text941-9-7-6"><tspan
sodipodi:role="line"
id="tspan939-1-0-2"
x="20.027035"
y="106.24359"
style="stroke-width:0.0987391;fill:#f4eff3;fill-opacity:1;">in</tspan><tspan
sodipodi:role="line"
x="20.027035"
y="111.18054"
id="tspan1041" /><tspan
sodipodi:role="line"
x="20.027035"
y="116.11749"
id="tspan961-2-9-6" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346;"
x="41.68335"
y="117.14787"
id="text941-9-3-1"><tspan
sodipodi:role="line"
id="tspan939-1-6-8"
x="41.68335"
y="117.14787"
style="stroke-width:0.115346;fill:#f4eff3;fill-opacity:1;">R1</tspan><tspan
sodipodi:role="line"
x="41.68335"
y="122.91517"
id="tspan961-2-0-7" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:3.94956px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.0987391"
x="43.512768"
y="116.5917"
id="text941-9-7-6-9" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346;"
x="67.941719"
y="117.49237"
id="text941-9-3-1-3"><tspan
sodipodi:role="line"
id="tspan939-1-6-8-7"
x="67.941719"
y="117.49237"
style="stroke-width:0.115346;fill:#f4eff3;fill-opacity:1;">R3</tspan><tspan
sodipodi:role="line"
x="67.941719"
y="123.25967"
id="tspan961-2-0-7-5" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:3.94956px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.0987391"
x="56.976643"
y="116.55823"
id="text941-9-7-6-9-9" />
<path
style="fill:#000090;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 60.784749,130.28393 h 6.437407"
id="path892-36"
inkscape:connector-curvature="0" />
<path
style="fill:#000090;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 61.960019,131.90215 h 4.098679"
id="path892-3-7"
inkscape:connector-curvature="0"
inkscape:transform-center-x="-0.1889881"
inkscape:transform-center-y="-0.66145834"
sodipodi:nodetypes="cc" />
<path
style="fill:#000090;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="M 62.964018,133.53217 H 64.92477"
id="path892-3-5-5"
inkscape:connector-curvature="0"
inkscape:transform-center-x="-0.1889881"
inkscape:transform-center-y="-0.66145834"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 64.050699,103.6475 0.01034,8.21478 2.142086,0.99627 -4.230842,1.4494 4.161747,1.54761 -4.344324,1.47351 4.157037,1.55811 -4.277011,1.43197 2.371503,1.01134 v 8.7281"
id="path58"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cccccccccc" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 72.400882,103.58521 -16.75708,0.0868 -0.942048,2.14208 -1.4494,-4.23084 -1.54761,4.16175 -1.47351,-4.34433 -1.503892,4.26548 -1.486188,-4.33123 -1.011345,2.31728 -17.216173,-0.0765"
id="path60"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cccccccccc" />
</g>
<g
inkscape:groupmode="layer"
id="layer2"
inkscape:label="Layer 2"
transform="translate(-14.716984,-94.402509)">
<circle
style="fill:none;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="path827"
cx="74.397797"
cy="103.60708"
r="1.7533218" />
<circle
style="fill:none;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="path827-3"
cx="27.198021"
cy="103.46535"
r="1.7533218" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 12 KiB

@@ -0,0 +1,293 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="78mm"
height="32mm"
viewBox="0 0 78 32"
version="1.1"
id="svg8"
inkscape:version="1.0.2 (1.0.2+r75+1)"
sodipodi:docname="att_splitter.svg"
inkscape:export-filename="/Users/jeff/kicad_dev/kicad/bitmaps_png/png_other/att_splitter.png"
inkscape:export-xdpi="72.065102"
inkscape:export-ydpi="72.065102">
<defs
id="defs2" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="4"
inkscape:cx="87.577258"
inkscape:cy="53.409952"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
showgrid="false"
inkscape:snap-global="false"
inkscape:window-width="2560"
inkscape:window-height="1371"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:measure-start="0,0"
inkscape:measure-end="0,0"
inkscape:document-rotation="0"
fit-margin-top="2"
lock-margins="true"
fit-margin-left="2"
fit-margin-right="2"
fit-margin-bottom="2" />
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
<cc:license
rdf:resource="http://creativecommons.org/licenses/by-sa/4.0/" />
</cc:Work>
<cc:License
rdf:about="http://creativecommons.org/licenses/by-sa/4.0/">
<cc:permits
rdf:resource="http://creativecommons.org/ns#Reproduction" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#Distribution" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#Notice" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#Attribution" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#DerivativeWorks" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#ShareAlike" />
</cc:License>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-14.2934,-77.588773)">
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346;"
x="78.866714"
y="104.76347"
id="text941-9"><tspan
sodipodi:role="line"
id="tspan939-1"
x="78.866714"
y="104.76347"
style="stroke-width:0.115346;fill:#f4eff3;fill-opacity:1;">Z</tspan><tspan
sodipodi:role="line"
x="78.866714"
y="110.53078"
id="tspan961-2" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.264583"
x="85.422623"
y="114.53199"
id="text986" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:3.94956px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.0987391;"
x="82.484703"
y="105.93513"
id="text941-9-7"><tspan
sodipodi:role="line"
id="tspan939-1-0"
x="82.484703"
y="105.93513"
style="stroke-width:0.0987391;fill:#f4eff3;fill-opacity:1;">out</tspan><tspan
sodipodi:role="line"
x="82.484703"
y="110.87208"
id="tspan961-2-9" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346;"
x="16.935583"
y="96.701141"
id="text941-9-3"><tspan
sodipodi:role="line"
id="tspan939-1-6"
x="16.935583"
y="96.701141"
style="stroke-width:0.115346;fill:#f4eff3;fill-opacity:1;">Z</tspan><tspan
sodipodi:role="line"
x="16.935583"
y="102.46844"
id="tspan961-2-0" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:3.94956px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.0987391;"
x="20.553572"
y="97.872818"
id="text941-9-7-6"><tspan
sodipodi:role="line"
id="tspan939-1-0-2"
x="20.553572"
y="97.872818"
style="stroke-width:0.0987391;fill:#f4eff3;fill-opacity:1;">in</tspan><tspan
sodipodi:role="line"
x="20.553572"
y="102.80977"
id="tspan1041" /><tspan
sodipodi:role="line"
x="20.553572"
y="107.74672"
id="tspan961-2-9-6" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:3.94956px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.0987391"
x="43.512768"
y="116.5917"
id="text941-9-7-6-9" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346;"
x="60.644146"
y="98.887894"
id="text941-9-3-1-3"><tspan
sodipodi:role="line"
id="tspan939-1-6-8-7"
x="60.644146"
y="98.887894"
style="stroke-width:0.115346;fill:#f4eff3;fill-opacity:1;">R3</tspan><tspan
sodipodi:role="line"
x="60.644146"
y="104.6552"
id="tspan961-2-0-7-5" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:3.94956px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.0987391"
x="56.976643"
y="116.55823"
id="text941-9-7-6-9-9" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346;"
x="37.991467"
y="90.981583"
id="text941-9-3-1-3-5"><tspan
sodipodi:role="line"
id="tspan939-1-6-8-7-6"
x="37.991467"
y="90.981583"
style="stroke-width:0.115346;fill:#f4eff3;fill-opacity:1;">R1</tspan><tspan
sodipodi:role="line"
x="37.991467"
y="96.748886"
id="tspan961-2-0-7-5-2" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346;"
x="60.956078"
y="83.145401"
id="text941-9-3-1-3-9"><tspan
sodipodi:role="line"
id="tspan939-1-6-8-7-1"
x="60.956078"
y="83.145401"
style="stroke-width:0.115346;fill:#f4eff3;fill-opacity:1;">R2</tspan><tspan
sodipodi:role="line"
x="60.956078"
y="88.912704"
id="tspan3321" /><tspan
sodipodi:role="line"
x="60.956078"
y="94.68"
id="tspan961-2-0-7-5-27" /></text>
<circle
style="fill:none;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="path827-9"
cx="75.189011"
cy="87.346275"
r="1.7533218" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="M 52.155989,87.308258 V 103.3752"
id="path3323"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346;"
x="79.112091"
y="89.075157"
id="text941-9-9"><tspan
sodipodi:role="line"
id="tspan939-1-2"
x="79.112091"
y="89.075157"
style="stroke-width:0.115346;fill:#f4eff3;fill-opacity:1;">Z</tspan><tspan
sodipodi:role="line"
x="79.112091"
y="94.842461"
id="tspan961-2-2" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:3.94956px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.0987391;"
x="82.73008"
y="90.246834"
id="text941-9-7-8"><tspan
sodipodi:role="line"
id="tspan939-1-0-9"
x="82.73008"
y="90.246834"
style="stroke-width:0.0987391;fill:#f4eff3;fill-opacity:1;">out</tspan><tspan
sodipodi:role="line"
x="82.73008"
y="95.183784"
id="tspan961-2-9-7" /></text>
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 73.489449,87.398676 -5.41704,0.0326 -1.053087,2.1963 -1.4494,-4.23084 -1.54761,4.16175 -1.47351,-4.34433 -1.55811,4.15704 -1.43197,-4.27701 -1.07337,2.3715 -6.66664,-0.02326"
id="path60"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cccccccccc" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 73.138916,103.02035 -5.084521,0.0326 -0.894337,2.1963 -1.4494,-4.23084 -1.54761,4.16175 -1.47351,-4.34433 -1.55811,4.15704 -1.43197,-4.27701 -1.126287,2.3715 -6.661169,-0.0233"
id="path134"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cccccccccc" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 52.317294,94.857675 -7.16906,0.0326 -0.894337,2.1963 -1.4494,-4.23084 -1.54761,4.16175 -1.47351,-4.34433 -1.55811,4.15704 -1.43197,-4.27701 -1.020453,2.3715 -7.145445,-0.02326"
id="path60-3"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cccccccccc" />
</g>
<g
inkscape:groupmode="layer"
id="layer2"
inkscape:label="Layer 2"
transform="translate(-14.2934,-77.588773)">
<circle
style="fill:none;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="path827"
cx="74.877083"
cy="103.08876"
r="1.7533218" />
<circle
style="fill:none;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="path827-3"
cx="26.99695"
cy="94.915039"
r="1.7533218" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 12 KiB

+260
View File
@@ -0,0 +1,260 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="74mm"
height="39mm"
viewBox="0 0 74 39"
version="1.1"
id="svg8"
inkscape:version="1.0.2 (1.0.2+r75+1)"
sodipodi:docname="att_tee.svg">
<defs
id="defs2" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="1.4142136"
inkscape:cx="152.38341"
inkscape:cy="56.794706"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
showgrid="false"
inkscape:snap-global="false"
inkscape:window-width="2560"
inkscape:window-height="1371"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:measure-start="0,0"
inkscape:measure-end="0,0"
inkscape:document-rotation="0"
fit-margin-top="0"
fit-margin-left="0"
fit-margin-right="0"
fit-margin-bottom="0" />
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
<cc:license
rdf:resource="http://creativecommons.org/licenses/by-sa/4.0/" />
</cc:Work>
<cc:License
rdf:about="http://creativecommons.org/licenses/by-sa/4.0/">
<cc:permits
rdf:resource="http://creativecommons.org/ns#Reproduction" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#Distribution" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#Notice" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#Attribution" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#DerivativeWorks" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#ShareAlike" />
</cc:License>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-15.857724,-95.331266)">
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346"
x="41.185181"
y="117.44218"
id="text941-6"><tspan
sodipodi:role="line"
id="tspan939-2"
x="41.185181"
y="117.44218"
style="fill:#f4eff3;fill-opacity:1;stroke-width:0.115346">R2</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346"
x="79.860718"
y="104.6214"
id="text941-9"><tspan
sodipodi:role="line"
id="tspan939-1"
x="79.860718"
y="104.6214"
style="fill:#f4eff3;fill-opacity:1;stroke-width:0.115346">Z</tspan><tspan
sodipodi:role="line"
x="79.860718"
y="110.3887"
id="tspan961-2" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.264583"
x="85.422623"
y="114.53199"
id="text986" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:3.94956px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.0987391"
x="83.478706"
y="105.79308"
id="text941-9-7"><tspan
sodipodi:role="line"
id="tspan939-1-0"
x="83.478706"
y="105.79308"
style="fill:#f4eff3;fill-opacity:1;stroke-width:0.0987391">out</tspan><tspan
sodipodi:role="line"
x="83.478706"
y="110.73003"
id="tspan961-2-9" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346"
x="15.650462"
y="104.46855"
id="text941-9-3"><tspan
sodipodi:role="line"
id="tspan939-1-6"
x="15.650462"
y="104.46855"
style="fill:#f4eff3;fill-opacity:1;stroke-width:0.115346">Z</tspan><tspan
sodipodi:role="line"
x="15.650462"
y="110.23586"
id="tspan961-2-0" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:3.94956px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.0987391"
x="19.26845"
y="105.64024"
id="text941-9-7-6"><tspan
sodipodi:role="line"
id="tspan939-1-0-2"
x="19.26845"
y="105.64024"
style="fill:#f4eff3;fill-opacity:1;stroke-width:0.0987391">in</tspan><tspan
sodipodi:role="line"
x="19.26845"
y="110.57719"
id="tspan1041" /><tspan
sodipodi:role="line"
x="19.26845"
y="115.51414"
id="tspan961-2-9-6" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:3.94956px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.0987391"
x="43.512768"
y="116.5917"
id="text941-9-7-6-9" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346"
x="60.77644"
y="98.7556"
id="text941-9-3-1-3"><tspan
sodipodi:role="line"
id="tspan939-1-6-8-7"
x="60.77644"
y="98.7556"
style="fill:#f4eff3;fill-opacity:1;stroke-width:0.115346">R3</tspan><tspan
sodipodi:role="line"
x="60.77644"
y="104.5229"
id="tspan961-2-0-7-5" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:3.94956px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.0987391"
x="56.976643"
y="116.55823"
id="text941-9-7-6-9-9" />
<path
style="fill:#000090;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 48.611282,129.9168 h 6.437407"
id="path892-36"
inkscape:connector-curvature="0" />
<path
style="fill:#000090;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 49.786552,131.53502 h 4.098679"
id="path892-3-7"
inkscape:connector-curvature="0"
inkscape:transform-center-x="-0.1889881"
inkscape:transform-center-y="-0.66145834"
sodipodi:nodetypes="cc" />
<path
style="fill:#000090;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 50.790551,133.16504 h 1.960752"
id="path892-3-5-5"
inkscape:connector-curvature="0"
inkscape:transform-center-x="-0.1889881"
inkscape:transform-center-y="-0.66145834"
sodipodi:nodetypes="cc" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.61384px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#f4eff3;fill-opacity:1;stroke:none;stroke-width:0.115346"
x="37.216618"
y="98.881287"
id="text941-9-3-1-3-5"><tspan
sodipodi:role="line"
id="tspan939-1-6-8-7-6"
x="37.216618"
y="98.881287"
style="fill:#f4eff3;fill-opacity:1;stroke-width:0.115346">R1</tspan><tspan
sodipodi:role="line"
x="37.216618"
y="104.64859"
id="tspan961-2-0-7-5-2" /></text>
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 52.217951,102.81197 -7.969134,0.0395 -0.942048,2.14208 -1.4494,-4.23084 -1.54761,4.16175 -1.47351,-4.34433 -1.503892,4.26548 -1.486188,-4.33123 -1.011345,2.31728 -7.058063,0.018"
id="path60"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cccccccccc" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 74.235064,102.85921 -6.173747,-0.008 -0.942048,2.14208 -1.4494,-4.23084 -1.54761,4.16175 -1.47351,-4.34433 -1.503892,4.26548 -1.486188,-4.33123 -1.011345,2.31728 -7.010816,-0.0293"
id="path125"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cccccccccc" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.8;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 51.87834,102.67696 -0.0077,8.6306 2.14208,0.94205 -4.23084,1.4494 4.16175,1.54761 -4.34433,1.47351 4.26548,1.50389 -4.33123,1.48619 2.31728,1.01134 0.01799,9.51492"
id="path60-4"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cccccccccc" />
</g>
<g
inkscape:groupmode="layer"
id="layer2"
inkscape:label="Layer 2"
transform="translate(-15.857724,-95.331266)">
<circle
style="fill:none;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="path827"
cx="76.011017"
cy="102.85252"
r="1.7533218" />
<circle
style="fill:none;fill-opacity:1;stroke:#42b8eb;stroke-width:0.8;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="path827-3"
cx="26.222099"
cy="102.81474"
r="1.7533218" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 11 KiB

@@ -0,0 +1,778 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="60mm"
height="46mm"
viewBox="0 0 60 46"
version="1.1"
id="svg19844"
inkscape:version="1.0.2 (1.0.2+r75+1)"
sodipodi:docname="c_microstrip.svg"
inkscape:export-filename="/Users/jeff/kicad_dev/kicad/bitmaps_png/png_other/c_microstrip.png"
inkscape:export-xdpi="96"
inkscape:export-ydpi="96">
<defs
id="defs19838">
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL"
style="overflow:visible"
inkscape:isstock="true">
<path
id="path12142"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#42b8eb;fill-opacity:1;fill-rule:evenodd;stroke:#42b8eb;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:stockid="Arrow2Lstart"
orient="auto"
refY="0"
refX="0"
id="Arrow2Lstart"
style="overflow:visible"
inkscape:isstock="true">
<path
id="path12027"
style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1"
d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z"
transform="matrix(1.1,0,0,1.1,1.1,0)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker23801"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
transform="scale(0.8)"
style="fill:#42b8eb;fill-opacity:1;fill-rule:evenodd;stroke:#42b8eb;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path23799" />
</marker>
<marker
inkscape:stockid="TriangleOutL"
orient="auto"
refY="0"
refX="0"
id="TriangleOutL"
style="overflow:visible"
inkscape:isstock="true"
inkscape:collect="always">
<path
id="path12151"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#42b8eb;fill-opacity:1;fill-rule:evenodd;stroke:#42b8eb;stroke-width:1pt;stroke-opacity:1"
transform="scale(0.8)" />
</marker>
<marker
style="overflow:visible"
id="DistanceEnd"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="DistanceEnd"
inkscape:isstock="true">
<g
id="g2301"
style="fill:#0081d5;fill-opacity:1;stroke:#0081d5;stroke-opacity:1">
<path
style="fill:#0081d5;fill-opacity:1;stroke:#0081d5;stroke-width:1.15;stroke-linecap:square;stroke-opacity:1"
d="M 0,0 H -2"
id="path2316" />
<path
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-opacity:1"
d="m 0,0 -13,4 4,-4 -4,-4 z"
id="path2312" />
<path
style="fill:#0081d5;fill-opacity:1;stroke:#0081d5;stroke-width:1;stroke-linecap:square;stroke-opacity:1"
d="M 0,-4 V 40"
id="path2314" />
</g>
</marker>
<marker
style="overflow:visible"
id="DistanceStart"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="DistanceStart"
inkscape:isstock="true">
<g
id="g2300"
style="fill:#0081d5;fill-opacity:1;stroke:#0081d5;stroke-opacity:1">
<path
style="fill:#0081d5;fill-opacity:1;stroke:#0081d5;stroke-width:1.15;stroke-linecap:square;stroke-opacity:1"
d="M 0,0 H 2"
id="path2306" />
<path
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-opacity:1"
d="M 0,0 13,4 9,0 13,-4 Z"
id="path2302" />
<path
style="fill:#0081d5;fill-opacity:1;stroke:#0081d5;stroke-width:1;stroke-linecap:square;stroke-opacity:1"
d="M 0,-4 V 40"
id="path2304" />
</g>
</marker>
<marker
inkscape:stockid="Arrow2Lend"
orient="auto"
refY="0"
refX="0"
id="marker21133"
style="overflow:visible"
inkscape:isstock="true">
<path
id="path21131"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1"
d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z"
transform="matrix(-1.1,0,0,-1.1,-1.1,0)" />
</marker>
<marker
inkscape:stockid="RazorWire"
id="RazorWire"
refX="0"
refY="0"
orient="auto"
style="overflow:visible"
inkscape:isstock="true">
<path
id="path12241"
transform="scale(0.8)"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:0.1pt;stroke-opacity:1"
d="m 0.02272727,-0.74009011 v 1.4375 L -7.7585227,3.0099099 H 10.678977 L 3.4914773,0.69740989 v -1.4375 L 10.741477,-2.8963401 H -7.7272727 Z" />
</marker>
<marker
inkscape:stockid="Arrow2Lend"
orient="auto"
refY="0"
refX="0"
id="Arrow2Lend"
style="overflow:visible"
inkscape:isstock="true">
<path
id="path12030"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1"
d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z"
transform="matrix(-1.1,0,0,-1.1,-1.1,0)" />
</marker>
<marker
inkscape:stockid="TriangleOutL"
orient="auto"
refY="0"
refX="0"
id="TriangleOutL-9"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path12151-0"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#42b8eb;fill-opacity:1;fill-rule:evenodd;stroke:#42b8eb;stroke-width:1pt;stroke-opacity:1"
transform="scale(0.8)" />
</marker>
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL-9"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path12142-6"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker23801-7"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
inkscape:connector-curvature="0"
transform="scale(0.8)"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path23799-7" />
</marker>
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL-9-7"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path12142-6-1"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker23801-7-2"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
inkscape:connector-curvature="0"
transform="scale(0.8)"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path23799-7-2" />
</marker>
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL-9-5"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path12142-6-0"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker23801-7-9"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
inkscape:connector-curvature="0"
transform="scale(0.8)"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path23799-7-0" />
</marker>
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL-9-5-0"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path12142-6-0-1"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker23801-7-9-3"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
inkscape:connector-curvature="0"
transform="scale(0.8)"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path23799-7-0-7" />
</marker>
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL-7"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path12142-5"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#42b8eb;fill-opacity:1;fill-rule:evenodd;stroke:#42b8eb;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker23801-6"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
inkscape:connector-curvature="0"
transform="scale(0.8)"
style="fill:#42b8eb;fill-opacity:1;fill-rule:evenodd;stroke:#42b8eb;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path23799-5" />
</marker>
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL-9-5-0-1"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path12142-6-0-1-6"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#42b8eb;fill-opacity:1;fill-rule:evenodd;stroke:#42b8eb;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker23801-7-9-3-5"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
inkscape:connector-curvature="0"
transform="scale(0.8)"
style="fill:#42b8eb;fill-opacity:1;fill-rule:evenodd;stroke:#42b8eb;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path23799-7-0-7-7" />
</marker>
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL-9-5-0-1-2"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path12142-6-0-1-6-1"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#42b8eb;fill-opacity:1;fill-rule:evenodd;stroke:#42b8eb;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker23801-7-9-3-5-6"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
inkscape:connector-curvature="0"
transform="scale(0.8)"
style="fill:#42b8eb;fill-opacity:1;fill-rule:evenodd;stroke:#42b8eb;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path23799-7-0-7-7-3" />
</marker>
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL-9-5-0-1-2-0"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path12142-6-0-1-6-1-2"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#42b8eb;fill-opacity:1;fill-rule:evenodd;stroke:#42b8eb;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker23801-7-9-3-5-6-5"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
inkscape:connector-curvature="0"
transform="scale(0.8)"
style="fill:#42b8eb;fill-opacity:1;fill-rule:evenodd;stroke:#42b8eb;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path23799-7-0-7-7-3-8" />
</marker>
</defs>
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="6.5053824"
inkscape:cx="89.390697"
inkscape:cy="72.645206"
inkscape:document-units="mm"
inkscape:current-layer="layer8"
showgrid="false"
inkscape:window-width="2560"
inkscape:window-height="1371"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:snap-global="false"
showguides="false"
inkscape:document-rotation="0"
lock-margins="true"
fit-margin-top="2"
fit-margin-left="2"
fit-margin-right="2"
fit-margin-bottom="2" />
<metadata
id="metadata19841">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
<cc:license
rdf:resource="http://creativecommons.org/licenses/by-sa/4.0/" />
</cc:Work>
<cc:License
rdf:about="http://creativecommons.org/licenses/by-sa/4.0/">
<cc:permits
rdf:resource="http://creativecommons.org/ns#Reproduction" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#Distribution" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#Notice" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#Attribution" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#DerivativeWorks" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#ShareAlike" />
</cc:License>
</rdf:RDF>
</metadata>
<g
inkscape:groupmode="layer"
id="layer9"
inkscape:label="Layer 4"
style="display:inline"
transform="translate(-51.034357,-151.63169)">
<path
style="fill:#cccccc;fill-opacity:1;stroke:none;stroke-width:0.264583px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 54.668288,180.88025 11.013217,-11.01322 h 41.862985 v 10.70911 l -10.748239,10.36133 z"
id="path20574"
inkscape:connector-curvature="0" />
<path
style="fill:#fcb23c;fill-opacity:1;stroke:none;stroke-width:0.264583px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 54.668288,190.93747 v 2.73555 h 42.115673 l 10.745889,-10.7459 v -2.6894 l -10.708006,10.70802 z"
id="path20813"
inkscape:connector-curvature="0" />
</g>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-51.034357,-151.63169)">
<path
style="fill:none;stroke:#895502;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 96.878065,193.72862 10.683805,-10.75397 -0.009,-2.57335"
id="path20805"
inkscape:connector-curvature="0"
sodipodi:nodetypes="ccc" />
<path
style="fill:none;stroke:#895502;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 54.667104,191.17808 -0.0021,2.48046 42.138614,-2e-4 v -2.47976"
id="path20803"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cccc" />
</g>
<g
inkscape:groupmode="layer"
id="layer8"
inkscape:label="Layer 3"
transform="translate(-51.034357,-151.63169)">
<rect
style="opacity:1;fill:#cccccc;fill-opacity:1;stroke:#474747;stroke-width:0.49747;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
id="rect20534"
width="42.127968"
height="10.05722"
x="54.668289"
y="180.88025" />
<path
style="fill:none;stroke:#474747;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="M 96.796251,180.88025 107.62341,169.8378"
id="path20538"
inkscape:connector-curvature="0" />
<path
style="fill:none;stroke:#474747;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="M 54.596668,180.80571 65.535219,169.72952 H 107.55313 V 180.4013 L 96.867872,191.00763"
id="path20536"
inkscape:connector-curvature="0"
sodipodi:nodetypes="ccccc" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:7.5037px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#42b8eb;fill-opacity:1;stroke:none;stroke-width:0.187593;"
x="59.309597"
y="188.94899"
id="text21059"><tspan
sodipodi:role="line"
id="tspan21057"
x="59.309597"
y="188.94899"
style="fill:#42b8eb;fill-opacity:1;stroke-width:0.187593;">T</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:9.15486px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#42b8eb;fill-opacity:1;stroke:none;stroke-width:0.228872;"
x="83.839119"
y="188.77823"
id="text23789"><tspan
sodipodi:role="line"
id="tspan23787"
x="83.839119"
y="188.77823"
style="fill:#42b8eb;fill-opacity:1;stroke-width:0.228872;">H</tspan></text>
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-start:url(#TriangleInL);marker-end:url(#marker23801)"
d="m 93.755463,188.95721 v -6.14522"
id="path23791"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:9.15486px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#0081d5;fill-opacity:1;stroke:none;stroke-width:0.228872"
x="87.574654"
y="162.95206"
id="text23789-9" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-start:url(#TriangleInL-7);marker-end:url(#marker23801-6)"
d="m 93.321197,179.37983 8.115583,-8.23352"
id="path23791-4"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<ellipse
style="opacity:1;fill:#cccccc;fill-opacity:1;stroke:none;stroke-width:0.341557;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
id="path35483"
cx="97.864662"
cy="174.76736"
rx="1.6803141"
ry="1.4883821" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:6.2411px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#42b8eb;fill-opacity:1;stroke:none;stroke-width:0.156027;"
x="96.785194"
y="175.8065"
id="text21059-1-3-2"><tspan
sodipodi:role="line"
id="tspan21057-1-0-2"
x="96.785194"
y="175.8065"
style="fill:#42b8eb;fill-opacity:1;stroke-width:0.156027;">L</tspan></text>
<path
style="opacity:1;fill:#fcb23c;fill-opacity:1;stroke:none;stroke-width:0.264583px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 73.878565,166.92203 7.32248,0.0122 0.12186,2.20498 -11.10794,11.14823 -6.6543,-0.21588 v -2.57247 z"
id="path20496-2-5-9-8"
inkscape:connector-curvature="0"
sodipodi:nodetypes="ccccccc" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:2, 0.50000000000000000;stroke-dashoffset:0;stroke-opacity:1"
d="m 73.958125,166.9041 c 0,-6.01022 0,-6.03361 0,-6.03361"
id="path24677-1-5"
inkscape:connector-curvature="0" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:2, 0.50000000000000000;stroke-dashoffset:0;stroke-opacity:1"
d="m 81.279995,166.90337 c 0,-6.01022 0,-6.03361 0,-6.03361"
id="path24677-4-9"
inkscape:connector-curvature="0" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.25;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-start:url(#TriangleInL-9-5-0-1);marker-end:url(#marker23801-7-9-3-5)"
d="m 79.664775,160.26144 h -4.02201"
id="path23791-3-4-4-2"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.92584px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#42b8eb;fill-opacity:1;stroke:none;stroke-width:0.123146;"
x="75.126236"
y="158.36339"
id="text21059-1-32-7"><tspan
sodipodi:role="line"
id="tspan21057-1-1-3"
x="75.126236"
y="158.36339"
style="fill:#42b8eb;fill-opacity:1;stroke-width:0.123146;">W</tspan></text>
<rect
style="opacity:1;fill:#fcb23c;fill-opacity:1;stroke:#895502;stroke-width:0.499178;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
id="rect20424-6"
width="6.6496596"
height="2.6584673"
x="63.511269"
y="177.71767" />
<path
style="fill:none;stroke:#895502;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 63.439505,177.64255 10.45486,-10.56438"
id="path20428-3-9-1-8-9-4"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#895502;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 70.014175,177.88925 11.13697,-10.79811"
id="path20428-7-9-6-6-7"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#895502;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 70.232245,180.44642 11.10794,-11.14823"
id="path20428-0-4-8-8-0-9"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#895502;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 81.267875,169.47518 0.012,-2.57383"
id="path20458-2-1-5-6-7"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#895502;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 73.714755,167.14911 7.81435,0.002"
id="path20475-2-6-1-4-2"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="opacity:1;fill:#fcb23c;fill-opacity:1;stroke:none;stroke-width:0.264583px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 90.932547,166.932 7.32248,0.0122 0.12186,2.20498 -11.10794,11.14823 -6.6543,-0.21588 v -2.57247 z"
id="path20496-2-5-9-8-0"
inkscape:connector-curvature="0"
sodipodi:nodetypes="ccccccc" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:2, 0.50000000000000000;stroke-dashoffset:0;stroke-opacity:1"
d="m 91.012107,166.91407 c 0,-6.01022 0,-6.03361 0,-6.03361"
id="path24677-1-5-2"
inkscape:connector-curvature="0" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:2, 0.50000000000000000;stroke-dashoffset:0;stroke-opacity:1"
d="m 98.333977,166.91334 c 0,-6.01022 0,-6.03361 0,-6.03361"
id="path24677-4-9-1"
inkscape:connector-curvature="0" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.25;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-start:url(#TriangleInL-9-5-0-1-2);marker-end:url(#marker23801-7-9-3-5-6)"
d="m 96.718757,160.27141 h -4.02201"
id="path23791-3-4-4-2-5"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.92584px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#42b8eb;fill-opacity:1;stroke:none;stroke-width:0.123146;"
x="92.180222"
y="158.37335"
id="text21059-1-32-7-6"><tspan
sodipodi:role="line"
id="tspan21057-1-1-3-5"
x="92.180222"
y="158.37335"
style="fill:#42b8eb;fill-opacity:1;stroke-width:0.123146;">W</tspan></text>
<rect
style="opacity:1;fill:#fcb23c;fill-opacity:1;stroke:#895502;stroke-width:0.499178;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
id="rect20424-6-0"
width="6.6496596"
height="2.6584673"
x="80.565239"
y="177.72763" />
<path
style="fill:none;stroke:#895502;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 80.493487,177.65252 10.45486,-10.56438"
id="path20428-3-9-1-8-9-4-0"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#895502;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 87.068157,177.89922 11.13697,-10.79811"
id="path20428-7-9-6-6-7-3"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#895502;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 87.286227,180.45639 11.10794,-11.14823"
id="path20428-0-4-8-8-0-9-4"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#895502;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 98.321857,169.48515 0.012,-2.57383"
id="path20458-2-1-5-6-7-6"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#895502;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 90.768737,167.15908 7.81435,0.002"
id="path20475-2-6-1-4-2-6"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.25;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-start:url(#TriangleInL-9-5-0-1-2-0);marker-end:url(#marker23801-7-9-3-5-6-5)"
d="M 89.569158,160.26602 H 82.810976"
id="path23791-3-4-4-2-5-9"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.92584px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#42b8eb;fill-opacity:1;stroke:none;stroke-width:0.123146;"
x="84.724129"
y="158.64711"
id="text21059-1-32-7-6-5"><tspan
sodipodi:role="line"
id="tspan21057-1-1-3-5-0"
x="84.724129"
y="158.64711"
style="fill:#42b8eb;fill-opacity:1;stroke-width:0.123146;">S</tspan><tspan
sodipodi:role="line"
x="84.724129"
y="164.80441"
id="tspan38353" /></text>
</g>
<g
inkscape:groupmode="layer"
id="layer7"
inkscape:label="Layer 2"
transform="translate(-51.034357,-151.63169)">
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#TriangleOutL)"
d="m 66.010613,188.24451 v -5.41497"
id="path21071"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#TriangleOutL-9)"
d="m 66.066342,170.36375 v 5.41497"
id="path21071-8"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 31 KiB

+423
View File
@@ -0,0 +1,423 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="64mm"
height="60mm"
viewBox="0 0 64 60"
version="1.1"
id="svg8"
inkscape:version="1.0.2 (1.0.2+r75+1)"
sodipodi:docname="coax.svg"
inkscape:export-filename="/Users/jeff/kicad_dev/kicad/bitmaps_png/png_other/coax.png"
inkscape:export-xdpi="96"
inkscape:export-ydpi="96">
<defs
id="defs2">
<marker
inkscape:stockid="TriangleOutL"
orient="auto"
refY="0"
refX="0"
id="marker16887"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path16885"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#42b8eb;fill-opacity:1;fill-rule:evenodd;stroke:#42b8eb;stroke-width:1pt;stroke-opacity:1"
transform="scale(0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker16639"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleInL">
<path
transform="scale(-0.8)"
style="fill:#42b8eb;fill-opacity:1;fill-rule:evenodd;stroke:#42b8eb;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path16637" />
</marker>
<marker
inkscape:stockid="TriangleOutL"
orient="auto"
refY="0"
refX="0"
id="marker16563"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path16561"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
transform="scale(0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker15132"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL"
inkscape:collect="always">
<path
transform="scale(0.8)"
style="fill:#42b8eb;fill-opacity:1;fill-rule:evenodd;stroke:#42b8eb;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path15130"
inkscape:connector-curvature="0" />
</marker>
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL"
style="overflow:visible"
inkscape:isstock="true"
inkscape:collect="always">
<path
id="path12142"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#42b8eb;fill-opacity:1;fill-rule:evenodd;stroke:#42b8eb;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:stockid="Arrow2Lstart"
orient="auto"
refY="0"
refX="0"
id="Arrow2Lstart"
style="overflow:visible"
inkscape:isstock="true">
<path
id="path12027"
style="fill:#0000fa;fill-opacity:1;fill-rule:evenodd;stroke:#0000fa;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1"
d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z"
transform="matrix(1.1,0,0,1.1,1.1,0)" />
</marker>
<marker
inkscape:stockid="TriangleOutL"
orient="auto"
refY="0"
refX="0"
id="marker14968"
style="overflow:visible"
inkscape:isstock="true">
<path
id="path14966"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#0000fa;fill-opacity:1;fill-rule:evenodd;stroke:#0000fa;stroke-width:1pt;stroke-opacity:1"
transform="scale(0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker14928"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
transform="scale(0.8)"
style="fill:#0000fa;fill-opacity:1;fill-rule:evenodd;stroke:#0000fa;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path14926" />
</marker>
<marker
inkscape:stockid="TriangleOutL"
orient="auto"
refY="0"
refX="0"
id="TriangleOutL"
style="overflow:visible"
inkscape:isstock="true"
inkscape:collect="always">
<path
id="path12151"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#42b8eb;fill-opacity:1;fill-rule:evenodd;stroke:#42b8eb;stroke-width:1pt;stroke-opacity:1"
transform="scale(0.8)" />
</marker>
<marker
inkscape:stockid="Arrow2Lend"
orient="auto"
refY="0"
refX="0"
id="Arrow2Lend"
style="overflow:visible"
inkscape:isstock="true">
<path
id="path12030"
style="fill:#0000ff;fill-opacity:1;fill-rule:evenodd;stroke:#0000ff;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1"
d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z"
transform="matrix(-1.1,0,0,-1.1,-1.1,0)" />
</marker>
<marker
inkscape:stockid="TriangleOutL"
orient="auto"
refY="0"
refX="0"
id="TriangleOutL-1"
style="overflow:visible"
inkscape:isstock="true"
inkscape:collect="always">
<path
inkscape:connector-curvature="0"
id="path12151-8"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#42b8eb;fill-opacity:1;fill-rule:evenodd;stroke:#42b8eb;stroke-width:1pt;stroke-opacity:1"
transform="scale(0.8)" />
</marker>
</defs>
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:zoom="4.2426407"
inkscape:cx="119.95512"
inkscape:cy="131.91063"
inkscape:document-units="mm"
inkscape:current-layer="layer2"
showgrid="false"
inkscape:window-width="2560"
inkscape:window-height="1371"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:snap-bbox="true"
inkscape:pagecheckerboard="false"
inkscape:document-rotation="0"
lock-margins="true"
fit-margin-top="2"
fit-margin-left="2"
fit-margin-right="2"
fit-margin-bottom="2" />
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title />
<cc:license
rdf:resource="http://creativecommons.org/licenses/by-sa/4.0/" />
</cc:Work>
<cc:License
rdf:about="http://creativecommons.org/licenses/by-sa/4.0/">
<cc:permits
rdf:resource="http://creativecommons.org/ns#Reproduction" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#Distribution" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#Notice" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#Attribution" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#DerivativeWorks" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#ShareAlike" />
</cc:License>
</rdf:RDF>
</metadata>
<g
inkscape:groupmode="layer"
id="layer4"
inkscape:label="Layer 3"
transform="translate(-32.802493,-152.21191)" />
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-32.802493,-152.21191)">
<rect
style="opacity:1;fill:#fcb23c;fill-opacity:1;stroke:#895502;stroke-width:0.500003;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect11897"
width="53.437809"
height="18.719559"
x="-102.86118"
y="166.15401"
rx="9.1421146"
ry="9.740695"
transform="matrix(0.70886122,-0.70534797,0.70886122,0.70534797,0,0)" />
<path
style="fill:none;stroke:#000000;stroke-width:0.264583px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 58.856488,191.81014 7.489277,-6.3578"
id="path11914"
inkscape:connector-curvature="0" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:7.43286px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#42b8eb;fill-opacity:1;stroke:none;stroke-width:0.185822;"
x="35.292469"
y="179.56654"
id="text11946"><tspan
sodipodi:role="line"
id="tspan11944"
x="35.292469"
y="179.56654"
style="fill:#42b8eb;fill-opacity:1;stroke-width:0.185822;">d</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:5.70015px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#42b8eb;fill-opacity:1;stroke:none;stroke-width:0.142504;"
x="39.553581"
y="181.05975"
id="text11950"><tspan
sodipodi:role="line"
id="tspan11948"
x="39.553581"
y="181.05975"
style="fill:#42b8eb;fill-opacity:1;stroke-width:0.142504;">in</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:6.7155px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#42b8eb;fill-opacity:1;stroke:none;stroke-width:0.167887;"
x="52.3652"
y="207.22546"
id="text11946-8"><tspan
sodipodi:role="line"
id="tspan11944-3"
x="52.3652"
y="207.22546"
style="fill:#42b8eb;fill-opacity:1;stroke-width:0.167887;">d</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:5.47403px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#42b8eb;fill-opacity:1;stroke:none;stroke-width:0.136851;"
x="56.137684"
y="208.51466"
id="text12005"><tspan
sodipodi:role="line"
id="tspan12003"
x="56.137684"
y="208.51466"
style="fill:#42b8eb;fill-opacity:1;stroke-width:0.136851;">out</tspan></text>
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#TriangleOutL)"
d="m 45.5227,178.84194 v 6.64794"
id="path12007"
inkscape:connector-curvature="0" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#TriangleOutL-1)"
d="m 45.370692,201.20369 v -6.64794"
id="path12007-9"
inkscape:connector-curvature="0" />
<path
style="display:inline;fill:none;stroke:#42b8eb;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:3, 0.50000000000000000;stroke-dashoffset:0;stroke-opacity:1"
d="m 48.741227,189.0913 0.0606,13.3891"
id="path11926-6-4"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc"
inkscape:transform-center-x="-15.577344"
inkscape:transform-center-y="-0.72760416" />
<path
style="display:inline;fill:none;stroke:#42b8eb;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:3, 0.50000000000000000;stroke-dashoffset:0;stroke-opacity:1"
d="m 67.361279,189.91812 0.0606,13.3891"
id="path11926-6"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-start:url(#TriangleInL);marker-end:url(#marker15132)"
d="M 50.528621,201.7059 H 65.498225"
id="path14918"
inkscape:connector-curvature="0" />
</g>
<g
inkscape:groupmode="layer"
id="layer2"
inkscape:label="Layer 2"
style="display:inline"
transform="translate(-32.802493,-152.21191)">
<circle
id="path11789"
cx="58.090473"
cy="189.78015"
style="opacity:1;fill:#cccccc;fill-opacity:1;stroke:#474747;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
r="9.3294096" />
<path
style="display:inline;fill:none;stroke:#42b8eb;stroke-width:0.315507;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-start:url(#marker16639);marker-end:url(#marker16887)"
d="m 65.999984,181.56305 21.689609,-21.6896"
id="path16496"
inkscape:connector-curvature="0" />
</g>
<g
inkscape:groupmode="layer"
id="layer6"
inkscape:label="Layer 5"
transform="translate(-32.802493,-152.21191)">
<path
style="fill:none;stroke:#474747;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:6, 0.5;stroke-dashoffset:0;stroke-opacity:1"
d="m 58.856488,191.81014 7.031297,-7.0313"
id="path11918"
inkscape:connector-curvature="0" />
<path
style="fill:none;stroke:#474747;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:6, 0.5;stroke-dashoffset:0;stroke-opacity:1"
d="m 55.35431,188.30796 6.84272,-6.84272"
id="path11924"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:3, 0.50000000000000000;stroke-dashoffset:0;stroke-opacity:1"
d="m 57.267038,192.36915 -13.389102,0.0606"
id="path11926"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#42b8eb;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:3, 0.50000000000000000;stroke-dashoffset:0;stroke-opacity:1"
d="m 57.295309,187.484 -13.389102,0.0606"
id="path11926-1"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<ellipse
style="opacity:1;fill:#fcb23c;fill-opacity:1;stroke:none;stroke-width:0.173017;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
id="path17442"
cx="76.271362"
cy="172.67838"
rx="2.2986085"
ry="2.5548441"
transform="matrix(0.99989217,0.01468465,-0.01287892,0.99991706,0,0)" />
</g>
<g
inkscape:groupmode="layer"
id="layer5"
inkscape:label="Layer 4"
transform="translate(-32.802493,-152.21191)">
<circle
style="opacity:0.954;fill:#fcb23c;fill-opacity:1;stroke:#895502;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="path11903"
r="2.5054057"
cy="189.87048"
cx="57.29398" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:6.59101px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#42b8eb;fill-opacity:1;stroke:none;stroke-width:0.164775;"
x="72.893173"
y="175.37985"
id="text17183"><tspan
sodipodi:role="line"
id="tspan17181"
x="72.893173"
y="175.37985"
style="fill:#42b8eb;fill-opacity:1;stroke-width:0.164775;">L</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.264583"
x="4.1010418"
y="136.66249"
id="text19772" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 16 KiB

@@ -0,0 +1,355 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="91"
height="305"
viewBox="0 0 24.077083 80.697919"
version="1.1"
id="svg8"
inkscape:version="1.0.2 (1.0.2+r75+1)"
sodipodi:docname="color_code_multiplier.svg">
<defs
id="defs2" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="2.8284271"
inkscape:cx="-81.117312"
inkscape:cy="359.88818"
inkscape:document-units="mm"
inkscape:current-layer="layer1"
showgrid="false"
inkscape:snap-global="false"
inkscape:window-width="2560"
inkscape:window-height="1371"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:document-rotation="0"
units="px"
fit-margin-top="0"
fit-margin-left="0"
fit-margin-right="0"
fit-margin-bottom="0" />
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
<cc:license
rdf:resource="http://creativecommons.org/licenses/by-sa/4.0/" />
</cc:Work>
<cc:License
rdf:about="http://creativecommons.org/licenses/by-sa/4.0/">
<cc:permits
rdf:resource="http://creativecommons.org/ns#Reproduction" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#Distribution" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#Notice" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#Attribution" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#DerivativeWorks" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#ShareAlike" />
</cc:License>
</rdf:RDF>
</metadata>
<g
inkscape:groupmode="layer"
id="layer2"
inkscape:label="Layer 2"
transform="translate(-95.405914,-88.418556)">
<rect
style="opacity:1;fill:#0b0000;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect1011"
width="23.821617"
height="80.68676"
x="95.405914"
y="88.418556" />
</g>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-95.405914,-88.418556)">
<rect
style="opacity:1;fill:#643234;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828"
width="22.753521"
height="6.6159968"
x="95.9683"
y="95.725464" />
<rect
style="opacity:1;fill:#ff0000;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3"
width="22.753521"
height="6.6159968"
x="95.9683"
y="102.34146" />
<rect
style="opacity:1;fill:#fc6604;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6"
width="22.753521"
height="6.6159968"
x="95.968292"
y="108.95746" />
<rect
style="opacity:1;fill:#fcfe04;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7"
width="22.753521"
height="6.6159968"
x="95.968292"
y="115.57346" />
<rect
style="opacity:1;fill:#34ce34;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5"
width="22.753521"
height="6.6159968"
x="95.968292"
y="122.18946" />
<rect
style="opacity:1;fill:#6466fc;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-3"
width="22.753521"
height="6.6159968"
x="95.968292"
y="128.80545" />
<rect
style="opacity:1;fill:#949294;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-3-5"
width="22.753521"
height="6.6159968"
x="95.968292"
y="142.03745" />
<rect
style="opacity:1;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-3-5-6"
width="22.753521"
height="6.6159968"
x="95.9683"
y="148.65344" />
<rect
style="opacity:1;fill:#cc9a34;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-3-5-9"
width="22.753521"
height="6.6159968"
x="95.9683"
y="155.26944" />
<rect
style="opacity:1;fill:#cccecc;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-3-5-1"
width="22.753521"
height="6.6159968"
x="95.9683"
y="161.88544" />
<rect
style="opacity:1;fill:#cc66fc;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-2"
width="22.753521"
height="6.6159968"
x="95.968292"
y="135.42145" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="97.585678"
y="160.1035"
id="text1054-6-1-8-2"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-4-0"
x="97.585678"
y="160.1035"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">x 0.1</tspan></text>
<flowRoot
xml:space="preserve"
id="flowRoot1521"
style="font-style:normal;font-weight:normal;font-size:40px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none"><flowRegion
id="flowRegion1523"><rect
id="rect1525"
width="205.5"
height="371"
x="314"
y="319.01968" /></flowRegion><flowPara
id="flowPara1527" /></flowRoot>
</g>
<g
inkscape:groupmode="layer"
id="layer3"
inkscape:label="Layer 3"
transform="translate(-95.405914,-88.418556)">
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="97.308388"
y="100.41052"
id="text1054-6-1"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8"
x="97.308388"
y="100.41052"
style="fill:#ffffff;fill-opacity:1;stroke-width:0.113757">x 10</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.37649px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.109412"
x="100.46444"
y="135.17349"
id="text1054-0-2-8-3"
transform="scale(0.9618037,1.0397132)" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.264583"
x="119.98854"
y="166.49428"
id="text1377" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="97.501625"
y="133.55063"
id="text1054-6-1-5"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-0"
x="97.501625"
y="133.55063"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">x 1M</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="97.269073"
y="127.28316"
id="text1054-6-1-5-3"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-0-6"
x="97.269073"
y="127.28316"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">x 100k</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="97.666641"
y="146.92744"
id="text1054-6-1-5-1"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-0-0"
x="97.666641"
y="146.92744"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">x 100M</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="97.644554"
y="140.40274"
id="text1054-6-1-5-1-6"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-0-0-3"
x="97.644554"
y="140.40274"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">x 10M</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="97.610374"
y="153.30145"
id="text1054-6-1-5-5"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-0-5"
x="97.610374"
y="153.30145"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">x 1G</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="97.776306"
y="166.76157"
id="text1054-6-1-8-2-4"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-4-0-7"
x="97.776306"
y="166.76157"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">x 0.01</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="97.420952"
y="120.49439"
id="text1054-6-1-5-3-6"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-0-6-5"
x="97.420952"
y="120.49439"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">x 10k</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="97.431282"
y="113.65575"
id="text1054-6-1-5-3-6-6"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-0-6-5-9"
x="97.431282"
y="113.65575"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">x 1k</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="97.494598"
y="107.00489"
id="text1054-6-1-5-3-6-6-7"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-0-6-5-9-4"
x="97.494598"
y="107.00489"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">x 100</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="97.452835"
y="93.73658"
id="text1054-6-1-52"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-5"
x="97.452835"
y="93.73658"
style="fill:#ffffff;fill-opacity:1;stroke-width:0.113757">x 1</tspan></text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 14 KiB

@@ -0,0 +1,303 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="91"
height="305"
viewBox="0 0 24.077083 80.697919"
version="1.1"
id="svg8"
inkscape:version="1.0.2 (1.0.2+r75+1)"
sodipodi:docname="color_code_tolerance.svg">
<defs
id="defs2" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="2"
inkscape:cx="-96.988892"
inkscape:cy="252.67475"
inkscape:document-units="mm"
inkscape:current-layer="layer3"
showgrid="false"
inkscape:snap-global="false"
inkscape:window-width="2560"
inkscape:window-height="1371"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:document-rotation="0"
units="px"
fit-margin-top="0"
fit-margin-left="0"
fit-margin-right="0"
fit-margin-bottom="0" />
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
<cc:license
rdf:resource="http://creativecommons.org/licenses/by-sa/4.0/" />
</cc:Work>
<cc:License
rdf:about="http://creativecommons.org/licenses/by-sa/4.0/">
<cc:permits
rdf:resource="http://creativecommons.org/ns#Reproduction" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#Distribution" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#Notice" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#Attribution" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#DerivativeWorks" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#ShareAlike" />
</cc:License>
</rdf:RDF>
</metadata>
<g
inkscape:groupmode="layer"
id="layer2"
inkscape:label="Layer 2"
transform="translate(-95.405914,-88.418556)">
<rect
style="opacity:1;fill:#0b0000;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect1011"
width="23.821617"
height="80.68676"
x="95.405914"
y="88.418556" />
</g>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-95.405914,-88.418556)">
<rect
style="opacity:1;fill:#643234;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828"
width="22.753521"
height="6.6159968"
x="95.9683"
y="95.725464" />
<rect
style="opacity:1;fill:#ff0000;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3"
width="22.753521"
height="6.6159968"
x="95.9683"
y="102.34146" />
<rect
style="opacity:1;fill:#fc6604;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6"
width="22.753521"
height="6.6159968"
x="95.968292"
y="108.95746" />
<rect
style="opacity:1;fill:#fcfe04;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7"
width="22.753521"
height="6.6159968"
x="95.968292"
y="115.57346" />
<rect
style="opacity:1;fill:#34ce34;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5"
width="22.753521"
height="6.6159968"
x="95.968292"
y="122.18946" />
<rect
style="opacity:1;fill:#6466fc;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-3"
width="22.753521"
height="6.6159968"
x="95.968292"
y="128.80545" />
<rect
style="opacity:1;fill:#949294;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-3-5"
width="22.753521"
height="6.6159968"
x="95.968292"
y="142.03745" />
<rect
style="opacity:1;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-3-5-6"
width="22.753521"
height="6.6159968"
x="95.9683"
y="148.65344" />
<rect
style="opacity:1;fill:#cc9a34;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-3-5-9"
width="22.753521"
height="6.6159968"
x="95.9683"
y="155.26944" />
<rect
style="opacity:1;fill:#cccecc;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-3-5-1"
width="22.753521"
height="6.6159968"
x="95.9683"
y="161.88544" />
<rect
style="opacity:1;fill:#cc66fc;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-2"
width="22.753521"
height="6.6159968"
x="95.968292"
y="135.42145" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="98.296745"
y="160.07043"
id="text1054-6-1-8-2"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-4-0"
x="98.296745"
y="160.07043"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">± 5%</tspan></text>
<flowRoot
xml:space="preserve"
id="flowRoot1521"
style="font-style:normal;font-weight:normal;font-size:40px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none"><flowRegion
id="flowRegion1523"><rect
id="rect1525"
width="205.5"
height="371"
x="314"
y="319.01968" /></flowRegion><flowPara
id="flowPara1527" /></flowRoot>
</g>
<g
inkscape:groupmode="layer"
id="layer3"
inkscape:label="Layer 3"
transform="translate(-95.405914,-88.418556)">
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="97.936775"
y="100.41052"
id="text1054-6-1"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8"
x="97.936775"
y="100.41052"
style="fill:#ffffff;fill-opacity:1;stroke-width:0.113757">± 1%</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.37649px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.109412"
x="100.46444"
y="135.17349"
id="text1054-0-2-8-3"
transform="scale(0.9618037,1.0397132)" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.264583"
x="119.98854"
y="166.49428"
id="text1377" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="98.046356"
y="107.17678"
id="text1054-6-1-8"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-4"
x="98.046356"
y="107.17678"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">± 2%</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="97.501625"
y="133.55063"
id="text1054-6-1-5"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-0"
x="97.501625"
y="133.55063"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">± 0.25%</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="97.269073"
y="127.65733"
id="text1054-6-1-5-3"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-0-6"
x="97.269073"
y="127.65733"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">± 0.5%</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="97.666641"
y="146.92744"
id="text1054-6-1-5-1"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-0-0"
x="97.666641"
y="146.92744"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">± 0.05%</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="97.644554"
y="140.65999"
id="text1054-6-1-5-1-6"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-0-0-3"
x="97.644554"
y="140.65999"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">± 0.10%</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="98.296753"
y="166.57178"
id="text1054-6-1-8-6"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-4-1"
x="98.296753"
y="166.57178"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">± 10%</tspan></text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 12 KiB

@@ -0,0 +1,367 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="91"
height="256"
viewBox="0 0 24.077082 67.733332"
version="1.1"
id="svg8"
inkscape:version="1.0.2 (1.0.2+r75+1)"
sodipodi:docname="color_code_value.svg">
<defs
id="defs2" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="0.70710678"
inkscape:cx="-650.9693"
inkscape:cy="462.00772"
inkscape:document-units="mm"
inkscape:current-layer="layer3"
showgrid="false"
inkscape:snap-global="false"
inkscape:window-width="2560"
inkscape:window-height="1371"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:document-rotation="0"
fit-margin-top="0"
fit-margin-left="0"
fit-margin-right="0"
fit-margin-bottom="0"
units="px" />
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
<cc:license
rdf:resource="http://creativecommons.org/licenses/by-sa/4.0/" />
</cc:Work>
<cc:License
rdf:about="http://creativecommons.org/licenses/by-sa/4.0/">
<cc:permits
rdf:resource="http://creativecommons.org/ns#Reproduction" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#Distribution" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#Notice" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#Attribution" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#DerivativeWorks" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#ShareAlike" />
</cc:License>
</rdf:RDF>
</metadata>
<g
inkscape:groupmode="layer"
id="layer2"
inkscape:label="Layer 2"
transform="translate(-95.405914,-88.418556)">
<rect
style="opacity:1;fill:#0b0000;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect1011"
width="23.821617"
height="67.497009"
x="95.405914"
y="88.418556" />
</g>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-95.405914,-88.418556)">
<rect
style="opacity:1;fill:#643234;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828"
width="22.753521"
height="6.6159968"
x="95.9683"
y="95.725464" />
<rect
style="opacity:1;fill:#ff0000;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3"
width="22.753521"
height="6.6159968"
x="95.9683"
y="102.34146" />
<rect
style="opacity:1;fill:#fc6604;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6"
width="22.753521"
height="6.6159968"
x="95.968292"
y="108.95746" />
<rect
style="opacity:1;fill:#fcfe04;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7"
width="22.753521"
height="6.6159968"
x="95.968292"
y="115.57346" />
<rect
style="opacity:1;fill:#34ce34;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5"
width="22.753521"
height="6.6159968"
x="95.968292"
y="122.18946" />
<rect
style="opacity:1;fill:#6466fc;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-3"
width="22.753521"
height="6.6159968"
x="95.968292"
y="128.80545" />
<rect
style="opacity:1;fill:#949294;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-3-5"
width="22.753521"
height="6.6159968"
x="95.968292"
y="142.03745" />
<rect
style="opacity:1;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-3-5-6"
width="22.753521"
height="6.6159968"
x="95.9683"
y="148.65344" />
<rect
style="opacity:1;fill:#cc66fc;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-2"
width="22.753521"
height="6.6159968"
x="95.968292"
y="135.42145" />
<flowRoot
xml:space="preserve"
id="flowRoot1521"
style="font-style:normal;font-weight:normal;font-size:40px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none"><flowRegion
id="flowRegion1523"><rect
id="rect1525"
width="205.5"
height="371"
x="314"
y="319.01968" /></flowRegion><flowPara
id="flowPara1527" /></flowRoot>
</g>
<g
inkscape:groupmode="layer"
id="layer3"
inkscape:label="Layer 3"
transform="translate(-95.405914,-88.418556)">
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="105.46709"
y="93.581787"
id="text1054-6-1"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8"
x="105.46709"
y="93.581787"
style="fill:#ffffff;fill-opacity:1;stroke-width:0.113757">0</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.37649px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.109412"
x="100.46444"
y="135.17349"
id="text1054-0-2-8-3"
transform="scale(0.9618037,1.0397132)" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.264583"
x="119.98854"
y="166.49428"
id="text1377" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="105.48313"
y="100.62868"
id="text1054-6-1-8"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-4"
x="105.48313"
y="100.62868"
style="fill:#ffffff;fill-opacity:1;stroke-width:0.113757">1</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="105.57397"
y="107.07978"
id="text1054-6-1-8-4"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-4-7"
x="105.57397"
y="107.07978"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">2</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="105.48799"
y="113.70467"
id="text1054-6-1-8-4-4"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-4-7-4"
x="105.48799"
y="113.70467"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">3</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="105.3389"
y="120.44639"
id="text1054-6-1-8-4-4-3"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-4-7-4-0"
x="105.3389"
y="120.44639"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">4</tspan><tspan
sodipodi:role="line"
x="105.3389"
y="126.13425"
id="tspan2587" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="105.33259"
y="126.94205"
id="text1054-6-1-8-4-4-3-3"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-4-7-4-0-1"
x="105.33259"
y="126.94205"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">5</tspan><tspan
sodipodi:role="line"
x="105.33259"
y="132.62991"
id="tspan2641" /><tspan
sodipodi:role="line"
x="105.33259"
y="138.31778"
id="tspan2587-4" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="105.49033"
y="133.45929"
id="text1054-6-1-8-4-4-3-9"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-4-7-4-0-2"
x="105.49033"
y="133.45929"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">6</tspan><tspan
sodipodi:role="line"
x="105.49033"
y="139.14716"
id="tspan2653" /><tspan
sodipodi:role="line"
x="105.49033"
y="144.83502"
id="tspan2587-0" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="105.39677"
y="140.38158"
id="text1054-6-1-8-4-4-3-6"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-4-7-4-0-8"
x="105.39677"
y="140.38158"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">7</tspan><tspan
sodipodi:role="line"
x="105.39677"
y="146.06944"
id="tspan2665" /><tspan
sodipodi:role="line"
x="105.39677"
y="151.75731"
id="tspan2587-9" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="105.38578"
y="146.98619"
id="text1054-6-1-8-4-4-3-6-2"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-4-7-4-0-8-6"
x="105.38578"
y="146.98619"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">8</tspan><tspan
sodipodi:role="line"
x="105.38578"
y="152.67406"
id="tspan2691" /><tspan
sodipodi:role="line"
x="105.38578"
y="158.36192"
id="tspan2665-6" /><tspan
sodipodi:role="line"
x="105.38578"
y="164.04977"
id="tspan2587-9-4" /></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="105.51141"
y="153.46626"
id="text1054-6-1-8-4-4-3-6-2-9"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-4-7-4-0-8-6-5"
x="105.51141"
y="153.46626"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">9</tspan><tspan
sodipodi:role="line"
x="105.51141"
y="159.15413"
id="tspan2691-0" /><tspan
sodipodi:role="line"
x="105.51141"
y="164.842"
id="tspan2665-6-4" /><tspan
sodipodi:role="line"
x="105.51141"
y="170.52985"
id="tspan2587-9-4-8" /></text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 14 KiB

@@ -0,0 +1,341 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="91"
height="305"
viewBox="0 0 24.077082 80.697919"
version="1.1"
id="svg8"
inkscape:version="1.0.2 (1.0.2+r75+1)"
sodipodi:docname="color_code_value_and_name.svg">
<defs
id="defs2" />
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="2"
inkscape:cx="-36.896785"
inkscape:cy="167.49281"
inkscape:document-units="mm"
inkscape:current-layer="layer3"
showgrid="false"
inkscape:snap-global="false"
inkscape:window-width="2560"
inkscape:window-height="1371"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:document-rotation="0"
fit-margin-top="0"
fit-margin-left="0"
fit-margin-right="0"
fit-margin-bottom="0"
units="px" />
<metadata
id="metadata5">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
<cc:license
rdf:resource="http://creativecommons.org/licenses/by-sa/4.0/" />
</cc:Work>
<cc:License
rdf:about="http://creativecommons.org/licenses/by-sa/4.0/">
<cc:permits
rdf:resource="http://creativecommons.org/ns#Reproduction" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#Distribution" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#Notice" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#Attribution" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#DerivativeWorks" />
<cc:requires
rdf:resource="http://creativecommons.org/ns#ShareAlike" />
</cc:License>
</rdf:RDF>
</metadata>
<g
inkscape:groupmode="layer"
id="layer2"
inkscape:label="Layer 2"
transform="translate(-95.405914,-88.418556)">
<rect
style="opacity:1;fill:#0b0000;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect1011"
width="23.821617"
height="80.68676"
x="95.405914"
y="88.418556" />
</g>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-95.405914,-88.418556)">
<image
y="89.113091"
x="95.438988"
id="image823"
xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFoAAAEYCAYAAADcT+HRAAAABHNCSVQICAgIfAhkiAAAB41JREFU eJztnU9u4zYUxmlDR8myi0GgAj1JkAMERheDrnuErAMvBm4OUPQks1CNHsBHEeIuLMoMTVlyzPe9 J+r7AcFkRP+hfnz6zFLseOWcOzoizlq7A0uBokFQNAiKBkHRICgaBEWDKFL04XDQ7sIFlXYHcmJR cMixtJ/D4aDeh/hHJDriyrJeaShEq0qjuixWtJhozRO2KLrIWYdFxEQfDgf38PDAfO5YuS4/cuIl D/1ditSgIt53CiKiySXMaBAUDYKiQVA0CIoGQdEgKBpEvx798lhr9qNY3veNc44VDYOiQVA0CIoG QdEgKBoERYOY7b6OP//5270+PV8cC4nbNZmd6FhmeDwl3ors2UXH69OzGXm3ICI6rrqhKlwSIqJf n557uZYuX03EosPLpuQTs8vouSIm2lcz8/lEv68j53p0HBk5IyQ1cP61Lc6j/Xq0iGhyhgv/YCga BEWDoGgQFA2CokFQNIh+Ht2uZ7c0PQuqj9Y5x4qGQdEgKBoERYOgaBBmpxrVR3sxE/Kf4J5b2zWx 05OOWFZ4PCXWHxtr18ZcdLTryoycnIiIjqtyqEqXhIjodl31ci1dvpqIRYeXTcknzGV0qYiJ9tXM fD4hsnoXR8YtEZIamHAKlzo+9FwLseX7xGVSYbhMCoaiQVA0CIoGQdEgKBoERYM4T55fFHtRMrvT H6xoEBQNgqJBUDSIxYiudrrLtUWK1paaoqi1UYuCPUVVdLupXLuZeIMBPCgy2w2ik7BWadWunTwg uZDZbrCperkaJ3UNrf7IbTfoZFPyiaIyeozwSkMjt92gqx5r+azVJ7EPQ3+JIk+s2rWfPhuG3ldD 9nm7gaEsLQk/oIvKaE0oGgRFg6BoEBQNgqJBUDSI8zz6g/NoCao159FQKBoERYOgaBCLEe0/lNTe X/Xd76BatxczpVimpZmUnZ5MZKgyh8RbkT276Gg/qizy0FEic4clOgntfIzRqHSZ7QYfVS/X0uXr nF5/5LYbdLIp+cTsMvoewisNjdx2g656rOWzVp9ErqPwEs0dIaEk/7ufiUydR2vEGpdJheEyKRiK BkHRICgaBEWDoGgQFA2inzz/9t83zX4UDL+UDApFg6BoEBQNYjGim8dG9f3NLtk1j42r9/XFsZBb 2zUxJ3qo8obE+2Nj7dqYi456X0PkoKNERHR8Etr5GKNR6SKi633dy7V0+Tqn1x+x6PCyKfmEuYyW JLzS0IiJ9tVjLZ+1+tTfBc95ScWX6C2XbEpCOIVLHR967rU+oGLE90lENDnjRS8qozWhaBAUDYKi QVA0CIoGQdEg+vXobz9+avajWJpOMSsaBEWDoGgQFA2iSNHvu8t7zu+7Knl8rC0X5u6C34O0rHso qqJfNq172Qz/P4Qvm/ZiMN531dXn5EJEdOpklo6I6LByUBUzFa2+iUWHPyFLkjUpKqOnolEEYqL9 iTCfT4h9GPpqQcoO58Njc2N0pPV3wZmlMvjBXmRGa0DRICgaBEWDoGgQFA2CokH0M/rfNXtRMO/d n6xoEBQNgqJBUDQIigYx28Xiele5JlpxrKNl0bDdt8XPGWvLxexExzLD4ynxkvJuYXbR0WzaL8tr Nu3FQKEGI7vo1IkQAdFh1Vi6dD1a/ZP5ZyS6k7EmWZPZZXQONApB5t/r6E6C+Xwmu4mwUiQqJxy8 cP6bGthr74uOtX67AfNUhprbDbBQNAiKBkHRICgaBEWDoGgQ/Qz/5y8/NPtRPKxoEBQNgqJBUDQI igZhdsH4+x/f3fZte3Es5JZ23xY/Z6wtF+ZEx7LC4ymx/thYuzbmomP7thWTs33bXgwkajCyi06d CBEQHVaNpUvXo9U/kejwJ2NNsibmMhqBRiGIiPYnwXw+k316F1bKVyonHJxwfpsauPB1x9pj0LHW bzdgnsrgB3+RGa0BRYOgaBAUDYKiQVA0CIoG0c+jj8ejclfKZLVaOedY0TAoGgRFg6BoEBQNwtxd 8BysVqvBWZSfBXhQs62iRMcSU+2x2GuDkpOiouN4PF6t5FQbqqKzi46raqzKlkJ20cfjsZeLuiy/ wmq16n8QiESHl21VsnPXY0aCojLaMiKifTVbymft/mRfvYsjAxkhKZGp6dy1dqk+cZlUGC6TgqFo EBQNgqJBUDQIigZB0SD69eh///pVsx/Fw4oGQdEgKBoERYOgaBCm74LXm+bT35tdPfl5Ux+Lwqzo lKwxgfHAWKKo6Gh2tblK9uT/MoWoqixXGZL8X6awq3u5FrNSC5kvU+hkU/KZojLaMjJfptBVs3Q+ zyn/83+ZQhAZ90RIaqDGXid8vP/dSnydv0zBSIdKww84MxoERYOgaBAUDYKiQVA0CIoGEXyVGr9M QYbTf5+wokFQNAiKBkHRICgahNm74M45Vz9+XlFs9tfXn6c+vn6sR18rN2ZFp2RcEzTl8fFAIFlU dDT7Bl7JnvzbDaKq0awiS+TfbrBverkaWWgVme0GnWxKPrOojNZEZrtBV83S+Tyn/M+/3SCIjHsi JDVQ115nyuPDdv87Kt7O2w2YpyL4AWVGg6BoEBQNgqJBUDQIigbRT++ILKxoEP8DO1ljF2WfaG4A AAAASUVORK5CYII= "
style="opacity:0.379;image-rendering:optimizeSpeed"
preserveAspectRatio="none"
height="74.083336"
width="23.8125" />
<rect
style="opacity:1;fill:#643234;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828"
width="22.753521"
height="6.6159968"
x="95.9683"
y="95.725464" />
<rect
style="opacity:1;fill:#ff0000;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3"
width="22.753521"
height="6.6159968"
x="95.9683"
y="102.34146" />
<rect
style="opacity:1;fill:#fc6604;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6"
width="22.753521"
height="6.6159968"
x="95.968292"
y="108.95746" />
<rect
style="opacity:1;fill:#fcfe04;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7"
width="22.753521"
height="6.6159968"
x="95.968292"
y="115.57346" />
<rect
style="opacity:1;fill:#34ce34;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5"
width="22.753521"
height="6.6159968"
x="95.968292"
y="122.18946" />
<rect
style="opacity:1;fill:#6466fc;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-3"
width="22.753521"
height="6.6159968"
x="95.968292"
y="128.80545" />
<rect
style="opacity:1;fill:#949294;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-3-5"
width="22.753521"
height="6.6159968"
x="95.968292"
y="142.03745" />
<rect
style="opacity:1;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-3-5-6"
width="22.753521"
height="6.6159968"
x="95.9683"
y="148.65344" />
<rect
style="opacity:1;fill:#cc9a34;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-3-5-9"
width="22.753521"
height="6.6159968"
x="95.9683"
y="155.26944" />
<rect
style="opacity:1;fill:#cccecc;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-3-5-1"
width="22.753521"
height="6.6159968"
x="95.9683"
y="161.88544" />
<rect
style="opacity:1;fill:#cc66fc;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-6-7-5-2"
width="22.753521"
height="6.6159968"
x="95.968292"
y="135.42145" />
<rect
style="opacity:1;fill:#0b0000;fill-opacity:1;stroke:none;stroke-width:0.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect828-3-7"
width="22.753521"
height="6.6159968"
x="95.968292"
y="89.109467" />
</g>
<g
inkscape:groupmode="layer"
id="layer3"
inkscape:label="Layer 3"
transform="translate(-95.405914,-88.418556)">
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="96.671974"
y="113.34624"
id="text1054"><tspan
sodipodi:role="line"
id="tspan1052"
x="96.671974"
y="113.34624"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">Orange 3</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="96.759331"
y="93.626266"
id="text1054-6"><tspan
sodipodi:role="line"
id="tspan1052-2"
x="96.759331"
y="93.626266"
style="fill:#ffffff;fill-opacity:1;stroke-width:0.113757">Black 0</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="96.580376"
y="100.4573"
id="text1054-6-1"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8"
x="96.580376"
y="100.4573"
style="fill:#ffffff;fill-opacity:1;stroke-width:0.113757">Brown 1</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="96.516182"
y="106.81372"
id="text1054-6-1-9"
inkscape:transform-center-x="0.72760416"
inkscape:transform-center-y="-5.0932292"><tspan
sodipodi:role="line"
id="tspan1052-2-8-2"
x="96.516182"
y="106.81372"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">Red 2</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.55029px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.113757"
x="96.560898"
y="120.41534"
id="text1054-0"><tspan
sodipodi:role="line"
id="tspan1052-23"
x="96.560898"
y="120.41534"
style="fill:#000000;fill-opacity:1;stroke-width:0.113757">Yellow 4</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.45977px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.111494"
x="98.495361"
y="124.21856"
id="text1054-0-2"
transform="scale(0.9801063,1.0202975)"><tspan
sodipodi:role="line"
id="tspan1052-23-2"
x="98.495361"
y="124.21856"
style="fill:#000000;fill-opacity:1;stroke-width:0.111494">Green 5</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.37649px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.109412"
x="100.40114"
y="128.81493"
id="text1054-0-2-8"
transform="scale(0.96180371,1.0397132)"><tspan
sodipodi:role="line"
id="tspan1052-23-2-9"
x="100.40114"
y="128.81493"
style="fill:#000000;fill-opacity:1;stroke-width:0.109412">Blue 6</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.37649px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.109412"
x="100.46444"
y="135.17349"
id="text1054-0-2-8-3"
transform="scale(0.9618037,1.0397132)"><tspan
sodipodi:role="line"
id="tspan1052-23-2-9-6"
x="100.46444"
y="135.17349"
style="fill:#000000;fill-opacity:1;stroke-width:0.109412">Violet 7</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.33364px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.108341"
x="101.27572"
y="139.79666"
id="text1054-0-2-8-3-1"
transform="scale(0.95238805,1.0499922)"><tspan
sodipodi:role="line"
id="tspan1052-23-2-9-6-2"
x="101.27572"
y="139.79666"
style="fill:#000000;fill-opacity:1;stroke-width:0.108341">Gray 8</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.38168px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.109542"
x="100.31073"
y="147.92805"
id="text1054-0-2-8-3-1-9"
transform="scale(0.96294441,1.0384815)"><tspan
sodipodi:role="line"
id="tspan1052-23-2-9-6-2-3"
x="100.31073"
y="147.92805"
style="fill:#000000;fill-opacity:1;stroke-width:0.109542">White 9</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.38168px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.109542"
x="100.3832"
y="154.18747"
id="text1054-0-2-8-3-1-9-1"
transform="scale(0.96294445,1.0384815)"><tspan
sodipodi:role="line"
id="tspan1052-23-2-9-6-2-3-9"
x="100.3832"
y="154.18747"
style="fill:#000000;fill-opacity:1;stroke-width:0.109542">Gold</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.264583"
x="119.98854"
y="166.49428"
id="text1377" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:4.38168px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.109542"
x="100.48061"
y="160.42957"
id="text1054-0-2-8-3-1-9-1-4"
transform="scale(0.96294445,1.0384815)"><tspan
sodipodi:role="line"
id="tspan1052-23-2-9-6-2-3-9-7"
x="100.48061"
y="160.42957"
style="fill:#000000;fill-opacity:1;stroke-width:0.109542">Silver</tspan></text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 16 KiB

@@ -0,0 +1,834 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
width="85mm"
height="44mm"
viewBox="0 0 85 44"
version="1.1"
id="svg19844"
inkscape:version="1.4 (e7c3feb1, 2024-10-09)"
sodipodi:docname="coupled_stripline.svg"
inkscape:export-filename="/Users/jeff/kicad_dev/kicad/bitmaps_png/png_other/stripline.png"
inkscape:export-xdpi="96"
inkscape:export-ydpi="96"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<defs
id="defs19838">
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL"
style="overflow:visible"
inkscape:isstock="true">
<path
id="path12142"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:stockid="Arrow2Lstart"
orient="auto"
refY="0"
refX="0"
id="Arrow2Lstart"
style="overflow:visible"
inkscape:isstock="true">
<path
id="path12027"
style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1"
d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z"
transform="matrix(1.1,0,0,1.1,1.1,0)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker23801"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
transform="scale(0.8)"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path23799" />
</marker>
<marker
inkscape:stockid="TriangleOutL"
orient="auto"
refY="0"
refX="0"
id="TriangleOutL"
style="overflow:visible"
inkscape:isstock="true"
inkscape:collect="always">
<path
id="path12151"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
transform="scale(0.8)" />
</marker>
<marker
style="overflow:visible"
id="DistanceEnd"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="DistanceEnd"
inkscape:isstock="true">
<g
id="g2301"
style="fill:#0081d5;fill-opacity:1;stroke:#0081d5;stroke-opacity:1">
<path
style="fill:#0081d5;fill-opacity:1;stroke:#0081d5;stroke-width:1.15;stroke-linecap:square;stroke-opacity:1"
d="M 0,0 H -2"
id="path2316" />
<path
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-opacity:1"
d="m 0,0 -13,4 4,-4 -4,-4 z"
id="path2312" />
<path
style="fill:#0081d5;fill-opacity:1;stroke:#0081d5;stroke-width:1;stroke-linecap:square;stroke-opacity:1"
d="M 0,-4 V 40"
id="path2314" />
</g>
</marker>
<marker
style="overflow:visible"
id="DistanceStart"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="DistanceStart"
inkscape:isstock="true">
<g
id="g2300"
style="fill:#0081d5;fill-opacity:1;stroke:#0081d5;stroke-opacity:1">
<path
style="fill:#0081d5;fill-opacity:1;stroke:#0081d5;stroke-width:1.15;stroke-linecap:square;stroke-opacity:1"
d="M 0,0 H 2"
id="path2306" />
<path
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-opacity:1"
d="M 0,0 13,4 9,0 13,-4 Z"
id="path2302" />
<path
style="fill:#0081d5;fill-opacity:1;stroke:#0081d5;stroke-width:1;stroke-linecap:square;stroke-opacity:1"
d="M 0,-4 V 40"
id="path2304" />
</g>
</marker>
<marker
inkscape:stockid="Arrow2Lend"
orient="auto"
refY="0"
refX="0"
id="marker21133"
style="overflow:visible"
inkscape:isstock="true">
<path
id="path21131"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1"
d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z"
transform="matrix(-1.1,0,0,-1.1,-1.1,0)" />
</marker>
<marker
inkscape:stockid="RazorWire"
id="RazorWire"
refX="0"
refY="0"
orient="auto"
style="overflow:visible"
inkscape:isstock="true">
<path
id="path12241"
transform="scale(0.8)"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:0.1pt;stroke-opacity:1"
d="m 0.02272727,-0.74009011 v 1.4375 L -7.7585227,3.0099099 H 10.678977 L 3.4914773,0.69740989 v -1.4375 L 10.741477,-2.8963401 H -7.7272727 Z" />
</marker>
<marker
inkscape:stockid="Arrow2Lend"
orient="auto"
refY="0"
refX="0"
id="Arrow2Lend"
style="overflow:visible"
inkscape:isstock="true">
<path
id="path12030"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:0.625;stroke-linejoin:round;stroke-opacity:1"
d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z"
transform="matrix(-1.1,0,0,-1.1,-1.1,0)" />
</marker>
<marker
inkscape:stockid="TriangleOutL"
orient="auto"
refY="0"
refX="0"
id="TriangleOutL-9"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path12151-0"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
transform="scale(0.8)" />
</marker>
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL-9"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path12142-6"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker23801-7"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
inkscape:connector-curvature="0"
transform="scale(0.8)"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path23799-7" />
</marker>
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL-9-7"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path12142-6-1"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker23801-7-2"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
inkscape:connector-curvature="0"
transform="scale(0.8)"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path23799-7-2" />
</marker>
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL-9-5"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path12142-6-0"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker23801-7-9"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
inkscape:connector-curvature="0"
transform="scale(0.8)"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path23799-7-0" />
</marker>
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL-9-5-0"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path12142-6-0-1"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker23801-7-9-3"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
inkscape:connector-curvature="0"
transform="scale(0.8)"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path23799-7-0-7" />
</marker>
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL-7"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path12142-5"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker23801-6"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
inkscape:connector-curvature="0"
transform="scale(0.8)"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path23799-5" />
</marker>
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL-7-1"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path12142-5-0"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker23801-6-6"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
inkscape:connector-curvature="0"
transform="scale(0.8)"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path23799-5-3" />
</marker>
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL-0"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path12142-61"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker23801-5"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
inkscape:connector-curvature="0"
transform="scale(0.8)"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path23799-54" />
</marker>
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL-74"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path12142-52"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker23801-54"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
inkscape:connector-curvature="0"
transform="scale(0.8)"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path23799-74" />
</marker>
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL-74-0"
style="overflow:visible"
inkscape:isstock="true">
<path
inkscape:connector-curvature="0"
id="path12142-52-7"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker23801-54-8"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
inkscape:connector-curvature="0"
transform="scale(0.8)"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path23799-74-6" />
</marker>
<marker
inkscape:stockid="TriangleInL"
orient="auto"
refY="0"
refX="0"
id="TriangleInL-8"
style="overflow:visible"
inkscape:isstock="true">
<path
id="path12142-8"
d="M 5.77,0 -2.88,5 V -5 Z"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
transform="scale(-0.8)" />
</marker>
<marker
inkscape:isstock="true"
style="overflow:visible"
id="marker23801-3"
refX="0"
refY="0"
orient="auto"
inkscape:stockid="TriangleOutL">
<path
transform="scale(0.8)"
style="fill:#0081d5;fill-opacity:1;fill-rule:evenodd;stroke:#0081d5;stroke-width:1pt;stroke-opacity:1"
d="M 5.77,0 -2.88,5 V -5 Z"
id="path23799-52" />
</marker>
</defs>
<sodipodi:namedview
id="base"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="0.80852013"
inkscape:cx="337.03552"
inkscape:cy="189.85303"
inkscape:document-units="mm"
inkscape:current-layer="layer8"
showgrid="false"
inkscape:window-width="1960"
inkscape:window-height="1178"
inkscape:window-x="0"
inkscape:window-y="44"
inkscape:window-maximized="0"
inkscape:snap-global="false"
showguides="false"
inkscape:document-rotation="0"
lock-margins="true"
fit-margin-top="2"
fit-margin-left="2"
fit-margin-right="2"
fit-margin-bottom="2"
inkscape:showpageshadow="2"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1" />
<metadata
id="metadata19841">
<rdf:RDF />
</metadata>
<g
inkscape:groupmode="layer"
id="layer9"
inkscape:label="Layer 4"
style="display:inline"
transform="translate(-50.901726,-151.02664)" />
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-50.901726,-151.02664)">
<path
style="fill:none;stroke:#895502;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 122.04879,192.51551 10.68381,-10.75397 -0.009,-2.92062"
id="path20805"
inkscape:connector-curvature="0"
sodipodi:nodetypes="ccc" />
<path
style="fill:none;stroke:#895502;stroke-width:0.619834;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 54.199347,190.45327 -0.0034,2.392 67.339143,-1.9e-4 v -2.39132"
id="path20803"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cccc" />
<path
style="fill:none;stroke:#895502;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="M 54.041006,164.19702 64.50364,153.58053"
id="path20805-1-9"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#895502;stroke-width:0.629986;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 64.326232,153.65354 68.633098,0.008"
id="path20805-1-4"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
</g>
<g
inkscape:groupmode="layer"
id="layer8"
inkscape:label="Layer 3"
transform="translate(-50.901726,-151.02664)">
<path
style="fill:#fcb23c;fill-opacity:1;stroke:#545454;stroke-width:0.529167;stroke-linecap:round"
d="m 54.195947,192.84527 67.339143,-1.9e-4 11.19751,-11.08354 0.11204,-2.74697 -78.682805,11.08537 z"
id="path2" />
<path
style="fill:#fcb23c;fill-opacity:1;stroke:#545454;stroke-width:0.529167;stroke-linecap:round"
d="m 54.040972,164.19705 10.462634,-10.61649 68.278984,-0.0652 0.0668,2.59461 -11.49568,10.89781 0.48952,-2.55692 z"
id="path1" />
<path
style="display:inline;fill:#cccccc;fill-opacity:1;stroke:none;stroke-width:0.264583px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 79.91759,167.00765 39.26361,1.66204 13.6126,-12.67526 -0.0702,22.84649 -10.60793,10.80566 z"
id="path20574"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cccccc" />
<rect
style="opacity:1;fill:#cccccc;fill-opacity:1;stroke:#474747;stroke-width:0.625544;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
id="rect20534"
width="67.191879"
height="23.092167"
x="54.161835"
y="167.00778" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:7.5037px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#0081d5;fill-opacity:1;stroke:none;stroke-width:0.187593"
x="61.715302"
y="186.69984"
id="text21059"><tspan
sodipodi:role="line"
id="tspan21057"
x="61.715302"
y="186.69984"
style="fill:#0081d5;fill-opacity:1;stroke-width:0.187593">T</tspan></text>
<path
style="fill:none;stroke:#895502;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 121.84323,164.45086 10.93939,-10.9355"
id="path20805-1"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:9.15486px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#0081d5;fill-opacity:1;stroke:none;stroke-width:0.228872"
x="56.627808"
y="179.02429"
id="text23789"><tspan
sodipodi:role="line"
id="tspan23787"
x="56.627808"
y="179.02429"
style="fill:#0081d5;fill-opacity:1;stroke-width:0.228872">H</tspan></text>
<path
style="fill:none;stroke:#0081d5;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-start:url(#TriangleInL);marker-end:url(#marker23801)"
d="M 56.546083,188.04342 V 169.08263"
id="path23791"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#0081d5;stroke-width:0.250923;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-start:url(#TriangleInL-8);marker-end:url(#marker23801-3)"
d="M 80.029497,181.46964 H 93.294174"
id="path23791-2"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc"
inkscape:transform-center-x="4.2335716"
inkscape:transform-center-y="-8.4721688" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:9.15486px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#0081d5;fill-opacity:1;stroke:none;stroke-width:0.228872"
x="87.574654"
y="162.95206"
id="text23789-9" />
<path
style="fill:none;stroke:#0081d5;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-start:url(#TriangleInL-7);marker-end:url(#marker23801-6)"
d="m 89.639803,162.80003 7.50755,-7.7658"
id="path23791-4"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:6.2411px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#0081d5;fill-opacity:1;stroke:none;stroke-width:0.156027"
x="87.845589"
y="159.39813"
id="text21059-1-3-2"><tspan
sodipodi:role="line"
id="tspan21057-1-0-2"
x="87.845589"
y="159.39813"
style="fill:#0081d5;fill-opacity:1;stroke-width:0.156027">L</tspan></text>
<path
style="fill:none;stroke:#474747;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 122.05054,190.09836 10.7941,-11.08379"
id="path20538-6"
inkscape:connector-curvature="0"
inkscape:transform-center-x="0.65481035"
inkscape:transform-center-y="7.4835468"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#474747;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 132.84464,179.01457 0.0187,-23.86743"
id="path20538-6-1"
inkscape:connector-curvature="0"
inkscape:transform-center-x="0.65481035"
inkscape:transform-center-y="7.4835468"
sodipodi:nodetypes="cc" />
<rect
style="opacity:1;fill:#fcb23c;fill-opacity:1;stroke:#895502;stroke-width:0.614626;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
id="rect6104"
width="67.207901"
height="2.1072214"
x="54.151272"
y="164.32817"
ry="0" />
<path
style="fill:none;stroke:#895502;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
d="m 122.05054,167.00938 10.79885,-10.89941 0.008,-2.19227"
id="path20805-3"
inkscape:connector-curvature="0"
sodipodi:nodetypes="ccc" />
<path
style="fill:none;stroke:#474747;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:3, 0.5;stroke-dashoffset:0;stroke-opacity:1"
d="m 78.447673,177.00008 9.624797,-9.8911"
id="path20538-6-8"
inkscape:connector-curvature="0"
inkscape:transform-center-x="0.65481035"
inkscape:transform-center-y="7.4835468"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#474747;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:3, 0.5;stroke-dashoffset:0;stroke-opacity:1"
d="m 78.425464,179.66243 9.624797,-9.8911"
id="path20538-6-8-0"
inkscape:connector-curvature="0"
inkscape:transform-center-x="0.65481035"
inkscape:transform-center-y="7.4835468"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#474747;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:3, 0.5;stroke-dashoffset:0;stroke-opacity:1"
d="m 71.760429,176.83271 9.624797,-9.8911"
id="path20538-6-8-0-3"
inkscape:connector-curvature="0"
inkscape:transform-center-x="0.65481035"
inkscape:transform-center-y="7.4835468"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#474747;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:3, 0.5;stroke-dashoffset:0;stroke-opacity:1"
d="m 87.88075,170.06683 0.07597,-3.05506"
id="path20538-6-8-0-6"
inkscape:connector-curvature="0"
inkscape:transform-center-x="0.65481035"
inkscape:transform-center-y="7.4835468"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#474747;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:3, 0.5;stroke-dashoffset:0;stroke-opacity:1"
d="m 111.28813,169.76512 0.076,-3.05506"
id="path20538-6-8-0-6-9"
inkscape:connector-curvature="0"
inkscape:transform-center-x="0.65481035"
inkscape:transform-center-y="7.4835468"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#0081d5;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:2.4, 0.3;stroke-dashoffset:0;stroke-opacity:1"
d="m 71.561356,179.69463 -5.224783,0.0131"
id="path23791-7"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#0081d5;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:2.4, 0.3;stroke-dashoffset:0;stroke-opacity:1"
d="m 71.51701,176.88556 -5.224783,0.0131"
id="path23791-7-3"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:7.5037px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#0081d5;fill-opacity:1;stroke:none;stroke-width:0.187593"
x="71.381172"
y="189.32043"
id="text21059-5"><tspan
sodipodi:role="line"
id="tspan21057-6"
x="71.381172"
y="189.32043"
style="fill:#0081d5;fill-opacity:1;stroke-width:0.187593">W</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:7.5037px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#0081d5;fill-opacity:1;stroke:none;stroke-width:0.187593"
x="84.089783"
y="188.25977"
id="text21059-5-7"><tspan
sodipodi:role="line"
id="tspan21057-6-1"
x="84.089783"
y="188.25977"
style="fill:#0081d5;fill-opacity:1;stroke-width:0.187593">S</tspan></text>
<path
style="fill:none;stroke:#0081d5;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:2.4, 0.3;stroke-dashoffset:0;stroke-opacity:1"
d="m 71.648638,179.5799 -0.0097,2.66362"
id="path23791-7-9"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#0081d5;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:2.4, 0.3;stroke-dashoffset:0;stroke-opacity:1"
d="m 78.468682,179.60109 -0.0097,2.61685"
id="path23791-7-9-3"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#0081d5;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:2.4, 0.3;stroke-dashoffset:0;stroke-opacity:1"
d="m 94.848919,179.80535 -0.0097,2.61685"
id="path23791-7-9-3-1"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#0081d5;stroke-width:0.25;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-start:url(#TriangleInL-74);marker-end:url(#marker23801-54)"
d="m 76.876847,181.51957 -3.624842,-0.0298"
id="path23791-43"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.264583"
x="58.652298"
y="173.61502"
id="text15381" />
</g>
<g
inkscape:groupmode="layer"
id="layer7"
inkscape:label="Layer 2"
transform="translate(-50.901726,-151.02664)">
<rect
style="opacity:1;fill:#fcb23c;fill-opacity:1;stroke:#895502;stroke-width:0.499178;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
id="rect20424"
width="6.6496596"
height="2.6584671"
x="71.743835"
y="176.97217" />
<path
style="fill:none;stroke:#474747;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:3, 0.5;stroke-dashoffset:0;stroke-opacity:1"
d="m 101.6132,176.95663 9.62485,-9.8911"
id="path20538-6-8-8"
inkscape:connector-curvature="0"
inkscape:transform-center-x="0.65481035"
inkscape:transform-center-y="7.4835468"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#474747;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:3, 0.5;stroke-dashoffset:0;stroke-opacity:1"
d="m 101.98778,179.66243 9.62485,-9.8911"
id="path20538-6-8-8-4"
inkscape:connector-curvature="0"
inkscape:transform-center-x="0.65481035"
inkscape:transform-center-y="7.4835468"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#474747;stroke-width:0.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:3, 0.5;stroke-dashoffset:0;stroke-opacity:1"
d="m 94.925946,176.78926 9.624824,-9.8911"
id="path20538-6-8-0-3-0"
inkscape:connector-curvature="0"
inkscape:transform-center-x="0.65481035"
inkscape:transform-center-y="7.4835468"
sodipodi:nodetypes="cc" />
<rect
style="fill:#fcb23c;fill-opacity:1;stroke:#895502;stroke-width:0.499178;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
id="rect20424-4"
width="6.6496596"
height="2.6584671"
x="94.909355"
y="176.92873" />
<path
style="fill:none;stroke:#0081d5;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#TriangleOutL)"
d="m 68.396624,187.21173 v -5.41497"
id="path21071"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
<path
style="fill:none;stroke:#0081d5;stroke-width:0.3;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#TriangleOutL-9)"
d="m 68.307853,169.42208 v 5.41497"
id="path21071-8"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 32 KiB

Some files were not shown because too many files have changed in this diff Show More