├── .gitignore
├── CONTRIBUTION.md
├── LICENSE.txt
├── README.md
├── case.go
├── go.mod
├── go.sum
├── kad.go
├── key.go
├── polygon.go
└── test
├── kad_test.go
├── key_test.go
└── output
├── stab_alps_size_switch.svg
├── stab_cherry_size_switch.svg
├── switch_types_switch.svg
├── usage_with_go_bottom.svg
├── usage_with_go_closed.svg
├── usage_with_go_open.svg
├── usage_with_go_switch.svg
├── usage_with_go_top.svg
├── usage_with_json_bottom.svg
├── usage_with_json_closed.svg
├── usage_with_json_open.svg
├── usage_with_json_switch.svg
└── usage_with_json_top.svg
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | usage
--------------------------------------------------------------------------------
/CONTRIBUTION.md:
--------------------------------------------------------------------------------
1 | Contributing
2 | ============
3 |
4 | KAD is a personal project which I try to maintain the the best of my ability on the side. I have had a hard time keeping up with the maintenance in recent years, mainly due to time, but I do intend to continue to maintain this project.
5 |
6 | Testing
7 | -------
8 |
9 | Please test your changes against the existing output to confirm compatibility.
10 |
11 | ```bash
12 | # simple output
13 | cd kad
14 | go test ./test
15 |
16 | # detailed output
17 | cd kad/test
18 | go test
19 | ```
20 |
21 | ```bash
22 | # use git status to check file changes
23 | git status
24 |
25 | # use git diff to check content changes
26 | git diff
27 | ```
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | KAD - Keyboard Automated Design
2 | ===============================
3 |
4 | [](https://godoc.org/github.com/swill/kad)
5 |
6 | KAD is the SVG CAD engine which powers the mechanical keyboard CAD generation site [builder.swillkb.com](http://builder.swillkb.com/). If you are going to use this library, you should probably review the documentation site for the published builder in order to understand what all the different features are. The documentation site is available and kept up to date at [builder-docs.swillkb.com](http://builder-docs.swillkb.com/).
7 |
8 | KAD is a Golang library to aid in the design of mechanical keyboard plates and cases. The keyboard layout uses the standard format developed by the [www.keyboard-layout-editor.com](http://www.keyboard-layout-editor.com/) project. KAD is designed to produce SVG files which can be taken to a laser or water cutting fabrication shop to be cut. KAD supports a huge number of features, including but not limited it; 4 switch types, 4 stabilizer types, 3 case types, rounded corners, padding, mount holes, usb cutouts, etc...
9 |
10 |
11 | ## Get Started
12 |
13 | ```
14 | $ go get github.com/swill/kad
15 | ```
16 |
17 | ### Installing DXF dependencies on MacOS
18 |
19 | You need [Homebrew](https://brew.sh/) installed.
20 |
21 | ```
22 | $ brew install pstoedit
23 | $ brew install caskformula/caskformula/inkscape --HEAD --branch-0.92
24 | ```
25 |
26 | ## Example
27 |
28 | ### Usage
29 |
30 | ``` go
31 | package main
32 |
33 | import (
34 | "encoding/json"
35 | "log"
36 |
37 | "github.com/swill/kad"
38 | )
39 |
40 | func main() {
41 | // you can define settings and the layout in JSON
42 | json_bytes := []byte(`{
43 | "switch-type":3,
44 | "stab-type":1,
45 | "layout":[
46 | ["Num Lock","/","*","-"],
47 | [{"f":3},"7\nHome","8\n↑","9\nPgUp",{"h":2}," "],
48 | ["4\n←","5","6\n→"],["1\nEnd","2\n↓","3\nPgDn",{"h":2},"Enter"],
49 | [{"w":2},"0\nIns",".\nDel"]
50 | ],
51 | "case": {
52 | "case-type":"sandwich",
53 | "mount-holes-num":4,
54 | "mount-holes-size":3,
55 | "mount-holes-edge":6
56 | },
57 | "top-padding":9,
58 | "left-padding":9,
59 | "right-padding":9,
60 | "bottom-padding":9
61 | }`)
62 |
63 | // create a new KAD instance
64 | cad := kad.New()
65 |
66 | // populate the 'cad' instance with the JSON contents
67 | err := json.Unmarshal(json_bytes, cad)
68 | if err != nil {
69 | log.Fatalf("Failed to parse json data into the KAD file\nError: %s", err.Error())
70 | }
71 |
72 | // and you can define settings via the KAD instance
73 | cad.Hash = "usage_example" // the name of the design
74 | cad.FileStore = kad.STORE_LOCAL // store the files locally
75 | cad.FileDirectory = "./" // the path location where the files will be saved
76 | cad.FileServePath = "/" // the url path for the 'results' (don't worry about this)
77 |
78 | // here are some more settings defined for this case
79 | cad.Case.UsbWidth = 12 // all dimension are in 'mm'
80 | cad.Fillet = 3 // 3mm radius on the rounded corners of the case
81 |
82 | // lets draw the SVG files now
83 | err = cad.Draw()
84 | if err != nil {
85 | log.Fatal("Failed to Draw the KAD file\nError: %s", err.Error())
86 | }
87 | }
88 | ```
89 | *For more usage examples, check the `./test/` folder.*
90 |
91 |
92 | ### Output
93 |
94 | | Top Layer | Switch Layer |
95 | |:---------:|:------------:|
96 | |  |  |
97 |
98 | | Closed Layer | Open Layer |
99 | |:------------:|:----------:|
100 | |  |  |
101 |
102 | | Bottom Layer |
103 | |:------------:|
104 | |  |
105 |
106 |
107 | ## License
108 |
109 | ```
110 | KAD generates SVG CAD files based on a keyboard layout described in JSON.
111 |
112 | Copyright (C) 2015-2016 Will Stevens (swill)
113 |
114 | This program is free software: you can redistribute it and/or modify
115 | it under the terms of the GNU Affero General Public License as
116 | published by the Free Software Foundation, either version 3 of the
117 | License, or (at your option) any later version.
118 |
119 | This program is distributed in the hope that it will be useful,
120 | but WITHOUT ANY WARRANTY; without even the implied warranty of
121 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
122 | GNU Affero General Public License for more details.
123 |
124 | You should have received a copy of the GNU Affero General Public License
125 | along with this program. If not, see .
126 | ```
127 |
128 |
--------------------------------------------------------------------------------
/case.go:
--------------------------------------------------------------------------------
1 | package kad
2 |
3 | import "math"
4 |
5 | const (
6 | CASE_NONE = ""
7 | CASE_POKER = "poker"
8 | CASE_SANDWICH = "sandwich"
9 | TOPLAYER = "top"
10 | SWITCHLAYER = "switch"
11 | BOTTOMLAYER = "bottom"
12 | CLOSEDLAYER = "closed"
13 | OPENLAYER = "open"
14 | TOPLAYER_NAME = "Top Layer"
15 | SWITCHLAYER_NAME = "Switch Layer"
16 | BOTTOMLAYER_NAME = "Bottom Layer"
17 | CLOSEDLAYER_NAME = "Closed Layer"
18 | OPENLAYER_NAME = "Open Layer"
19 | )
20 |
21 | type Case struct {
22 | Type string `json:"case-type"`
23 | HoleDiameter float64 `json:"mount-holes-size"`
24 | Holes int `json:"mount-holes-num"`
25 | EdgeWidth float64 `json:"mount-holes-edge"`
26 | LeftWidth float64
27 | RightWidth float64
28 | TopWidth float64
29 | BottomWidth float64
30 | Xholes int
31 | Yholes int
32 | RemovePokerSlots bool `json:"poker-slots-remove"`
33 | UsbLocation float64 `json:"usb-location"`
34 | UsbWidth float64 `json:"usb-width"`
35 | }
36 |
37 | func (k *KAD) InitCaseLayers() {
38 | // setup drawings details
39 | switch k.Case.Type {
40 | case CASE_NONE:
41 | k.Result.Plates = []string{SWITCHLAYER}
42 | k.Result.Details[SWITCHLAYER] = &ResultDetails{
43 | Name: SWITCHLAYER_NAME,
44 | }
45 | case CASE_POKER:
46 | k.Result.Plates = []string{SWITCHLAYER}
47 | k.Result.Details[SWITCHLAYER] = &ResultDetails{
48 | Name: SWITCHLAYER_NAME,
49 | }
50 | case CASE_SANDWICH:
51 | k.Result.Plates = []string{SWITCHLAYER, OPENLAYER, CLOSEDLAYER, TOPLAYER, BOTTOMLAYER}
52 | k.Result.Details[SWITCHLAYER] = &ResultDetails{
53 | Name: SWITCHLAYER_NAME,
54 | }
55 | k.Result.Details[OPENLAYER] = &ResultDetails{
56 | Name: OPENLAYER_NAME,
57 | }
58 | k.Result.Details[CLOSEDLAYER] = &ResultDetails{
59 | Name: CLOSEDLAYER_NAME,
60 | }
61 | k.Result.Details[TOPLAYER] = &ResultDetails{
62 | Name: TOPLAYER_NAME,
63 | }
64 | k.Result.Details[BOTTOMLAYER] = &ResultDetails{
65 | Name: BOTTOMLAYER_NAME,
66 | }
67 | }
68 | // initialize the layer objects
69 | for _, layer := range k.Result.Plates {
70 | k.Layers[layer] = &Layer{}
71 | }
72 | }
73 |
74 | func (k *KAD) InitCaseEdges() {
75 | // update the case edge width details
76 | k.Case.LeftWidth, k.Case.RightWidth, k.Case.TopWidth, k.Case.BottomWidth = k.LeftPad, k.RightPad, k.TopPad, k.BottomPad
77 | if k.LeftPad > k.Case.EdgeWidth && k.Case.EdgeWidth != 0 {
78 | k.Case.LeftWidth = k.Case.EdgeWidth
79 | }
80 | if k.RightPad > k.Case.EdgeWidth && k.Case.EdgeWidth != 0 {
81 | k.Case.RightWidth = k.Case.EdgeWidth
82 | }
83 | if k.TopPad > k.Case.EdgeWidth && k.Case.EdgeWidth != 0 {
84 | k.Case.TopWidth = k.Case.EdgeWidth
85 | }
86 | if k.BottomPad > k.Case.EdgeWidth && k.Case.EdgeWidth != 0 {
87 | k.Case.BottomWidth = k.Case.EdgeWidth
88 | }
89 | }
90 |
91 | // Draw the holes for the KAD based on the type of case selected.
92 | func (k *KAD) DrawHoles() {
93 | switch k.Case.Type {
94 | case CASE_POKER:
95 | points := k.GetPokerHoles()
96 | for i := range points {
97 | // create circle polygons with 5 segments per 1/4 turn
98 | k.Layers[SWITCHLAYER].CutPolys = append(k.Layers[SWITCHLAYER].CutPolys,
99 | CirclePolygon(points[i].X, points[i].Y, (k.Case.HoleDiameter/2)-k.Kerf, 5))
100 | }
101 | if !k.Case.RemovePokerSlots {
102 | // calculate polygon slots for poker layer
103 | depth := 6.0 - k.Kerf // total depth of the side slots in mm
104 | sc := k.Width/2 - (depth-k.Case.HoleDiameter/2)/2 // round rectangle center for slot
105 | slots := Path{{sc, 9.2}, {-sc, 9.2}}
106 | slots.Rel(k.CaseCenter) // make relative to the actual cad coords
107 | for _, center := range slots {
108 | slot := RoundRectanglePolygon(center.X, center.Y,
109 | depth+k.Case.HoleDiameter/2, k.Case.HoleDiameter-k.Kerf*2,
110 | k.Case.HoleDiameter/2-k.Kerf-.001, 5)
111 | k.Layers[SWITCHLAYER].CutPolys = append(k.Layers[SWITCHLAYER].CutPolys, slot)
112 | }
113 | }
114 | case CASE_SANDWICH:
115 | points := k.GetSandwichHoles()
116 | for _, layer := range k.Result.Plates {
117 | for i := range points {
118 | // create circle polygons with 5 segments per 1/4 turn
119 | k.Layers[layer].CutPolys = append(k.Layers[layer].CutPolys,
120 | CirclePolygon(points[i].X, points[i].Y, (k.Case.HoleDiameter/2)-k.Kerf, 5))
121 | }
122 | }
123 | }
124 | }
125 |
126 | // Get the Path for a Poker case hole placement.
127 | func (k *KAD) GetPokerHoles() Path {
128 | // the slots at {139, 9.2}, {-139, 9.2} are handled by the 'DrawHoles' function
129 | points := Path{{-117.3, -19.4}, {-14.3, 0}, {48, 37.9}, {117.55, -19.4}} // relative to center
130 | points.Rel(k.CaseCenter)
131 | return points
132 | }
133 |
134 | // Get the Path for a Sandwich case hole placement.
135 | func (k *KAD) GetSandwichHoles() Path {
136 | points := make(Path, 0)
137 | if k.Case.Holes >= 4 && math.Mod(float64(k.Case.Holes), 2) == 0 {
138 | switch {
139 | case k.Case.TopWidth == k.Case.EdgeWidth && k.Case.BottomWidth == k.Case.EdgeWidth &&
140 | k.Case.LeftWidth == k.Case.EdgeWidth && k.Case.RightWidth == k.Case.EdgeWidth:
141 |
142 | var x_len, y_len float64
143 | x_len = k.Width - k.Case.EdgeWidth - k.Kerf // x length to split
144 | y_len = k.Height - k.Case.EdgeWidth - k.Kerf // y length to split
145 | x_num := 0.0
146 | y_num := 0.0
147 | for i := 0.0; i < (float64(k.Case.Holes-4) / 2); i++ {
148 | switch {
149 | case x_len/(x_num+1) == y_len/(y_num+1):
150 | if x_len >= y_len { // if equal, add the hole to the longer side
151 | x_num += 1
152 | } else {
153 | y_num += 1
154 | }
155 | case x_len/(x_num+1) > y_len/(y_num+1):
156 | x_num += 1
157 | case x_len/(x_num+1) < y_len/(y_num+1):
158 | y_num += 1
159 | }
160 | }
161 | // the hole layout has been determined
162 | x_gap := (x_len - k.Kerf) / (x_num + 1)
163 | y_gap := (y_len - k.Kerf) / (y_num + 1)
164 | // start layout out the points
165 | p := &Point{X: k.DMZ + k.Case.EdgeWidth/2 + k.Kerf, Y: k.DMZ + k.Case.EdgeWidth/2 + k.Kerf} // start at top left // LeftPad, TopPad
166 | for i := 0.0; i < x_num+1; i++ {
167 | p.X += x_gap
168 | points = append(points, Point{p.X, p.Y})
169 | }
170 | for i := 0.0; i < y_num+1; i++ {
171 | p.Y += y_gap
172 | points = append(points, Point{p.X, p.Y})
173 | }
174 | for i := 0.0; i < x_num+1; i++ {
175 | p.X -= x_gap
176 | points = append(points, Point{p.X, p.Y})
177 | }
178 | for i := 0.0; i < y_num+1; i++ {
179 | p.Y -= y_gap
180 | points = append(points, Point{p.X, p.Y})
181 | }
182 | case k.Case.TopWidth == k.Case.EdgeWidth && k.Case.BottomWidth == k.Case.EdgeWidth:
183 | var x_len, x_num float64
184 | x_len = k.Width - k.Case.EdgeWidth - k.Kerf // x length to split
185 | x_num = float64(k.Case.Holes-4) / 2
186 |
187 | // the hole layout has been determined
188 | x_gap := (x_len - k.Kerf) / (x_num + 1)
189 | // start layout out the points
190 | p := &Point{X: k.DMZ + k.Case.EdgeWidth/2 + k.Kerf, Y: k.DMZ + k.Case.EdgeWidth/2 + k.Kerf} // start at top left
191 | points = append(points, Point{p.X, p.Y})
192 | for i := 0.0; i < x_num+1; i++ {
193 | p.X += x_gap
194 | points = append(points, Point{p.X, p.Y})
195 | }
196 | p = &Point{X: k.DMZ + k.Case.EdgeWidth/2 + k.Kerf, Y: k.DMZ + k.Height - k.Case.EdgeWidth/2 - k.Kerf} // start at bottom left
197 | points = append(points, Point{p.X, p.Y})
198 | for i := 0.0; i < x_num+1; i++ {
199 | p.X += x_gap
200 | points = append(points, Point{p.X, p.Y})
201 | }
202 | case k.Case.LeftWidth == k.Case.EdgeWidth && k.Case.RightWidth == k.Case.EdgeWidth:
203 | var y_len, y_num float64
204 | y_len = k.Height - k.Case.EdgeWidth - k.Kerf // y length to split
205 | y_num = float64(k.Case.Holes-4) / 2
206 |
207 | // the hole layout has been determined
208 | y_gap := (y_len - k.Kerf) / (y_num + 1)
209 | // start layout out the points
210 | p := &Point{X: k.DMZ + k.Case.EdgeWidth/2 + k.Kerf, Y: k.DMZ + k.Case.EdgeWidth/2 + k.Kerf} // start at top left
211 | points = append(points, Point{p.X, p.Y})
212 | for i := 0.0; i < y_num+2; i++ {
213 | p.Y += y_gap
214 | points = append(points, Point{p.X, p.Y})
215 | }
216 | p = &Point{X: k.DMZ + k.Width - k.Case.EdgeWidth/2 - k.Kerf, Y: k.DMZ + k.Case.EdgeWidth/2 + k.Kerf} // start at top right
217 | points = append(points, Point{p.X, p.Y})
218 | for i := 0.0; i < y_num+2; i++ {
219 | p.Y += y_gap
220 | points = append(points, Point{p.X, p.Y})
221 | }
222 | }
223 | }
224 | return points
225 | }
226 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/swill/kad
2 |
3 | go 1.16
4 |
5 | require (
6 | github.com/Knetic/govaluate v3.0.0+incompatible
7 | github.com/ctessum/geom v0.2.11 // indirect
8 | github.com/ncw/swift v1.0.53
9 | github.com/swill/go.clipper v0.0.0-20160727040122-3274bcc4839c
10 | github.com/swill/svgo v0.0.0-20150715025413-bc384fa1e849
11 | )
12 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
2 | github.com/Knetic/govaluate v3.0.0+incompatible h1:7o6+MAPhYTCF0+fdvoz1xDedhRb4f6s9Tn1Tt7/WTEg=
3 | github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=
4 | github.com/ajstarks/svgo v0.0.0-20180226025133-644b8db467af h1:wVe6/Ea46ZMeNkQjjBW6xcqyQA/j5e0D6GytH95g0gQ=
5 | github.com/ajstarks/svgo v0.0.0-20180226025133-644b8db467af/go.mod h1:K08gAheRH3/J6wwsYMMT4xOr94bZjxIelGM0+d/wbFw=
6 | github.com/ctessum/geom v0.2.11 h1:1f2FkeoAkreRflm0lidpY+jcKM/NBqVx1GRRvAeXryw=
7 | github.com/ctessum/geom v0.2.11/go.mod h1:1ukx8rYvMXVANqaPWfnx5PkT0B9CZpY+l+QpgVJMxZs=
8 | github.com/ctessum/polyclip-go v1.1.0 h1:TGMfwMynNykXwCZCxI+CHdjo/ZE9JThup/gmrgigGEE=
9 | github.com/ctessum/polyclip-go v1.1.0/go.mod h1:e/Lh1JOGyynZwLr0M4tZGIyx07wXw9T+pu6hFut+kFQ=
10 | github.com/go-gl/gl v0.0.0-20180407155706-68e253793080/go.mod h1:482civXOzJJCPzJ4ZOX/pwvXBWSnzD4OKMdH4ClKGbk=
11 | github.com/go-gl/glfw v0.0.0-20180426074136-46a8d530c326/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
12 | github.com/gogo/protobuf v1.3.0/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o=
13 | github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o=
14 | github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
15 | github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
16 | github.com/gonum/floats v0.0.0-20181209220543-c233463c7e82 h1:EvokxLQsaaQjcWVWSV38221VAK7qc2zhaO17bKys/18=
17 | github.com/gonum/floats v0.0.0-20181209220543-c233463c7e82/go.mod h1:PxC8OnwL11+aosOB5+iEPoV3picfs8tUpkVd0pDo+Kg=
18 | github.com/gonum/internal v0.0.0-20181124074243-f884aa714029 h1:8jtTdc+Nfj9AR+0soOeia9UZSvYBvETVHZrugUowJ7M=
19 | github.com/gonum/internal v0.0.0-20181124074243-f884aa714029/go.mod h1:Pu4dmpkhSyOzRwuXkOgAvijx4o+4YMUJJo9OvPYMkks=
20 | github.com/jonas-p/go-shp v0.1.2-0.20190401125246-9fd306ae10a6/go.mod h1:MRIhyxDQ6VVp0oYeD7yPGr5RSTNScUFKCDsI5DR7PtI=
21 | github.com/jung-kurt/gofpdf v1.0.0 h1:EroSdlP9BOoL5ssLYf3uLJXhCQMMM2fFxCJDKA3RhnA=
22 | github.com/jung-kurt/gofpdf v1.0.0/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes=
23 | github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00=
24 | github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
25 | github.com/llgcode/draw2d v0.0.0-20180817132918-587a55234ca2 h1:3xDkT1Tbsw2yDtKWUrROAlr15+dzp76kwucDvAPPnQo=
26 | github.com/llgcode/draw2d v0.0.0-20180817132918-587a55234ca2/go.mod h1:mVa0dA29Db2S4LVqDYLlsePDzRJLDfdhVZiI15uY0FA=
27 | github.com/llgcode/ps v0.0.0-20150911083025-f1443b32eedb/go.mod h1:1l8ky+Ew27CMX29uG+a2hNOKpeNYEQjjtiALiBlFQbY=
28 | github.com/ncw/swift v1.0.53 h1:luHjjTNtekIEvHg5KdAFIBaH7bWfNkefwFnpDffSIks=
29 | github.com/ncw/swift v1.0.53/go.mod h1:23YIA4yWVnGwv2dQlN4bB7egfYX6YLn0Yo/S6zZO/ZM=
30 | github.com/paulmach/orb v0.1.6/go.mod h1:pPwxxs3zoAyosNSbNKn1jiXV2+oovRDObDKfTvRegDI=
31 | github.com/paulmach/osm v0.1.1/go.mod h1:/UEV7XqKKTG3/46W+MtSmIl81yjV7cGoLkpol3S094I=
32 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
33 | github.com/remyoudompheng/bigfft v0.0.0-20170806203942-52369c62f446/go.mod h1:uYEyJGbgTkfkS4+E/PavXkNJcbFIpEtjt2B0KDQ5+9M=
34 | github.com/swill/go.clipper v0.0.0-20160727040122-3274bcc4839c h1:sr4ewNudhajqwJwQN4p4DkuDjXAVEz4NEAfKHaM7vtE=
35 | github.com/swill/go.clipper v0.0.0-20160727040122-3274bcc4839c/go.mod h1:ZM1njTxz+Lbh770OBPuD7EJ0d1it9KYa61rDXiHCgZY=
36 | github.com/swill/svgo v0.0.0-20150713022320-9f84ec778968 h1:wlnyZzToGPFwZw6SQHQxEAfYUyb+dyOar+MWbebdQto=
37 | github.com/swill/svgo v0.0.0-20150713022320-9f84ec778968/go.mod h1:SSvV4Jfl4EpJ4+llpP6jS3b0HbUSd8dj/41bifi4Mkg=
38 | github.com/swill/svgo v0.0.0-20150715025413-bc384fa1e849 h1:y/mkdxJaxL1b2p0ky+UlTKr45ZZ+GHgckfZjei+Lv/k=
39 | github.com/swill/svgo v0.0.0-20150715025413-bc384fa1e849/go.mod h1:SSvV4Jfl4EpJ4+llpP6jS3b0HbUSd8dj/41bifi4Mkg=
40 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
41 | golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
42 | golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
43 | golang.org/x/exp v0.0.0-20190125153040-c74c464bbbf2/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
44 | golang.org/x/exp v0.0.0-20190312203227-4b39c73a6495/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
45 | golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs=
46 | golang.org/x/image v0.0.0-20190227222117-0694c2d4d067 h1:KYGJGHOQy8oSi1fDlSpcZF0+juKwk/hEMv5SiwHogR0=
47 | golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
48 | golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE=
49 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
50 | golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
51 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
52 | golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
53 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
54 | golang.org/x/time v0.0.0-20190921001708-c4c64cad1fd0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
55 | golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
56 | golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
57 | golang.org/x/tools v0.0.0-20190206041539-40960b6deb8e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
58 | golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
59 | gonum.org/v1/gonum v0.0.0-20180816165407-929014505bf4/go.mod h1:Y+Yx5eoAFn32cQvJDxZx5Dpnq+c3wtXuadVZAcxbbBo=
60 | gonum.org/v1/gonum v0.0.0-20190331200053-3d26580ed485/go.mod h1:2ltnJ7xHfj0zHS40VVPYEAAMTa3ZGguvHGBSJeRWqE0=
61 | gonum.org/v1/gonum v0.0.0-20190509213835-50179cd3f3f7 h1:pTkUVMunXAr9zqT3oQUWs515Lsp5YGZF335aC1HI3N0=
62 | gonum.org/v1/gonum v0.0.0-20190509213835-50179cd3f3f7/go.mod h1:2ltnJ7xHfj0zHS40VVPYEAAMTa3ZGguvHGBSJeRWqE0=
63 | gonum.org/v1/netlib v0.0.0-20190313105609-8cb42192e0e0/go.mod h1:wa6Ws7BG/ESfp6dHfk7C6KdzKA7wR7u/rKwOGE66zvw=
64 | gonum.org/v1/netlib v0.0.0-20190331212654-76723241ea4e/go.mod h1:kS+toOQn6AQKjmKJ7gzohV1XkqsFehRA2FbsbkopSuQ=
65 | gonum.org/v1/plot v0.0.0-20181127114151-f41a315af148 h1:yYvSIczU/Bv0aQo2PoyVuJeUgucaxihBMa+YSBMNN9U=
66 | gonum.org/v1/plot v0.0.0-20181127114151-f41a315af148/go.mod h1:VIQWjXleEHakKVLjfhAAXUy3mq0NuXvobpOBf0ZBZro=
67 | modernc.org/cc v1.0.0/go.mod h1:1Sk4//wdnYJiUIxnW8ddKpaOJCF37yAdqYnkxUpaYxw=
68 | modernc.org/golex v1.0.0/go.mod h1:b/QX9oBD/LhixY6NDh+IdGv17hgB+51fET1i2kPSmvk=
69 | modernc.org/mathutil v1.0.0/go.mod h1:wU0vUrJsVWBZ4P6e7xtFJEhFSNsfRLJ8H458uRjg03k=
70 | modernc.org/strutil v1.0.0/go.mod h1:lstksw84oURvj9y3tn8lGvRxyRC1S2+g5uuIzNfIOBs=
71 | modernc.org/xc v1.0.0/go.mod h1:mRNCo0bvLjGhHO9WsyuKVU4q0ceiDDDoEeWDJHrNx8I=
72 | rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
73 |
--------------------------------------------------------------------------------
/kad.go:
--------------------------------------------------------------------------------
1 | package kad
2 |
3 | import (
4 | "bytes"
5 | "encoding/json"
6 | "fmt"
7 | "log"
8 | "os"
9 | "os/exec"
10 | "path/filepath"
11 | "reflect"
12 | "runtime"
13 | "strings"
14 |
15 | "github.com/ncw/swift"
16 | svg "github.com/swill/svgo"
17 | )
18 |
19 | const (
20 | PRECISION float64 = 1000
21 | OVERLAP = 0.001
22 | STORE_SWIFT = "swift"
23 | STORE_LOCAL = "local"
24 | )
25 |
26 | type KAD struct {
27 | Hash string
28 | UOM string
29 | U1 float64 `json:"key-unit"`
30 | DMZ float64
31 | Width float64
32 | Height float64
33 | LayoutCenter Point
34 | CaseCenter Point
35 | Fillet float64 `json:"fillet"`
36 | Kerf float64 `json:"kerf"`
37 | Xoff float64
38 | TopPad float64 `json:"top-padding"`
39 | LeftPad float64 `json:"left-padding"`
40 | RightPad float64 `json:"right-padding"`
41 | BottomPad float64 `json:"bottom-padding"`
42 | Xgrow float64 `json:"grow_x"`
43 | Ygrow float64 `json:"grow_y"`
44 | SwitchType int `json:"switch-type"`
45 | StabType int `json:"stab-type"`
46 | Case Case `json:"case"`
47 | CustomPolygons []CustomPolygon `json:"custom"`
48 | RawLayout []interface{} `json:"layout"`
49 | Layout [][]Key `json:"-"` // ignore in 'unmarshal'
50 | Svgs map[string]SvgWrapper
51 | Layers map[string]*Layer
52 | SvgStyle string
53 | LineColor string `json:"line-color"`
54 | LineWeight float64 `json:"line-weight"`
55 | Result Result
56 | Bounds Bounds
57 | Swift *swift.Connection
58 | SwiftBucket string
59 | FileStore string
60 | FileDirectory string
61 | FileServePath string
62 | }
63 |
64 | type Result struct {
65 | HasLayers bool `json:"has_layers"`
66 | Plates []string `json:"plates"`
67 | Formats []string `json:"formats"`
68 | Details map[string]*ResultDetails `json:"details"`
69 | }
70 |
71 | type ResultDetails struct {
72 | Name string `json:"name"`
73 | Width float64 `json:"width"`
74 | Height float64 `json:"height"`
75 | Area float64 `json:"area"`
76 | Exports []Export `json:"exports"`
77 | }
78 |
79 | type Export struct {
80 | Ext string `json:"ext"`
81 | Url string `json:"url"`
82 | }
83 |
84 | type SvgWrapper struct {
85 | File *os.File
86 | Svg *svg.SVG
87 | }
88 | type Layer struct {
89 | CutPolys []Path
90 | KeepPolys []Path
91 | Width float64
92 | Height float64
93 | }
94 |
95 | type Bounds struct {
96 | Xmin float64
97 | Xmax float64
98 | Ymin float64
99 | Ymax float64
100 | }
101 |
102 | type UploadCtl struct {
103 | Export *Export
104 | FailedExt string
105 | DelFile string
106 | Error error
107 | Attempt int
108 | }
109 |
110 | func New() *KAD {
111 | k := &KAD{
112 | Hash: "",
113 | UOM: "mm",
114 | U1: 19.05,
115 | DMZ: 5,
116 | Width: 0,
117 | Height: 0,
118 | LayoutCenter: Point{},
119 | CaseCenter: Point{},
120 | Fillet: 0,
121 | Kerf: 0,
122 | Xoff: 0,
123 | TopPad: 0,
124 | LeftPad: 0,
125 | RightPad: 0,
126 | BottomPad: 0,
127 | Xgrow: 0,
128 | Ygrow: 0,
129 | SwitchType: SWITCHMXH,
130 | StabType: STABCHERRYCOSTAR,
131 | Case: Case{
132 | EdgeWidth: 0,
133 | LeftWidth: 0,
134 | RightWidth: 0,
135 | TopWidth: 0,
136 | BottomWidth: 0,
137 | UsbLocation: 0,
138 | UsbWidth: 10,
139 | },
140 | Svgs: make(map[string]SvgWrapper),
141 | Layers: make(map[string]*Layer),
142 | SvgStyle: "fill:none",
143 | LineColor: "black",
144 | LineWeight: 0.05,
145 | Result: Result{
146 | HasLayers: false,
147 | Plates: []string{},
148 | Formats: []string{"svg"},
149 | Details: make(map[string]*ResultDetails),
150 | },
151 | }
152 |
153 | // if linux we can handle the DXF export so add it
154 | if runtime.GOOS == "linux" {
155 | k.Result.Formats = append(k.Result.Formats, []string{"dxf", "eps"}...)
156 | }
157 | return k
158 | }
159 |
160 | // Draw the SVGs needed for this layout.
161 | func (k *KAD) Draw() error {
162 | k.Kerf = k.Kerf / 2 // set kerf to be half of the real kerf as we are working from the center of the kerf
163 | k.SvgStyle = fmt.Sprintf("%s;stroke-width:%fmm;stroke:%s", k.SvgStyle, k.LineWeight, k.LineColor)
164 |
165 | k.InitCaseLayers()
166 | k.InitCaseEdges()
167 |
168 | if err := k.ParseLayout(); err != nil { // populates k.Layout with Keys
169 | log.Printf("ERROR in ParseLayout, exiting early...")
170 | return err
171 | }
172 | k.DrawLayout()
173 | k.UpdateLayerDimensions()
174 | k.DrawHoles()
175 | k.FinalizePolygons()
176 | k.FinalizeLayerDimensions()
177 | if err := k.DrawOutputFiles(); err != nil {
178 | log.Printf("ERROR drawing SVGs, exiting early...\n%s", err.Error())
179 | return err
180 | }
181 | if k.FileStore == STORE_SWIFT {
182 | k.StoreSwiftFiles()
183 | }
184 | if k.FileStore == STORE_LOCAL {
185 | k.StoreLocalFiles()
186 | }
187 | return nil
188 | }
189 |
190 | // Parse the layout and populate all the important information in the KAD object.
191 | func (k *KAD) ParseLayout() error {
192 | var err error
193 | kad_map := false // if there is user data passed to be added to the KAD object
194 | // see if the first element in the list is a map of user defined settings
195 | if len(k.RawLayout) > 0 && (reflect.ValueOf(k.RawLayout[0])).Kind() == reflect.Map {
196 | log.Printf("user settings: %s\n", json_str(k.RawLayout[0]))
197 | tmp_json, err := json.Marshal(k.RawLayout[0])
198 | if err != nil {
199 | log.Printf("ERROR Marshaling user settings\nRawLayout[0]: %s\n%s", json_str(k.RawLayout[0]), err.Error())
200 | return err
201 | }
202 | err = json.Unmarshal(tmp_json, &k) // popluate the KAD with the user specified
203 | if err != nil {
204 | log.Printf("ERROR Unmarshaling user settings\nRawLayout[0]: %s\n%s", json_str(k.RawLayout[0]), err.Error())
205 | return err
206 | }
207 | // to simplify things later, we will divide the grow values by two if they are not zero
208 | k.Xgrow = k.Xgrow / 2
209 | k.Ygrow = k.Ygrow / 2
210 | kad_map = true
211 | }
212 | // parse the keyboard layout from the slice of slices
213 | key_map := false // boolean to track if the key has already been handled by a map
214 | // we now need to make it a [][]interface{} as we now know it has that format (in theory)
215 | raw_layout := make([][]interface{}, 0)
216 | var tmp_raw []byte
217 | if kad_map && len(k.RawLayout) > 1 {
218 | tmp_raw, err = json.Marshal(k.RawLayout[1:])
219 | if err != nil {
220 | log.Printf("ERROR Marshaling layout\nRawLayout[1:]: %s\n%s", json_str(k.RawLayout[1:]), err.Error())
221 | return err
222 | }
223 | } else {
224 | tmp_raw, err = json.Marshal(k.RawLayout)
225 | if err != nil {
226 | log.Printf("ERROR Marshaling layout\nRawLayout: %s\n%s", json_str_ary(k.RawLayout), err.Error())
227 | return err
228 | }
229 | }
230 | err = json.Unmarshal(tmp_raw, &raw_layout) // use provided description of the key
231 | if err != nil {
232 | log.Printf("ERROR Unmarshaling layout\nRawLayout: %s\n%s", json_str_ary(k.RawLayout), err.Error())
233 | return err
234 | }
235 | for row := range raw_layout {
236 | row_layout := make([]Key, 0)
237 | for k := range raw_layout[row] {
238 | key := &Key{}
239 | key.Stab = -1 // since 0 is a valid entry
240 | // populate the Key
241 | if (reflect.ValueOf(raw_layout[row][k])).Kind() == reflect.Map {
242 | tmp_key, err := json.Marshal(raw_layout[row][k])
243 | if err != nil {
244 | log.Printf("ERROR Marshaling key details\nraw_layout[row][k]: %s\n%s", json_str(raw_layout[row][k]), err.Error())
245 | return err
246 | }
247 | err = json.Unmarshal(tmp_key, &key) // use provided description of the key
248 | if err != nil {
249 | log.Printf("ERROR Unmarshaling key details\nraw_layout[row][k]: %s\n%s", json_str(raw_layout[row][k]), err.Error())
250 | return err
251 | }
252 | if key.Width < 1 {
253 | key.Width = 1
254 | }
255 | if key.Height < 1 {
256 | key.Height = 1
257 | }
258 | if key.Xrel < 0 && len(row_layout) > 0 { // set stacked on previous key
259 | prev_key := row_layout[len(row_layout)-1] // get the prev_key
260 | prev_key.Stacked = true // set stacked for prev_key
261 | row_layout[len(row_layout)-1] = prev_key // update the row_layout
262 | }
263 | row_layout = append(row_layout, *key)
264 | key_map = true // this will ignore the next non-map key
265 | } else {
266 | if !key_map { // only handle if it was not already handled as a key_map, set to defaults
267 | key.Width = 1
268 | key.Height = 1
269 | row_layout = append(row_layout, *key)
270 | }
271 | key_map = false
272 | }
273 | }
274 | // add the row of Keys
275 | k.Layout = append(k.Layout, row_layout)
276 | }
277 | return nil
278 | }
279 |
280 | // Draw the switch and stabilizer openings for this KAD layout.
281 | func (k *KAD) DrawLayout() {
282 | prev_width := 0.0
283 | prev_y_off := 0.0
284 | c := &Key{}
285 | p := &Point{k.DMZ + k.Kerf + k.LeftPad, k.DMZ + k.Kerf + k.TopPad}
286 | for ri, row := range k.Layout {
287 | for ki, key := range row {
288 | // handle absolute positioned keys and rotated clusters
289 | if key.RotateCluster != 0 || key.Xabs != 0 || key.Yabs != 0 {
290 | if key.RotateCluster != 0 {
291 | c.RotateCluster = key.RotateCluster
292 | }
293 | if key.Xabs != 0 {
294 | c.Xabs = key.Xabs
295 | }
296 | if key.Yabs != 0 {
297 | c.Yabs = key.Yabs
298 | }
299 | }
300 | switch {
301 | case ri == 0 && ki == 0: // first key
302 | p.X += key.Xrel*k.U1 + key.Width*k.U1/2
303 | p.Y += key.Yrel*k.U1 + k.U1/2
304 | if c.Xabs != 0 || c.Yabs != 0 { // handle absolute positioned keys
305 | p.X += c.Xabs * k.U1
306 | p.Y += c.Yabs * k.U1
307 | }
308 | case ki == 0: // change rows
309 | p.X = k.DMZ + k.LeftPad + k.Kerf + key.Xrel*k.U1 + key.Width*k.U1/2
310 | switch {
311 | case key.Xabs != 0 || key.Yabs != 0: // the first row in a cluster
312 | p.X += c.Xabs * k.U1
313 | p.Y = k.DMZ + k.TopPad + k.Kerf + c.Yabs*k.U1 + key.Yrel*k.U1 + k.U1/2
314 | case c.Xabs != 0 || c.Yabs != 0: // a cluster row, but not the first cluster row
315 | p.X += c.Xabs * k.U1
316 | p.Y += key.Yrel*k.U1 + k.U1
317 | default: // all other keys
318 | p.Y += key.Yrel*k.U1 + k.U1
319 | }
320 | default:
321 | p.X += prev_width*k.U1/2 + key.Xrel*k.U1 + key.Width*k.U1/2
322 | }
323 | if prev_y_off != 0 {
324 | p.Y += -prev_y_off
325 | prev_y_off = 0.0
326 | }
327 | if key.Height > 1 {
328 | prev_y_off = key.Height*k.U1/2 - k.U1/2
329 | p.Y += prev_y_off
330 | }
331 | var init bool
332 | if ri == 0 && ki == 0 {
333 | init = true
334 | } else {
335 | init = false
336 | }
337 | key.Draw(k, *p, *c, init)
338 | //k.draw_switch(*p, key, *c, init)
339 | prev_width = key.Width
340 | }
341 | }
342 | }
343 |
344 | // update the dimensions of the kad based on what has been added
345 | func (k *KAD) UpdateLayerDimensions() {
346 | k.Width = k.Bounds.Xmax + k.RightPad + k.Kerf - k.DMZ
347 | k.Height = k.Bounds.Ymax + k.BottomPad + k.Kerf - k.DMZ
348 | k.CaseCenter = Point{k.DMZ + (k.Width / 2), k.DMZ + (k.Height / 2)}
349 | k.LayoutCenter = Point{
350 | (k.Bounds.Xmax-k.Bounds.Xmin)/2 + k.Bounds.Xmin,
351 | (k.Bounds.Ymax-k.Bounds.Ymin)/2 + k.Bounds.Ymin}
352 |
353 | // update the result dimensions while we are at it
354 | for _, layer := range k.Result.Plates {
355 | switch {
356 | case (layer == OPENLAYER || layer == CLOSEDLAYER) && k.TopPad < 0 && k.BottomPad < 0:
357 | if k.Case.EdgeWidth > 0 {
358 | k.Result.Details[layer].Width = 2*k.Case.EdgeWidth + 4*k.Kerf + 10 // layout the two parts 10mm apart
359 | } else {
360 | k.Result.Details[layer].Width = k.LeftPad + k.RightPad + 4*k.Kerf + 10 // layout the two parts 10mm apart
361 | }
362 | k.Result.Details[layer].Height = k.Height
363 | case (layer == OPENLAYER || layer == CLOSEDLAYER) && k.LeftPad < 0 && k.RightPad < 0:
364 | if k.Case.EdgeWidth > 0 {
365 | k.Result.Details[layer].Height = 2*k.Case.EdgeWidth + 4*k.Kerf + 10 // layout the two parts 10mm apart
366 | } else {
367 | k.Result.Details[layer].Height = k.TopPad + k.BottomPad + 4*k.Kerf + 10 // layout the two parts 10mm apart
368 | }
369 | k.Result.Details[layer].Width = k.Width
370 | default:
371 | k.Result.Details[layer].Width = k.Width
372 | k.Result.Details[layer].Height = k.Height
373 | }
374 | }
375 | }
376 |
377 | // Finalize the polygons before they go for file processing
378 | func (k *KAD) FinalizeLayerDimensions() {
379 | // update the bounds again
380 | for _, layer := range k.Result.Plates {
381 | for _, path := range k.Layers[layer].KeepPolys {
382 | k.UpdateBounds(path, false)
383 | }
384 | }
385 |
386 | // determine the offset from the new bounds
387 | offset := &Point{0.0, 0.0}
388 | if k.Bounds.Xmin-k.DMZ < 0 {
389 | offset.X = -(k.Bounds.Xmin - k.DMZ)
390 | }
391 | if k.Bounds.Ymin-k.DMZ < 0 {
392 | offset.Y = -(k.Bounds.Ymin - k.DMZ)
393 | }
394 |
395 | // get the new dimensions
396 | k.Width = k.Bounds.Xmax - k.Bounds.Xmin
397 | k.Height = k.Bounds.Ymax - k.Bounds.Ymin
398 | k.CaseCenter.X += offset.X
399 | k.CaseCenter.Y += offset.Y
400 | k.LayoutCenter.X += offset.X
401 | k.LayoutCenter.Y += offset.Y
402 |
403 | // shift the points based on the updated dimensions
404 | for _, layer := range k.Result.Plates {
405 | // shift points by offset
406 | for p := range k.Layers[layer].KeepPolys {
407 | k.Layers[layer].KeepPolys[p].Rel(*offset)
408 | }
409 | // update result sizes
410 | switch {
411 | case (layer == OPENLAYER || layer == CLOSEDLAYER) && k.TopPad < 0 && k.BottomPad < 0:
412 | k.Result.Details[layer].Height = k.Height
413 | case (layer == OPENLAYER || layer == CLOSEDLAYER) && k.LeftPad < 0 && k.RightPad < 0:
414 | k.Result.Details[layer].Width = k.Width
415 | default:
416 | k.Result.Details[layer].Width = k.Width
417 | k.Result.Details[layer].Height = k.Height
418 | }
419 | }
420 | }
421 |
422 | // Initialize the SVG files and their File writers.
423 | func (k *KAD) DrawOutputFiles() error {
424 | _ = os.Mkdir(k.FileDirectory, 0755)
425 | for _, layer := range k.Result.Plates {
426 | abs_svg, err := filepath.Abs(fmt.Sprintf("%s%s_%s.svg", k.FileDirectory, k.Hash, layer))
427 | file, err := os.Create(abs_svg)
428 | if err != nil {
429 | log.Printf("ERROR Creating export file: %s, %s | %s", k.Hash, layer, err.Error())
430 | return err
431 | }
432 |
433 | k.Svgs[layer] = SvgWrapper{File: file, Svg: svg.New(file)}
434 | canvas := k.Svgs[layer].Svg
435 | canvas.FloatDecimals = 3
436 | canvas.StartviewUnitF(k.Width+2*k.DMZ, k.Height+2*k.DMZ, k.UOM, 0, 0, k.Width+2*k.DMZ, k.Height+2*k.DMZ)
437 |
438 | // draw the elements
439 | if len(k.Layers[layer].KeepPolys) > 0 { // draw polygons
440 | xs, ys := make([]float64, 0), make([]float64, 0)
441 | for _, poly := range k.Layers[layer].KeepPolys {
442 | if len(poly) > 0 {
443 | xs, ys = poly.SplitOnAxis()
444 | canvas.PolygonF(xs, ys, k.SvgStyle)
445 | }
446 | }
447 | }
448 |
449 | canvas.End()
450 | file.Close() // close written svg
451 |
452 | // create other file formats
453 | if in_strings("dxf", k.Result.Formats) || in_strings("eps", k.Result.Formats) {
454 | err = exec.Command("inkscape", "--export-type=eps", abs_svg).Run()
455 | if err != nil {
456 | log.Printf("ERROR: could not create EPS file for: %s, %s | %s", k.Hash, layer, err.Error())
457 | continue // skip dxf because it depends on eps
458 | }
459 | log.Println("created eps file")
460 |
461 | if in_strings("dxf", k.Result.Formats) {
462 | // inkscape's export-type option automatically creates file extension of "eps".
463 | // pstoedit converts "eps" to "dxf".
464 | abs_eps := fmt.Sprintf("%s.%s", strings.TrimSuffix(abs_svg, ".svg"), "eps")
465 | abs_dxf := fmt.Sprintf("%s.%s", strings.TrimSuffix(abs_svg, ".svg"), "dxf")
466 | cmd := exec.Command("pstoedit", "-dt", "-f", "dxf: -polyaslines -mm", abs_eps, abs_dxf)
467 | var out bytes.Buffer
468 | cmd.Stdout = &out
469 | err = cmd.Run()
470 | if err != nil {
471 | log.Printf("ERROR: could not create DXF file for: %s, %s | %s : %s",
472 | k.Hash, layer, err.Error(), out.String())
473 | } else {
474 | log.Println("created dxf file")
475 | }
476 | }
477 | }
478 | }
479 | return nil
480 | }
481 |
482 | // Store the generated SVG files in an object store.
483 | func (k *KAD) StoreSwiftFiles() {
484 | log.Printf("started uploading %s\n", k.Hash)
485 | failed_exts := []string{}
486 | delete_files := []string{}
487 |
488 | concurrency := 5
489 | give_up_after := 3
490 |
491 | for _, layer := range k.Result.Plates {
492 | exports := []Export{}
493 |
494 | sem := make(chan bool, concurrency)
495 | buffer := make(chan UploadCtl, concurrency)
496 | process_file := func(ext string, control UploadCtl) {
497 | // block until we have a semaphore slot
498 | sem <- true // semaphore lock
499 |
500 | go func(ext string) { // create concurrent goroutine
501 | defer func() { <-sem }() // semaphore release
502 | control.Attempt = control.Attempt + 1
503 |
504 | file_path, err := filepath.Abs(fmt.Sprintf("%s%s_%s.%s", k.FileDirectory, k.Hash, layer, ext))
505 | if err != nil {
506 | log.Printf("ERROR: Unable to create filepath '%s'\n%s", file_path, err.Error())
507 | control.Error = err
508 | control.FailedExt = ext
509 | buffer <- control
510 | return
511 | }
512 |
513 | // check that the file exists
514 | if _, err := os.Stat(file_path); err == nil {
515 | // make sure the swift directory is in place
516 | obj, _, err := k.Swift.Object(k.SwiftBucket, k.Hash)
517 | if err != nil || obj.ContentType != "application/directory" {
518 | err = k.Swift.ObjectPutString(k.SwiftBucket, k.Hash, "", "application/directory")
519 | if err != nil {
520 | log.Printf("ERROR: Problem creating folder '%s' (not required)\n%s", k.Hash, err.Error())
521 | }
522 | }
523 |
524 | // upload the file
525 | obj_path := fmt.Sprintf("%s/%s_%s.%s", k.Hash, k.Hash, layer, ext)
526 | f, err := os.Open(file_path)
527 | if err != nil {
528 | log.Printf("ERROR: Problem opening file '%s'\n%s", file_path, err.Error())
529 | control.Error = err
530 | control.FailedExt = ext
531 | buffer <- control
532 | return
533 | }
534 | defer f.Close()
535 | _, err = k.Swift.ObjectPut(k.SwiftBucket, obj_path, f, false, "", "", nil)
536 | if err != nil {
537 | log.Printf("ERROR: Problem uploading object '%s'\n%s", obj_path, err.Error())
538 | control.Error = err
539 | control.FailedExt = ext
540 | buffer <- control
541 | return
542 | }
543 | control.Export = &Export{
544 | Ext: ext,
545 | Url: fmt.Sprintf(
546 | "%s%s/%s/%s_%s.%s", k.FileServePath, k.SwiftBucket, k.Hash, k.Hash, layer, ext),
547 | }
548 | control.DelFile = file_path
549 | // send control by default
550 | } else {
551 | log.Printf("ERROR: File not found '%s'", file_path)
552 | control.Error = err
553 | control.FailedExt = ext
554 | buffer <- control
555 | return
556 | }
557 |
558 | buffer <- control
559 | }(ext) // call function
560 | }
561 |
562 | // since the semaphore channel has limited size,
563 | // this loop must exit in order for the reads to happen
564 | for _, ext := range k.Result.Formats {
565 | go process_file(ext, UploadCtl{}) // queue up the files
566 | }
567 |
568 | // read from the channel of concurrent results
569 | expect_total := len(k.Result.Formats) // number of tries we know of so far
570 | for i := 0; i < expect_total; i++ {
571 | select {
572 | case result := <-buffer:
573 |
574 | if result.Export != nil {
575 | exports = append(exports, *result.Export)
576 | if result.DelFile != "" {
577 | delete_files = append(delete_files, result.DelFile) // clean up after upload
578 | }
579 | } else {
580 | if result.FailedExt != "" {
581 | if result.Attempt == give_up_after {
582 | failed_exts = append(failed_exts, result.FailedExt)
583 | if result.DelFile != "" {
584 | delete_files = append(delete_files, result.DelFile) // clean up after upload
585 | }
586 | } else {
587 | expect_total += 1
588 | go process_file(result.FailedExt, result) // queue up another attempt
589 | }
590 | }
591 | }
592 |
593 | }
594 | }
595 | close(buffer)
596 | close(sem)
597 |
598 | k.Result.Details[layer].Exports = exports
599 |
600 | }
601 | log.Printf("finished uploading %s\n", k.Hash)
602 | // remove formats that failed
603 | if len(failed_exts) > 0 {
604 | formats := k.Result.Formats
605 | for i := len(k.Result.Formats) - 1; i >= 0; i-- { // loop backwards so we don't break index on change
606 | if in_strings(k.Result.Formats[i], failed_exts) {
607 | formats = append(formats[:i], formats[i+1:]...) // remove index
608 | }
609 | }
610 | k.Result.Formats = formats
611 | }
612 | // clean up local files
613 | for _, f := range delete_files {
614 | err := os.Remove(f)
615 | if err != nil {
616 | log.Printf("ERROR: problem deleting '%s'\n%s", f, err.Error())
617 | }
618 | }
619 | }
620 |
621 | // Store and serve the generated SVG files locally.
622 | func (k *KAD) StoreLocalFiles() {
623 | log.Printf("saving locally %s\n", k.Hash)
624 | failed_exts := []string{}
625 | _ = os.Mkdir(k.FileDirectory, 0755)
626 | for _, layer := range k.Result.Plates {
627 | exports := []Export{}
628 | failed := false
629 | for _, ext := range k.Result.Formats {
630 | file_path, err := filepath.Abs(fmt.Sprintf("%s%s_%s.%s", k.FileDirectory, k.Hash, layer, ext))
631 | if err != nil {
632 | log.Printf("ERROR: Unable to create filepath '%s'\n%s", file_path, err.Error())
633 | failed = true
634 | }
635 | if !failed {
636 | exports = append(exports, Export{
637 | Ext: ext,
638 | Url: fmt.Sprintf(
639 | "%s%s_%s.%s", k.FileServePath, k.Hash, layer, ext),
640 | })
641 | }
642 | if failed {
643 | // failed extension
644 | if !in_strings(ext, failed_exts) {
645 | failed_exts = append(failed_exts, ext)
646 | }
647 | }
648 | }
649 | k.Result.Details[layer].Exports = exports
650 | }
651 | log.Printf("saved locally %s\n", k.Hash)
652 | // remove formats that failed
653 | if len(failed_exts) > 0 {
654 | formats := k.Result.Formats
655 | for i := len(k.Result.Formats) - 1; i >= 0; i-- { // loop backwards so we don't break index on change
656 | if in_strings(k.Result.Formats[i], failed_exts) {
657 | formats = append(formats[:i], formats[i+1:]...) // remove index
658 | }
659 | }
660 | k.Result.Formats = formats
661 | }
662 | }
663 |
664 | // determine the size of the canvas by checking the bounds of the keys.
665 | func (k *KAD) UpdateBounds(path Path, init bool) {
666 | for _, point := range path {
667 | if point.X < k.Bounds.Xmin || init {
668 | k.Bounds.Xmin = point.X
669 | }
670 | if point.X > k.Bounds.Xmax || init {
671 | k.Bounds.Xmax = point.X
672 | }
673 | if point.Y < k.Bounds.Ymin || init {
674 | k.Bounds.Ymin = point.Y
675 | }
676 | if point.Y > k.Bounds.Ymax || init {
677 | k.Bounds.Ymax = point.Y
678 | }
679 | }
680 | }
681 |
682 | func json_str_ary(input []interface{}) string {
683 | raw_json, err := json.Marshal(input)
684 | if err != nil {
685 | return fmt.Sprintf("%+v", input)
686 | }
687 | return string(raw_json)
688 | }
689 |
690 | func json_str(input interface{}) string {
691 | raw_json, err := json.Marshal(input)
692 | if err != nil {
693 | return fmt.Sprintf("%+v", input)
694 | }
695 | return string(raw_json)
696 | }
697 |
698 | func in_strings(query string, strings []string) bool {
699 | for _, x := range strings {
700 | if x == query {
701 | return true
702 | }
703 | }
704 | return false
705 | }
706 |
707 | func in_ints(query int, ints []int) bool {
708 | for _, x := range ints {
709 | if x == query {
710 | return true
711 | }
712 | }
713 | return false
714 | }
715 |
716 | func in_floats(query float64, floats []float64) bool {
717 | for _, x := range floats {
718 | if x == query {
719 | return true
720 | }
721 | }
722 | return false
723 | }
724 |
--------------------------------------------------------------------------------
/key.go:
--------------------------------------------------------------------------------
1 | package kad
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "strconv"
7 | "strings"
8 | )
9 |
10 | const (
11 | SWITCHMX = 1
12 | SWITCHMXALPS = 2
13 | SWITCHMXH = 3
14 | SWITCHALPS = 4
15 | STABREMOVE = 0
16 | STABCHERRYCOSTAR = 1
17 | STABCHERRY = 2
18 | STABCOSTAR = 3
19 | STABALPS = 4
20 | )
21 |
22 | type Key struct {
23 | Width float64 `json:"w"` // width in key units
24 | Height float64 `json:"h"` // height in key units
25 | AltWidth float64 `json:"w2"` // alternate width in key units for strangely shaped keys
26 | AltHeight float64 `json:"h2"` // alternate height in key units for strangely shaped keys
27 | Xrel float64 `json:"x"` // x relative position in key units
28 | Yrel float64 `json:"y"` // y relative position in key units
29 | Xabs float64 `json:"rx"` // x absolute position in key units
30 | Yabs float64 `json:"ry"` // y absolute position in key units
31 | Xalt float64 `json:"x2"` // x relative position in key units for strangely shaped keys
32 | Yalt float64 `json:"y2"` // y relative position in key units for strangely shaped keys
33 | Type int `json:"_t"` // switch type as int
34 | Stab int `json:"_s"` // stab type as int
35 | Kerf float64 `json:"_k"` // kerf for this key
36 | Custom string `json:"_c"` // center point as custom index
37 | Stacked bool
38 | Bounds Path
39 | Rotate float64 `json:"_r"` // rotate switch opening in degrees
40 | RotateStab float64 `json:"_rs"` // rotate stabilizer opening in degrees
41 | RotateCluster float64 `json:"r"` // rotate the following cluster of keys (in degrees)
42 | }
43 |
44 | func GetCherryStabOffset(size float64) (float64, error) {
45 | switch size {
46 | case 2: // 2u
47 | return 11.9, nil
48 | case 2.25: // 2.25u
49 | return 11.9, nil
50 | case 2.75: // 2.75u
51 | return 11.9, nil
52 | case 3: // 3u
53 | return 19.05, nil
54 | case 4: // 4u
55 | return 28.575, nil
56 | case 4.5: // 4.5u
57 | return 34.671, nil
58 | case 5.5: // 5.5u
59 | return 42.8625, nil
60 | case 6: // 6u
61 | return 47.5, nil
62 | case 6.25: // 6.25u
63 | return 50, nil
64 | case 6.5: // 6.5u
65 | return 52.38, nil
66 | case 7: // 7u
67 | return 57.15, nil
68 | case 8: // 8u
69 | return 66.675, nil
70 | case 9: // 9u
71 | return 66.675, nil
72 | case 10: // 10u
73 | return 66.675, nil
74 | default:
75 | return 0, errors.New(fmt.Sprintf("No cherry stabilizer offset defined for a %fu key.", size))
76 | }
77 | }
78 |
79 | func GetAlpsStabOffset(size float64) (float64, error) {
80 | switch size {
81 | case 1.75: // 1.75u
82 | return 11.938, nil
83 | case 2.0: // 2.0u
84 | return 14.096, nil
85 | case 2.25: // 2.25u
86 | return 14.096, nil
87 | case 2.75: // 2.75u
88 | return 14.096, nil
89 | case 6.25: // 6.25u
90 | return 41.859, nil
91 | case 6.5: // 6.5u
92 | return 45.3, nil
93 | default:
94 | return 0, errors.New(fmt.Sprintf("No alps stabilizer offset defined for a %fu key.", size))
95 | }
96 | }
97 |
98 | // Draw an individual switch/stabilizer opening.
99 | func (key *Key) Draw(k *KAD, c Point, ctx Key, init bool) {
100 | // set the key defaults and update items like kerf to the functional value
101 | if !in_ints(key.Type, []int{SWITCHMX, SWITCHMXALPS, SWITCHMXH, SWITCHALPS}) {
102 | key.Type = k.SwitchType
103 | }
104 | if !in_ints(key.Stab, []int{STABREMOVE, STABCHERRYCOSTAR, STABCHERRY, STABCOSTAR, STABALPS}) {
105 | key.Stab = k.StabType
106 | }
107 | if key.Kerf != 0 {
108 | key.Kerf = key.Kerf / 2
109 | } else {
110 | key.Kerf = k.Kerf
111 | }
112 | // handle custom polygons centered at this key
113 | if key.Custom != "" {
114 | index_parts := strings.Split(strings.Replace(key.Custom, " ", "", -1), ",")
115 | for _, i := range index_parts {
116 | if index_int, err := strconv.ParseInt(i, 10, 64); err == nil {
117 | if int64(len(k.CustomPolygons)) > index_int {
118 | point_ary := strings.Split(strings.Replace(k.CustomPolygons[index_int].RelAbs, " ", "", -1), ";")
119 | point_ary = append(point_ary, fmt.Sprintf("[%f,%f]", c.X, c.Y))
120 | k.CustomPolygons[index_int].RelAbs = strings.Join(point_ary, ";")
121 | }
122 | }
123 | }
124 | }
125 |
126 | vertical := false
127 | if key.Height > key.Width {
128 | vertical = true
129 | }
130 |
131 | // determine the bounds of the keycap
132 | var bound_path Path
133 | b := c // bounds center point
134 | x_point := k.U1 * key.Width / 2
135 | y_point := k.U1 * key.Height / 2
136 | if key.AltWidth > key.Width {
137 | x_point = k.U1 * key.AltWidth / 2
138 | b = Point{b.X + k.U1*(key.AltWidth-key.Width)/2, b.Y}
139 | }
140 | if key.AltHeight > key.Height {
141 | y_point = k.U1 * key.AltHeight / 2
142 | }
143 | bound_path = Path{
144 | {x_point + OVERLAP, -y_point - OVERLAP},
145 | {x_point + OVERLAP, y_point + OVERLAP},
146 | {-x_point - OVERLAP, y_point + OVERLAP},
147 | {-x_point - OVERLAP, -y_point - OVERLAP},
148 | }
149 | // adapt the bounds to account for alternate offsets
150 | if key.Xalt != 0 {
151 | b = Point{b.X + k.U1*key.Xalt, b.Y}
152 | }
153 | bound_path.Rel(b) // make the path relative to key center
154 | if key.Rotate != 0 {
155 | bound_path.RotatePath(key.Rotate, b)
156 | }
157 | if ctx.RotateCluster != 0 {
158 | bound_path.RotatePath(ctx.RotateCluster, Point{ctx.Xabs*k.U1 + k.DMZ + k.LeftPad, ctx.Yabs*k.U1 + k.DMZ + k.TopPad})
159 | }
160 | k.UpdateBounds(bound_path, init)
161 |
162 | // add the top layer cutouts for sandwich cases
163 | if k.Case.Type == CASE_SANDWICH {
164 | k.Layers[TOPLAYER].CutPolys = append(k.Layers[TOPLAYER].CutPolys, bound_path)
165 | }
166 |
167 | // draw the switch cutout path
168 | var switch_path Path
169 | switch key.Type {
170 | case SWITCHMX: // standard square mx
171 | switch_path = Path{
172 | {7 - key.Kerf + k.Xgrow, -7 + key.Kerf - k.Ygrow}, {7 - key.Kerf + k.Xgrow, 7 - key.Kerf + k.Ygrow},
173 | {-7 + key.Kerf - k.Xgrow, 7 - key.Kerf + k.Ygrow}, {-7 + key.Kerf - k.Xgrow, -7 + key.Kerf - k.Ygrow},
174 | }
175 | case SWITCHMXALPS: // alps + mx compatible
176 | switch_path = Path{
177 | {7 - key.Kerf, -7 + key.Kerf}, {7 - key.Kerf, -6.4 + key.Kerf}, {7.8 - key.Kerf, -6.4 + key.Kerf}, {7.8 - key.Kerf, 6.4 - key.Kerf},
178 | {7 - key.Kerf, 6.4 - key.Kerf}, {7 - key.Kerf, 7 - key.Kerf}, {-7 + key.Kerf, 7 - key.Kerf}, {-7 + key.Kerf, 6.4 - key.Kerf},
179 | {-7.8 + key.Kerf, 6.4 - key.Kerf}, {-7.8 + key.Kerf, -6.4 + key.Kerf}, {-7 + key.Kerf, -6.4 + key.Kerf}, {-7 + key.Kerf, -7 + key.Kerf},
180 | }
181 | case SWITCHMXH: // mx with side wings
182 | switch_path = Path{
183 | {7 - key.Kerf, -7 + key.Kerf}, {7 - key.Kerf, -6 + key.Kerf}, {7.8 - key.Kerf, -6 + key.Kerf}, {7.8 - key.Kerf, -2.9 - key.Kerf},
184 | {7 - key.Kerf, -2.9 - key.Kerf}, {7 - key.Kerf, 2.9 + key.Kerf}, {7.8 - key.Kerf, 2.9 + key.Kerf}, {7.8 - key.Kerf, 6 - key.Kerf},
185 | {7 - key.Kerf, 6 - key.Kerf}, {7 - key.Kerf, 7 - key.Kerf}, {-7 + key.Kerf, 7 - key.Kerf}, {-7 + key.Kerf, 6 - key.Kerf},
186 | {-7.8 + key.Kerf, 6 - key.Kerf}, {-7.8 + key.Kerf, 2.9 + key.Kerf}, {-7 + key.Kerf, 2.9 + key.Kerf}, {-7 + key.Kerf, -2.9 - key.Kerf},
187 | {-7.8 + key.Kerf, -2.9 - key.Kerf}, {-7.8 + key.Kerf, -6 + key.Kerf}, {-7 + key.Kerf, -6 + key.Kerf}, {-7 + key.Kerf, -7 + key.Kerf},
188 | }
189 | case SWITCHALPS: // alps cutout
190 | switch_path = Path{
191 | {7.8 - key.Kerf, -6.4 + key.Kerf}, {7.8 - key.Kerf, 6.4 - key.Kerf},
192 | {-7.8 + key.Kerf, 6.4 - key.Kerf}, {-7.8 + key.Kerf, -6.4 + key.Kerf},
193 | }
194 | }
195 |
196 | if vertical {
197 | switch_path.RotatePath(90, Point{0, 0})
198 | }
199 | if key.Rotate != 0 {
200 | switch_path.RotatePath(key.Rotate, Point{0, 0})
201 | }
202 | switch_path.Rel(c) // make the path relative to center
203 |
204 | if ctx.RotateCluster != 0 {
205 | switch_path.RotatePath(ctx.RotateCluster, Point{ctx.Xabs*k.U1 + k.DMZ + k.LeftPad, ctx.Yabs*k.U1 + k.DMZ + k.TopPad})
206 | }
207 |
208 | // check if the key needs stabilizer cutouts
209 | flip_stab := false
210 | if ctx.RotateCluster > 0 && (key.Width >= 2 || (vertical && key.Height >= 2)) {
211 | flip_stab = true
212 | }
213 |
214 | switch key.Stab {
215 | case STABCHERRYCOSTAR: // cherry + costar stabilizer
216 | key.DrawCherryCostarStab(k, c, ctx, vertical, flip_stab)
217 | case STABCHERRY: // cherry spec stabilizer
218 | key.DrawCherryStab(k, c, ctx, vertical, flip_stab)
219 | case STABCOSTAR: // costar stabilizer
220 | key.DrawCostarStab(k, c, ctx, vertical, flip_stab)
221 | case STABALPS:
222 | key.DrawAlpsStab(k, c, ctx, vertical, flip_stab)
223 | }
224 |
225 | if key.Width == 6 || (vertical && key.Height == 6) { // adjust for offcenter stem switch
226 | switch_path.Rel(Point{k.U1 / 2, 0}) // off center is 1/2 a switch right
227 | }
228 |
229 | k.Layers[SWITCHLAYER].CutPolys = append(k.Layers[SWITCHLAYER].CutPolys, switch_path)
230 | }
231 |
232 | // path for cherry + costar stabilizer
233 | func (key *Key) DrawCherryCostarStab(k *KAD, c Point, ctx Key, vertical, flip_stab bool) {
234 | var stab_path Path
235 | size := key.Width
236 | if vertical {
237 | size = key.Height
238 | }
239 |
240 | s, err := GetCherryStabOffset(size)
241 | if err != nil {
242 | return
243 | }
244 |
245 | stab_path = Path{
246 | {s - 3.375 + key.Kerf, -2.3 + key.Kerf}, {s - 3.375 + key.Kerf, -5.53 + key.Kerf}, {s - 1.65 + key.Kerf, -5.53 + key.Kerf},
247 | {s - 1.65 + key.Kerf, -6.45 + key.Kerf}, {s + 1.65 - key.Kerf, -6.45 + key.Kerf}, {s + 1.65 - key.Kerf, -5.53 + key.Kerf},
248 | {s + 3.375 - key.Kerf, -5.53 + key.Kerf}, {s + 3.375 - key.Kerf, -2.3 + key.Kerf}, {s + 4.2 - key.Kerf, -2.3 + key.Kerf},
249 | {s + 4.2 - key.Kerf, 0.5 - key.Kerf}, {s + 3.375 - key.Kerf, 0.5 - key.Kerf}, {s + 3.375 - key.Kerf, 6.77 - key.Kerf},
250 | {s + 1.65 - key.Kerf, 6.77 - key.Kerf}, {s + 1.65 - key.Kerf, 7.75 - key.Kerf}, {s - 1.65 + key.Kerf, 7.75 - key.Kerf},
251 | {s - 1.65 + key.Kerf, 6.77 - key.Kerf}, {s - 3.375 + key.Kerf, 6.77 - key.Kerf}, {s - 3.375 + key.Kerf, 2.3 - key.Kerf},
252 | {-s + 3.375 - key.Kerf, 2.3 - key.Kerf}, {-s + 3.375 - key.Kerf, 6.77 - key.Kerf}, {-s + 1.65 - key.Kerf, 6.77 - key.Kerf},
253 | {-s + 1.65 - key.Kerf, 7.75 - key.Kerf}, {-s - 1.65 + key.Kerf, 7.75 - key.Kerf}, {-s - 1.65 + key.Kerf, 6.77 - key.Kerf},
254 | {-s - 3.375 + key.Kerf, 6.77 - key.Kerf}, {-s - 3.375 + key.Kerf, 0.5 - key.Kerf}, {-s - 4.2 + key.Kerf, 0.5 - key.Kerf},
255 | {-s - 4.2 + key.Kerf, -2.3 + key.Kerf}, {-s - 3.375 + key.Kerf, -2.3 + key.Kerf}, {-s - 3.375 + key.Kerf, -5.53 + key.Kerf},
256 | {-s - 1.65 + key.Kerf, -5.53 + key.Kerf}, {-s - 1.65 + key.Kerf, -6.45 + key.Kerf}, {-s + 1.65 - key.Kerf, -6.45 + key.Kerf},
257 | {-s + 1.65 - key.Kerf, -5.53 + key.Kerf}, {-s + 3.375 - key.Kerf, -5.53 + key.Kerf}, {-s + 3.375 - key.Kerf, -2.3 + key.Kerf},
258 | }
259 | if vertical {
260 | stab_path.RotatePath(90, Point{0, 0})
261 | }
262 | if flip_stab {
263 | stab_path.RotatePath(180, Point{0, 0})
264 | }
265 | if key.RotateStab != 0 {
266 | stab_path.RotatePath(key.RotateStab, Point{0, 0})
267 | }
268 |
269 | stab_path.Rel(c)
270 | if ctx.RotateCluster != 0 {
271 | stab_path.RotatePath(ctx.RotateCluster, Point{ctx.Xabs*k.U1 + k.DMZ + k.LeftPad, ctx.Yabs*k.U1 + k.DMZ + k.TopPad})
272 | }
273 | k.Layers[SWITCHLAYER].CutPolys = append(k.Layers[SWITCHLAYER].CutPolys, stab_path)
274 | }
275 |
276 | // path for cherry stabilizer
277 | func (key *Key) DrawCherryStab(k *KAD, c Point, ctx Key, vertical, flip_stab bool) {
278 | var stab_path Path
279 | size := key.Width
280 | if vertical {
281 | size = key.Height
282 | }
283 |
284 | s, err := GetCherryStabOffset(size)
285 | if err != nil {
286 | return
287 | }
288 |
289 | stab_path = Path{
290 | {s - 3.375 + key.Kerf, -2.3 + key.Kerf}, {s - 3.375 + key.Kerf, -5.53 + key.Kerf}, {s + 3.375 - key.Kerf, -5.53 + key.Kerf},
291 | {s + 3.375 - key.Kerf, -2.3 + key.Kerf}, {s + 4.2 - key.Kerf, -2.3 + key.Kerf}, {s + 4.2 - key.Kerf, 0.5 - key.Kerf},
292 | {s + 3.375 - key.Kerf, 0.5 - key.Kerf}, {s + 3.375 - key.Kerf, 6.77 - key.Kerf}, {s + 1.65 - key.Kerf, 6.77 - key.Kerf},
293 | {s + 1.65 - key.Kerf, 7.97 - key.Kerf}, {s - 1.65 + key.Kerf, 7.97 - key.Kerf}, {s - 1.65 + key.Kerf, 6.77 - key.Kerf},
294 | {s - 3.375 + key.Kerf, 6.77 - key.Kerf}, {s - 3.375 + key.Kerf, 2.3 - key.Kerf}, {-s + 3.375 - key.Kerf, 2.3 - key.Kerf},
295 | {-s + 3.375 - key.Kerf, 6.77 - key.Kerf}, {-s + 1.65 - key.Kerf, 6.77 - key.Kerf}, {-s + 1.65 - key.Kerf, 7.97 - key.Kerf},
296 | {-s - 1.65 + key.Kerf, 7.97 - key.Kerf}, {-s - 1.65 + key.Kerf, 6.77 - key.Kerf}, {-s - 3.375 + key.Kerf, 6.77 - key.Kerf},
297 | {-s - 3.375 + key.Kerf, 0.5 - key.Kerf}, {-s - 4.2 + key.Kerf, 0.5 - key.Kerf}, {-s - 4.2 + key.Kerf, -2.3 + key.Kerf},
298 | {-s - 3.375 + key.Kerf, -2.3 + key.Kerf}, {-s - 3.375 + key.Kerf, -5.53 + key.Kerf}, {-s + 3.375 - key.Kerf, -5.53 + key.Kerf},
299 | {-s + 3.375 - key.Kerf, -2.3 + key.Kerf},
300 | }
301 | if vertical {
302 | stab_path.RotatePath(90, Point{0, 0})
303 | }
304 | if flip_stab {
305 | stab_path.RotatePath(180, Point{0, 0})
306 | }
307 | if key.RotateStab != 0 {
308 | stab_path.RotatePath(key.RotateStab, Point{0, 0})
309 | }
310 |
311 | stab_path.Rel(c)
312 | if ctx.RotateCluster != 0 {
313 | stab_path.RotatePath(ctx.RotateCluster, Point{ctx.Xabs*k.U1 + k.DMZ + k.LeftPad, ctx.Yabs*k.U1 + k.DMZ + k.TopPad})
314 | }
315 | k.Layers[SWITCHLAYER].CutPolys = append(k.Layers[SWITCHLAYER].CutPolys, stab_path)
316 | }
317 |
318 | // draw the costar stabilizer
319 | func (key *Key) DrawCostarStab(k *KAD, c Point, ctx Key, vertical, flip_stab bool) {
320 | // special case where 'union' will never be applied, so 'stab_path' is not used
321 | var stab_path_l Path
322 | var stab_path_r Path
323 | size := key.Width
324 | if vertical {
325 | size = key.Height
326 | }
327 |
328 | s, err := GetCherryStabOffset(size)
329 | if err != nil {
330 | return
331 | }
332 |
333 | stab_path_l = Path{
334 | {-s + 1.65 - key.Kerf, -6.45 + key.Kerf}, {-s - 1.65 + key.Kerf, -6.45 + key.Kerf}, {-s - 1.65 + key.Kerf, 7.75 - key.Kerf},
335 | {-s + 1.65 - key.Kerf, 7.75 - key.Kerf},
336 | }
337 | stab_path_r = Path{
338 | {s - 1.65 + key.Kerf, -6.45 + key.Kerf}, {s + 1.65 - key.Kerf, -6.45 + key.Kerf}, {s + 1.65 - key.Kerf, 7.75 - key.Kerf},
339 | {s - 1.65 + key.Kerf, 7.75 - key.Kerf},
340 | }
341 | if vertical {
342 | stab_path_l.RotatePath(90, Point{0, 0})
343 | stab_path_r.RotatePath(90, Point{0, 0})
344 | }
345 | if flip_stab {
346 | stab_path_l.RotatePath(180, Point{0, 0})
347 | stab_path_r.RotatePath(180, Point{0, 0})
348 | }
349 | if key.RotateStab != 0 {
350 | stab_path_l.RotatePath(key.RotateStab, Point{0, 0})
351 | stab_path_r.RotatePath(key.RotateStab, Point{0, 0})
352 | }
353 | // draw this special case at this point
354 | stab_path_l.Rel(c)
355 | stab_path_r.Rel(c)
356 | if ctx.RotateCluster != 0 {
357 | stab_path_l.RotatePath(ctx.RotateCluster, Point{ctx.Xabs*k.U1 + k.DMZ + k.LeftPad, ctx.Yabs*k.U1 + k.DMZ + k.TopPad})
358 | stab_path_r.RotatePath(ctx.RotateCluster, Point{ctx.Xabs*k.U1 + k.DMZ + k.LeftPad, ctx.Yabs*k.U1 + k.DMZ + k.TopPad})
359 | }
360 | k.Layers[SWITCHLAYER].CutPolys = append(k.Layers[SWITCHLAYER].CutPolys, stab_path_l)
361 | k.Layers[SWITCHLAYER].CutPolys = append(k.Layers[SWITCHLAYER].CutPolys, stab_path_r)
362 | }
363 |
364 | // draw the alps stabilizer
365 | func (key *Key) DrawAlpsStab(k *KAD, c Point, ctx Key, vertical, flip_stab bool) {
366 | // special case where 'union' will never be applied, so 'stab_path' is not used
367 | var stab_path_l Path
368 | var stab_path_r Path
369 | size := key.Width
370 | if vertical {
371 | size = key.Height
372 | }
373 |
374 | s, err := GetAlpsStabOffset(size)
375 | if err == nil {
376 | stab_path_l = Path{
377 | {-s - 1.333 + key.Kerf, 3.873 + key.Kerf}, {-s + 1.333 - key.Kerf, 3.873 + key.Kerf},
378 | {-s + 1.333 - key.Kerf, 9.08 - key.Kerf}, {-s - 1.333 + key.Kerf, 9.08 - key.Kerf},
379 | }
380 | stab_path_r = Path{
381 | {s - 1.333 + key.Kerf, 3.873 + key.Kerf}, {s + 1.333 - key.Kerf, 3.873 + key.Kerf},
382 | {s + 1.333 - key.Kerf, 9.08 - key.Kerf}, {s - 1.333 + key.Kerf, 9.08 - key.Kerf},
383 | }
384 | if vertical {
385 | stab_path_l.RotatePath(90, Point{0, 0})
386 | stab_path_r.RotatePath(90, Point{0, 0})
387 | }
388 | if flip_stab {
389 | stab_path_l.RotatePath(180, Point{0, 0})
390 | stab_path_r.RotatePath(180, Point{0, 0})
391 | }
392 | if key.RotateStab != 0 {
393 | stab_path_l.RotatePath(key.RotateStab, Point{0, 0})
394 | stab_path_r.RotatePath(key.RotateStab, Point{0, 0})
395 | }
396 | // draw this special case at this point
397 | stab_path_l.Rel(c)
398 | stab_path_r.Rel(c)
399 | if ctx.RotateCluster != 0 {
400 | stab_path_l.RotatePath(ctx.RotateCluster, Point{ctx.Xabs*k.U1 + k.DMZ + k.LeftPad, ctx.Yabs*k.U1 + k.DMZ + k.TopPad})
401 | stab_path_r.RotatePath(ctx.RotateCluster, Point{ctx.Xabs*k.U1 + k.DMZ + k.LeftPad, ctx.Yabs*k.U1 + k.DMZ + k.TopPad})
402 | }
403 | k.Layers[SWITCHLAYER].CutPolys = append(k.Layers[SWITCHLAYER].CutPolys, stab_path_l)
404 | k.Layers[SWITCHLAYER].CutPolys = append(k.Layers[SWITCHLAYER].CutPolys, stab_path_r)
405 | } else { // not a known size, draw a coster instead...
406 | key.DrawCostarStab(k, c, ctx, vertical, flip_stab)
407 | }
408 | }
409 |
--------------------------------------------------------------------------------
/polygon.go:
--------------------------------------------------------------------------------
1 | package kad
2 |
3 | import (
4 | "log"
5 | "math"
6 | "strings"
7 |
8 | "github.com/Knetic/govaluate"
9 | clipper "github.com/swill/go.clipper"
10 | )
11 |
12 | const (
13 | CLIP_DIST = 0.7 // In order to just clean duplicate points: .7*.7 = 0.49 < 0.5
14 | )
15 |
16 | type Point struct { // point, saving space as it is used a LOT
17 | X, Y float64
18 | }
19 |
20 | type Path []Point
21 |
22 | type CustomPolygon struct {
23 | Diameter float64 `json:"diameter"`
24 | Height float64 `json:"height"`
25 | Layers []string `json:"layers"`
26 | Op string `json:"op"`
27 | Points string `json:"points"`
28 | Polygon string `json:"polygon"`
29 | Radius float64 `json:"radius"`
30 | RelTo string `json:"rel_to"`
31 | RelAbs string `json:"-"`
32 | Width float64 `json:"width"`
33 | }
34 |
35 | // Sets the path to the absolute positioning of the Path relative to an origin Point 'r'.
36 | func (ps Path) Rel(r Point) {
37 | for i := range ps {
38 | ps[i].X += r.X
39 | ps[i].Y += r.Y
40 | }
41 | }
42 |
43 | // Copies the Path
44 | func (ps Path) Copy() Path {
45 | dup := Path{}
46 | for i := range ps {
47 | dup = append(dup, Point{ps[i].X, ps[i].Y})
48 | }
49 | return dup
50 | }
51 |
52 | // Rotates each point in a set and rotates them 'r' degrees around 'a'.
53 | func (ps Path) RotatePath(r float64, a Point) {
54 | for i := range ps {
55 | px := ps[i].X
56 | py := ps[i].Y
57 | ps[i].X = math.Cos(radians(r))*(px-a.X) - math.Sin(radians(r))*(py-a.Y) + a.X
58 | ps[i].Y = math.Sin(radians(r))*(px-a.X) + math.Cos(radians(r))*(py-a.Y) + a.Y
59 | }
60 | }
61 |
62 | // SplitOnAxis path to be drawn by SVGo
63 | func (ps Path) SplitOnAxis() ([]float64, []float64) {
64 | xs := make([]float64, 0)
65 | ys := make([]float64, 0)
66 | for i := range ps {
67 | xs = append(xs, ps[i].X)
68 | ys = append(ys, ps[i].Y)
69 | }
70 | return xs, ys
71 | }
72 |
73 | func (ps Path) ToClipperPath() clipper.Path {
74 | p := make(clipper.Path, 0)
75 | for i := range ps {
76 | p = append(p, &clipper.IntPoint{clipper.CInt(ps[i].X * PRECISION), clipper.CInt(ps[i].Y * PRECISION)})
77 | }
78 | c := clipper.NewClipper(clipper.IoNone)
79 | p = c.CleanPolygon(p, CLIP_DIST) // clean duplicates
80 | return p
81 | }
82 |
83 | func FromClipperPath(cp clipper.Path) Path {
84 | c := clipper.NewClipper(clipper.IoNone)
85 | cp = c.CleanPolygon(cp, CLIP_DIST) // clean duplicates
86 | p := make(Path, 0)
87 | for i := range cp {
88 | p = append(p, Point{float64(cp[i].X) / PRECISION, float64(cp[i].Y) / PRECISION})
89 | }
90 | return p
91 | }
92 |
93 | // Finalize the polygons before they go for file processing
94 | func (k *KAD) FinalizePolygons() {
95 | has_err := false
96 | corner_segments := 20
97 | if k.Fillet == 0 {
98 | corner_segments = 0 // square corner
99 | }
100 | for _, layer := range k.Result.Plates {
101 | // handle layer specific details
102 | switch {
103 | case layer == OPENLAYER:
104 | usb_shift := k.Case.UsbLocation
105 | if usb_shift < -(k.Width/2 - k.Case.EdgeWidth - k.Case.UsbWidth/2) {
106 | usb_shift = -(k.Width/2 - k.Case.EdgeWidth - k.Case.UsbWidth/2)
107 | }
108 | if usb_shift > (k.Width/2 - k.Case.EdgeWidth - k.Case.UsbWidth/2) {
109 | usb_shift = k.Width/2 - k.Case.EdgeWidth - k.Case.UsbWidth/2
110 | }
111 | usb_width := k.Case.UsbWidth
112 | if usb_width > (k.Width - 2*k.Case.EdgeWidth - 2*k.Kerf) {
113 | usb_width = k.Width - 2*k.Case.EdgeWidth - 2*k.Kerf
114 | usb_shift = 0
115 | }
116 | c := Point{k.LayoutCenter.X + usb_shift, k.DMZ + k.TopPad/2 + k.Kerf}
117 | usb_pts := Path{
118 | {-usb_width/2 + k.Kerf, -k.TopPad/2 - k.Kerf}, {usb_width/2 - k.Kerf, -k.TopPad/2 - k.Kerf},
119 | {usb_width/2 - k.Kerf, k.TopPad/2 + k.Kerf}, {-usb_width/2 + k.Kerf, k.TopPad/2 + k.Kerf}}
120 | usb_pts.Rel(c)
121 | // overlap top side so it is completely removed...
122 | usb_pts[0].Y -= 1
123 | usb_pts[1].Y -= 1
124 | k.Layers[layer].CutPolys = append(k.Layers[layer].CutPolys, usb_pts)
125 |
126 | mid_pts := Path{
127 | {-k.Width/2 + 2*k.Kerf + k.Case.LeftWidth, -k.Height/2 + 2*k.Kerf + k.Case.TopWidth},
128 | {k.Width/2 - 2*k.Kerf - k.Case.RightWidth, -k.Height/2 + 2*k.Kerf + k.Case.TopWidth},
129 | {k.Width/2 - 2*k.Kerf - k.Case.RightWidth, k.Height/2 - 2*k.Kerf - k.Case.BottomWidth},
130 | {-k.Width/2 + 2*k.Kerf + k.Case.LeftWidth, k.Height/2 - 2*k.Kerf - k.Case.BottomWidth}}
131 | mid_pts.Rel(k.CaseCenter)
132 | k.Layers[layer].CutPolys = append(k.Layers[layer].CutPolys, mid_pts)
133 |
134 | case layer == CLOSEDLAYER:
135 | mid_pts := Path{
136 | {-k.Width/2 + 2*k.Kerf + k.Case.LeftWidth, -k.Height/2 + 2*k.Kerf + k.Case.TopWidth},
137 | {k.Width/2 - 2*k.Kerf - k.Case.RightWidth, -k.Height/2 + 2*k.Kerf + k.Case.TopWidth},
138 | {k.Width/2 - 2*k.Kerf - k.Case.RightWidth, k.Height/2 - 2*k.Kerf - k.Case.BottomWidth},
139 | {-k.Width/2 + 2*k.Kerf + k.Case.LeftWidth, k.Height/2 - 2*k.Kerf - k.Case.BottomWidth}}
140 | mid_pts.Rel(k.CaseCenter)
141 | k.Layers[layer].CutPolys = append(k.Layers[layer].CutPolys, mid_pts)
142 | }
143 |
144 | // starting point for the 'keep' polygon
145 | keep_poly := RoundRectanglePolygon(k.DMZ+(k.Width/2), k.DMZ+(k.Height/2),
146 | k.Width, k.Height, k.Fillet, corner_segments)
147 | k.Layers[layer].KeepPolys = []Path{keep_poly}
148 |
149 | // handle custom polygons added to this drawing
150 | for _, cp := range k.CustomPolygons {
151 | if in_strings(layer, cp.Layers) { // apply this custom polygon to this layer
152 | paths := k.ParsePoints(cp.Points, cp.RelTo, true)
153 | paths = append(paths, k.ParsePoints(cp.Points, cp.RelAbs, false)...)
154 | polygons := make([]Path, 0)
155 | if len(paths) > 0 && len(paths[0]) > 0 {
156 | switch cp.Polygon {
157 | case "custom-circle":
158 | for _, path := range paths {
159 | for _, pt := range path {
160 | polygons = append(polygons, CirclePolygon(pt.X, pt.Y, cp.Diameter/2, 20))
161 | }
162 | }
163 | break
164 | case "custom-superellipse":
165 | for _, path := range paths {
166 | for _, pt := range path {
167 | polygons = append(polygons, SuperellipsePolygon(pt.X, pt.Y, cp.Radius, 20))
168 | }
169 | }
170 | break
171 | case "custom-rectangle":
172 | for _, path := range paths {
173 | for _, pt := range path {
174 | polygons = append(polygons, RoundRectanglePolygon(pt.X, pt.Y, cp.Width, cp.Height, 0, 0))
175 | }
176 | }
177 | break
178 | case "custom-rounded-rectangle":
179 | for _, path := range paths {
180 | for _, pt := range path {
181 | polygons = append(polygons, RoundRectanglePolygon(pt.X, pt.Y, cp.Width, cp.Height, cp.Radius, 20))
182 | }
183 | }
184 | break
185 | case "custom-path":
186 | for _, path := range paths {
187 | if len(path) > 2 {
188 | polygons = append(polygons, path)
189 | }
190 | }
191 | break
192 | }
193 | }
194 | // apply the polygons to the kad
195 | if len(polygons) > 0 {
196 | switch cp.Op {
197 | case "add":
198 | k.Layers[layer].KeepPolys = append(k.Layers[layer].KeepPolys, polygons...)
199 | break
200 | case "cut":
201 | k.Layers[layer].CutPolys = append(k.Layers[layer].CutPolys, polygons...)
202 | break
203 | }
204 | }
205 | }
206 | }
207 |
208 | // union all of the cut polygons to make sure we don't have any crossing cut paths
209 | if len(k.Layers[layer].CutPolys) > 0 { // union all inside
210 | c := clipper.NewClipper(clipper.IoNone)
211 | c.AddPath(Path{}.ToClipperPath(), clipper.PtSubject, true)
212 | for _, poly := range k.Layers[layer].CutPolys {
213 | c.AddPath(poly.ToClipperPath(), clipper.PtClip, true)
214 | }
215 | solution, ok := c.Execute1(clipper.CtUnion, clipper.PftNonZero, clipper.PftNonZero)
216 | if !ok {
217 | log.Printf("ERROR drawing layout: %s, %s", k.Hash, layer)
218 | log.Printf("ERROR drawing inner union...\nCutPolys: %#v", k.Layers[layer].CutPolys)
219 | has_err = true
220 | } else {
221 | cut_union := make([]Path, 0)
222 | for _, cpath := range solution {
223 | cut_union = append(cut_union, FromClipperPath(cpath))
224 | }
225 | k.Layers[layer].CutPolys = cut_union
226 | }
227 | }
228 |
229 | // union all of the keep polygons to make sure we don't have any crossing keep paths
230 | if len(k.Layers[layer].KeepPolys) > 0 { // union all inside
231 | c := clipper.NewClipper(clipper.IoNone)
232 | c.AddPath(Path{}.ToClipperPath(), clipper.PtSubject, true)
233 | for _, poly := range k.Layers[layer].KeepPolys {
234 | c.AddPath(poly.ToClipperPath(), clipper.PtClip, true)
235 | }
236 | solution, ok := c.Execute1(clipper.CtUnion, clipper.PftNonZero, clipper.PftNonZero)
237 | if !ok {
238 | log.Printf("ERROR drawing layout: %s, %s", k.Hash, layer)
239 | log.Printf("ERROR drawing inner union...\nKeepPolys: %#v", k.Layers[layer].KeepPolys)
240 | has_err = true
241 | } else {
242 | keep_union := make([]Path, 0)
243 | for _, cpath := range solution {
244 | keep_union = append(keep_union, FromClipperPath(cpath))
245 | }
246 | k.Layers[layer].KeepPolys = keep_union
247 | }
248 | }
249 |
250 | // at this point we have everything we need to evaluate if any cut polygons cross the exterior keep boundary
251 |
252 | // get the surface areas before we 'cut' from the 'keep' paths
253 | k.Result.Details[layer].Area = SurfaceArea(k.Layers[layer].KeepPolys) - SurfaceArea(k.Layers[layer].CutPolys)
254 |
255 | // get the difference when we do the cut from keep
256 | if len(k.Layers[layer].CutPolys) > 0 { // difference with cuts
257 | c := clipper.NewClipper(clipper.IoNone)
258 | for _, poly := range k.Layers[layer].KeepPolys {
259 | c.AddPath(poly.ToClipperPath(), clipper.PtSubject, true)
260 | }
261 | for _, poly := range k.Layers[layer].CutPolys {
262 | c.AddPath(poly.ToClipperPath(), clipper.PtClip, true)
263 | }
264 | solution, ok := c.Execute1(clipper.CtDifference, clipper.PftNonZero, clipper.PftNonZero)
265 | if !ok {
266 | log.Printf("ERROR drawing layout: %s, %s", k.Hash, layer)
267 | log.Printf("ERROR drawing outer / inner difference...\nKeepPolys: %#v\nCutPolys: %#v",
268 | k.Layers[layer].KeepPolys, k.Layers[layer].CutPolys)
269 | has_err = true
270 | } else {
271 | keep_polys := make([]Path, 0)
272 | for _, cpath := range solution {
273 | keep_polys = append(keep_polys, FromClipperPath(cpath))
274 | }
275 | k.Layers[layer].KeepPolys = keep_polys
276 | }
277 | }
278 | }
279 |
280 | if has_err {
281 | log.Printf("ERROR Context (raw layout):\n%#v", k.RawLayout)
282 | }
283 | }
284 |
285 | // Parse the points passed in for custom polygons
286 | func (k *KAD) ParsePoints(points_str, rel_to_str string, rel_center bool) []Path {
287 | get_points := func(point_str string) Path {
288 | points := make(Path, 0)
289 | point_str = strings.ToLower(strings.Replace(point_str, " ", "", -1)) // remove spaces and make lower case
290 | point_ary := strings.Split(point_str, ";")
291 | for _, pt := range point_ary {
292 | pt = strings.Replace(pt, "[", "", -1)
293 | pt = strings.Replace(pt, "]", "", -1)
294 | pts := strings.Split(pt, ",")
295 | point_error := false
296 | if len(pts) == 2 {
297 | params := make(map[string]interface{}, 8)
298 | params["x"] = k.Width / 2
299 | params["y"] = k.Height / 2
300 |
301 | var err error
302 | var x_exp, y_exp *govaluate.EvaluableExpression
303 | var x_val, y_val interface{}
304 | x_exp, err = govaluate.NewEvaluableExpression(pts[0])
305 | if err != nil {
306 | log.Printf("ERROR Govaluating expression: %s", pts[0])
307 | point_error = true
308 | }
309 | if !point_error {
310 | x_val, err = x_exp.Evaluate(params)
311 | if err != nil {
312 | log.Printf("ERROR Govaluating '%s' w/ params: %#v", pts[0], params)
313 | point_error = true
314 | }
315 | }
316 | if !point_error {
317 | y_exp, err = govaluate.NewEvaluableExpression(pts[1])
318 | if err != nil {
319 | log.Printf("ERROR Govaluating expression: %s", pts[1])
320 | point_error = true
321 | }
322 | }
323 | if !point_error {
324 | y_val, err = y_exp.Evaluate(params)
325 | if err != nil {
326 | log.Printf("ERROR Govaluating '%s' w/ params: %#v", pts[1], params)
327 | point_error = true
328 | }
329 | }
330 |
331 | if !point_error {
332 | points = append(points, Point{x_val.(float64), y_val.(float64)})
333 | }
334 | }
335 | }
336 | return points
337 | }
338 | paths := make([]Path, 0)
339 | points := get_points(points_str)
340 | rel_to := get_points(rel_to_str)
341 | if rel_center {
342 | rel_to.Rel(k.CaseCenter)
343 | }
344 | if len(rel_to) > 0 {
345 | for p := range rel_to {
346 | rel_points := points.Copy()
347 | rel_points.Rel(rel_to[p])
348 | paths = append(paths, rel_points)
349 | }
350 | }
351 | return paths
352 | }
353 |
354 | // create a rectangle as a polygon with optional rounded corners.
355 | // set 'r' and 's' to zero to have a non-rounded corner.
356 | func RoundRectanglePolygon(cx, cy, w, h, r float64, s int) Path {
357 | // make a rounded corner
358 | corner := func(x, y, r, a float64, s int, ps *Path) {
359 | n := float64(s)
360 | p := &Point{x, y}
361 | *ps = append(*ps, *p)
362 | la := radians(90 - (90.0 / (2 * n))) // angle to determine the segment length
363 | for j := 1.0; j < n+1; j++ {
364 | sa := radians(90 - ((90.0 / (2 * n)) * (2*j - 1)) + a) // angle of the vector of each successive segment
365 | p.X += 2 * r * math.Cos(la) * math.Sin(sa)
366 | p.Y += 2 * r * math.Cos(la) * math.Cos(sa)
367 | *ps = append(*ps, *p)
368 | }
369 | }
370 | // draw the rounded rectangle
371 | pts := make(Path, 0)
372 | corner((cx + w/2 - r), (cy - h/2), r, 0, s, &pts)
373 | corner((cx + w/2), (cy + h/2 - r), r, -90, s, &pts)
374 | corner((cx - w/2 + r), (cy + h/2), r, 180, s, &pts)
375 | corner((cx - w/2), (cy - h/2 + r), r, 90, s, &pts)
376 | return pts
377 | }
378 |
379 | // create a circle as a polygon with each quarter made up of 's' segments.
380 | func CirclePolygon(cx, cy, r float64, s int) Path {
381 | // make a circle
382 | circle := func(x, y, r float64, s int, ps *Path) {
383 | n := float64(s)
384 | p := &Point{x, y}
385 | *ps = append(*ps, *p)
386 | la := radians(90 - (90.0 / (2 * n))) // angle to determine the segment length
387 | for j := 1.0; j < 4*n; j++ {
388 | sa := radians(90 - ((90.0 / (2 * n)) * (2*j - 1))) // angle of the vector of each successive segment
389 | p.X += 2 * r * math.Cos(la) * math.Sin(sa)
390 | p.Y += 2 * r * math.Cos(la) * math.Cos(sa)
391 | *ps = append(*ps, *p)
392 | }
393 | }
394 | // draw the circle
395 | pts := make(Path, 0)
396 | circle(cx, cy-r, r, s, &pts)
397 | return pts
398 | }
399 |
400 | // create a superellipse as a polygon with each quarter made up of 's' segments.
401 | func SuperellipsePolygon(cx, cy, r float64, s int) Path {
402 | // make a concave quadrant
403 | quadrant := func(x, y, r, a float64, s int, ps *Path) {
404 | n := float64(s)
405 | p := &Point{x, y}
406 | *ps = append(*ps, *p)
407 | la := radians(90 + (90.0 / (2 * n))) // angle to determine the segment length
408 | for j := 1.0; j < n+1; j++ {
409 | sa := radians(90 + ((90.0 / (2 * n)) * (2*j - 1)) + a) // angle of the vector of each successive segment
410 | p.X += 2 * r * math.Cos(la) * math.Sin(sa)
411 | p.Y += 2 * r * math.Cos(la) * math.Cos(sa)
412 | *ps = append(*ps, *p)
413 | }
414 | }
415 | // draw the superellipse
416 | pts := make(Path, 0)
417 | quadrant((cx), (cy - r), r, 90, s, &pts)
418 | quadrant((cx + r), (cy), r, 0, s, &pts)
419 | quadrant((cx), (cy + r), r, -90, s, &pts)
420 | quadrant((cx - r), (cy), r, 180, s, &pts)
421 | return pts
422 | }
423 |
424 | func SurfaceArea(paths []Path) float64 {
425 | sa := 0.0
426 | for _, path := range paths {
427 | area := 0.0
428 | i := len(path) - 1
429 | for j := 0; j < len(path); j++ {
430 | area += (path[i].X + path[j].X) * (path[i].Y - path[j].Y)
431 | i = j //set previous to current for next pass
432 | }
433 | sa += math.Abs(area / 2)
434 | }
435 | return sa
436 | }
437 |
438 | // convert degrees to radians
439 | func radians(deg float64) float64 {
440 | return (deg * math.Pi) / 180
441 | }
442 |
--------------------------------------------------------------------------------
/test/kad_test.go:
--------------------------------------------------------------------------------
1 | package kad
2 |
3 | import (
4 | "encoding/json"
5 | "strings"
6 | "testing"
7 |
8 | clipper "github.com/swill/go.clipper"
9 | "github.com/swill/kad"
10 | )
11 |
12 | func TestUsageWithJSON(t *testing.T) {
13 | json_str := `{
14 | "switch-type":3,
15 | "stab-type":1,
16 | "layout":[
17 | ["Num Lock","/","*","-"],
18 | [{"f":3},"7\nHome","8\n↑","9\nPgUp",{"h":2}," "],
19 | ["4\n←","5","6\n→"],["1\nEnd","2\n↓","3\nPgDn",{"h":2},"Enter"],
20 | [{"w":2},"0\nIns",".\nDel"]
21 | ],
22 | "case": {
23 | "case-type":"sandwich",
24 | "usb-location":100,
25 | "usb-width":12,
26 | "mount-holes-num":4,
27 | "mount-holes-size":3,
28 | "mount-holes-edge":6
29 | },
30 | "top-padding":9,
31 | "left-padding":9,
32 | "right-padding":9,
33 | "bottom-padding":9,
34 | "fillet":3
35 | }`
36 |
37 | cad := kad.New()
38 |
39 | // force only SVG output
40 | cad.Result.Formats = []string{"svg"}
41 |
42 | // populate the kad object with the request POST json, oh and get the hash...
43 | decoder := json.NewDecoder(strings.NewReader(json_str))
44 | err := decoder.Decode(cad)
45 | if err != nil {
46 | t.Errorf("TestUsageWithJSON: failed to parse json data into KAD file")
47 | return
48 | }
49 |
50 | cad.Hash = "usage_with_json"
51 | cad.FileStore = kad.STORE_LOCAL
52 | cad.FileDirectory = "./output/"
53 | cad.FileServePath = "/test/output/"
54 |
55 | err = cad.Draw()
56 | if err != nil {
57 | t.Errorf("TestUsageWithJSON: failed to Draw the KAD file")
58 | return
59 | }
60 | }
61 |
62 | func TestUsageWithGo(t *testing.T) {
63 | json_str := `{
64 | "layout":[
65 | ["Num Lock","/","*","-"],
66 | [{"f":3},"7\nHome","8\n↑","9\nPgUp",{"h":2}," "],
67 | ["4\n←","5","6\n→"],["1\nEnd","2\n↓","3\nPgDn",{"h":2},"Enter"],
68 | [{"w":2},"0\nIns",".\nDel"]
69 | ]}`
70 |
71 | cad := kad.New()
72 |
73 | // force only SVG output
74 | cad.Result.Formats = []string{"svg"}
75 |
76 | // populate the kad object with the request POST json, oh and get the hash...
77 | decoder := json.NewDecoder(strings.NewReader(json_str))
78 | err := decoder.Decode(cad)
79 | if err != nil {
80 | t.Errorf("TestUsageWithGo: failed to parse json data into KAD file")
81 | return
82 | }
83 |
84 | cad.Hash = "usage_with_go"
85 | cad.FileStore = kad.STORE_LOCAL
86 | cad.FileDirectory = "./output/"
87 | cad.FileServePath = "/test/output/"
88 |
89 | cad.SwitchType = kad.SWITCHMXH
90 | cad.StabType = kad.STABCHERRYCOSTAR
91 | cad.Case.Type = "sandwich"
92 | cad.Case.Holes = 4
93 | cad.Case.HoleDiameter = 3
94 | cad.Case.EdgeWidth = 6
95 | cad.Case.UsbLocation = 100
96 | cad.Case.UsbWidth = 12
97 | cad.TopPad = 9
98 | cad.LeftPad = 9
99 | cad.RightPad = 9
100 | cad.BottomPad = 9
101 | cad.Fillet = 3
102 |
103 | err = cad.Draw()
104 | if err != nil {
105 | t.Errorf("TestUsageWithGo: failed to Draw the KAD file")
106 | return
107 | }
108 | }
109 |
110 | func TestSurfaceArea(t *testing.T) {
111 | cases := []struct {
112 | paths []kad.Path
113 | area float64
114 | }{
115 | {[]kad.Path{{{2, 2}, {2, 4}, {4, 4}, {4, 2}}}, 4},
116 | {[]kad.Path{{{2, 2}, {4, 2}, {4, 4}, {2, 4}}}, 4},
117 | }
118 | for _, c := range cases {
119 | sa := kad.SurfaceArea(c.paths)
120 | if sa != c.area {
121 | t.Errorf("SurfaceArea([]Path) == %f, expected %f", sa, c.area)
122 | }
123 | }
124 | }
125 |
126 | func TestClipperCleanPolygon(t *testing.T) {
127 | cases := []struct {
128 | input clipper.Path
129 | output clipper.Path
130 | }{
131 | {
132 | clipper.Path{{1, 1}, {1, 2}, {1, 2}, {2, 2}, {2, 2}, {2, 1}},
133 | clipper.Path{{1, 1}, {1, 2}, {2, 2}, {2, 1}},
134 | },
135 | {
136 | clipper.Path{{5, 5}, {5, 10}, {5, 10}, {10, 10}, {10, 10}, {10, 5}},
137 | clipper.Path{{5, 5}, {5, 10}, {10, 10}, {10, 5}},
138 | },
139 | }
140 | for _, c := range cases {
141 | p := clipper.NewClipper(clipper.IoNone)
142 | r := p.CleanPolygon(c.input, .7) // In order to just clean duplicate points: .7*.7 = 0.49 < 0.5
143 | if len(r) != len(c.output) {
144 | t.Errorf("CleanPolygon(clipper.Path) == %#v, expected %#v", r, c.output)
145 | }
146 | }
147 | }
148 |
--------------------------------------------------------------------------------
/test/key_test.go:
--------------------------------------------------------------------------------
1 | package kad
2 |
3 | import (
4 | "encoding/json"
5 | "strings"
6 | "testing"
7 |
8 | "github.com/swill/kad"
9 | )
10 |
11 | func TestSwitchTypes(t *testing.T) {
12 | json_str := `{
13 | "layout":[
14 | [{"_t":1},"", {"_t":1,"w":2,"_s":0},"", {"_t":1,"w":2,"_s":1},"", {"_t":1,"w":2,"_s":2},"", {"_t":1,"w":2,"_s":3},"", {"_t":1,"w":2,"_s":4},""],
15 | [{"_t":2},"", {"_t":2,"w":2,"_s":0},"", {"_t":2,"w":2,"_s":1},"", {"_t":2,"w":2,"_s":2},"", {"_t":2,"w":2,"_s":3},"", {"_t":2,"w":2,"_s":4},""],
16 | [{"_t":3},"", {"_t":3,"w":2,"_s":0},"", {"_t":3,"w":2,"_s":1},"", {"_t":3,"w":2,"_s":2},"", {"_t":3,"w":2,"_s":3},"", {"_t":3,"w":2,"_s":4},""],
17 | [{"_t":4},"", {"_t":4,"w":2,"_s":0},"", {"_t":4,"w":2,"_s":1},"", {"_t":4,"w":2,"_s":2},"", {"_t":4,"w":2,"_s":3},"", {"_t":4,"w":2,"_s":4},""]
18 | ]}`
19 |
20 | cad := kad.New()
21 |
22 | // force only SVG output
23 | cad.Result.Formats = []string{"svg"}
24 |
25 | // populate the kad object with the request POST json, oh and get the hash...
26 | decoder := json.NewDecoder(strings.NewReader(json_str))
27 | err := decoder.Decode(cad)
28 | if err != nil {
29 | t.Errorf("TestSwitchTypes: failed to parse json data into KAD file")
30 | return
31 | }
32 |
33 | cad.Hash = "switch_types"
34 | cad.FileStore = kad.STORE_LOCAL
35 | cad.FileDirectory = "./output/"
36 | cad.FileServePath = "/test/output/"
37 |
38 | err = cad.Draw()
39 | if err != nil {
40 | t.Errorf("TestSwitchTypes: failed to Draw the KAD file")
41 | return
42 | }
43 | }
44 |
45 | func TestStabCherrySize(t *testing.T) {
46 | json_str := `{
47 | "layout":[
48 | [{"w":2},"", {"w":10},""],
49 | [{"w":3},"", {"w":9},""],
50 | [{"w":4},"", {"w":8},""],
51 | [{"w":2.25},"", {"w":2.75},"", {"w":7},""],
52 | [{"w":5.5},"", {"w":6.5},""],
53 | [{"w":1.25},"", {"w":4.5},"", {"w":6.25},""],
54 | [{"w":6},"", {"w":6},""]
55 | ]}`
56 |
57 | cad := kad.New()
58 |
59 | // force only SVG output
60 | cad.Result.Formats = []string{"svg"}
61 |
62 | // populate the kad object with the request POST json, oh and get the hash...
63 | decoder := json.NewDecoder(strings.NewReader(json_str))
64 | err := decoder.Decode(cad)
65 | if err != nil {
66 | t.Errorf("TestStabCherrySize: failed to parse json data into KAD file")
67 | return
68 | }
69 |
70 | cad.Hash = "stab_cherry_size"
71 | cad.FileStore = kad.STORE_LOCAL
72 | cad.FileDirectory = "./output/"
73 | cad.FileServePath = "/test/output/"
74 |
75 | err = cad.Draw()
76 | if err != nil {
77 | t.Errorf("TestStabCherrySize: failed to Draw the KAD file")
78 | return
79 | }
80 | }
81 |
82 | func TestStabAlpsSize(t *testing.T) {
83 | json_str := `{
84 | "layout":[
85 | [{"w":1.5},"", {"w":6.5},""],
86 | [{"w":1.75},"", {"w":6.25},""],
87 | [{"w":1},"", {"w":2},"", {"w":2.25},"", {"w":2.75},""]
88 | ]}`
89 |
90 | cad := kad.New()
91 |
92 | // force only SVG output
93 | cad.Result.Formats = []string{"svg"}
94 |
95 | // populate the kad object with the request POST json, oh and get the hash...
96 | decoder := json.NewDecoder(strings.NewReader(json_str))
97 | err := decoder.Decode(cad)
98 | if err != nil {
99 | t.Errorf("TestStabAlpsSize: failed to parse json data into KAD file")
100 | return
101 | }
102 |
103 | cad.Hash = "stab_alps_size"
104 | cad.FileStore = kad.STORE_LOCAL
105 | cad.FileDirectory = "./output/"
106 | cad.FileServePath = "/test/output/"
107 |
108 | cad.SwitchType = kad.SWITCHALPS
109 | cad.StabType = kad.STABALPS
110 |
111 | err = cad.Draw()
112 | if err != nil {
113 | t.Errorf("TestStabAlpsSize: failed to Draw the KAD file")
114 | return
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/test/output/stab_alps_size_switch.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
29 |
--------------------------------------------------------------------------------
/test/output/stab_cherry_size_switch.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
25 |
--------------------------------------------------------------------------------
/test/output/switch_types_switch.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
49 |
--------------------------------------------------------------------------------
/test/output/usage_with_go_bottom.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
13 |
--------------------------------------------------------------------------------
/test/output/usage_with_go_closed.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
14 |
--------------------------------------------------------------------------------
/test/output/usage_with_go_open.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
13 |
--------------------------------------------------------------------------------
/test/output/usage_with_go_switch.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
30 |
--------------------------------------------------------------------------------
/test/output/usage_with_go_top.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
14 |
--------------------------------------------------------------------------------
/test/output/usage_with_json_bottom.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
13 |
--------------------------------------------------------------------------------
/test/output/usage_with_json_closed.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
14 |
--------------------------------------------------------------------------------
/test/output/usage_with_json_open.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
13 |
--------------------------------------------------------------------------------
/test/output/usage_with_json_switch.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
30 |
--------------------------------------------------------------------------------
/test/output/usage_with_json_top.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
14 |
--------------------------------------------------------------------------------