Sıfırdan Yeni Bir Depo Başlatın:
Mevcut Bir Git Deposu veya Klasörü Gönderin:
Hataları Geri Alma, İptal & Temizlik:
Son commit'i geri al (yapılan değişiklikleri korur):
git reset --soft HEAD~1
Yapılan yerel değişiklikleri iptal et (çalışma ağacını temizler):
git restore .
Takip edilmeyen gereksiz dosyaları sil:
git clean -fd
Değişiklikleri geçici sakla ve geri getir (stash):
git stash git stash pop
Dal (Branch) ve Sürüm Etiketleri:
Yeni dal aç ve geçiş yap:
git checkout -b yeni-ozellik git push -u origin yeni-ozellik
Sürüm etiketi (tag) oluştur ve gönder:
git tag -a v1.0.0 -m "Sürüm 1.0.0" git push origin --tags
release: publish v1.0.0
@@ -38,4 +38,4 @@ The app runs at `http://127.0.0.1:3000/` by default.
|
||||
|
||||
## Contribution Licensing
|
||||
|
||||
Unless explicitly agreed otherwise in writing, by submitting a contribution you license it under the MIT License. See [LICENSE](../LICENSE).
|
||||
Unless explicitly agreed otherwise in writing, by submitting a contribution you license it under the GNU Affero General Public License v3.0 only (`AGPL-3.0-only`). See [LICENSE](../LICENSE).
|
||||
@@ -1,21 +1,661 @@
|
||||
MIT License
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (c) 2026 SketchForge contributors
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
Preamble
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
@@ -15,11 +15,11 @@
|
||||
</table>
|
||||
|
||||
<p>
|
||||
<a href="LICENSE"><img alt="MIT license" src="https://img.shields.io/badge/license-MIT-16a34a"></a>
|
||||
<a href="LICENSE"><img alt="GNU AGPLv3 license" src="https://img.shields.io/badge/license-AGPLv3-663399"></a>
|
||||
<a href="https://github.com/Formsmith746/SketchForge-3D/stargazers"><img alt="Star SketchForge on GitHub" src="docs/media/badges/github-star.svg"></a>
|
||||
<a href="https://github.com/sponsors/Formsmith746"><img alt="Sponsor SketchForge on GitHub" src="docs/media/badges/github-sponsor.svg"></a>
|
||||
<img alt="Local first" src="https://img.shields.io/badge/local--first-no%20account-0ea5e9">
|
||||
<img alt="Version v0.9.0" src="https://img.shields.io/badge/version-v0.9.0-2563eb">
|
||||
<img alt="Version v1.0.0" src="https://img.shields.io/badge/version-v1.0.0-2563eb">
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -212,19 +212,38 @@ docker compose -f deploy/docker/compose.yaml down
|
||||
|
||||
### Update SketchForge Later
|
||||
|
||||
If you used Git:
|
||||
The home dashboard's **Settings** panel checks the official version and displays an update prompt when a newer version is available. It never installs an update automatically. Choosing **Not now** dismisses only that version, so a later release will be offered again.
|
||||
|
||||
If you used Git, update the existing checkout in place. You do not need to remove or download the repository again:
|
||||
|
||||
```bash
|
||||
git pull
|
||||
docker compose -f deploy/docker/compose.yaml up --build -d
|
||||
```
|
||||
|
||||
If you use the prebuilt GHCR Compose file:
|
||||
|
||||
```bash
|
||||
docker compose -f deploy/docker/compose-ghcr.yaml pull sketchforge
|
||||
docker compose -f deploy/docker/compose-ghcr.yaml up -d --no-deps sketchforge
|
||||
```
|
||||
|
||||
If you downloaded the ZIP, download the newest ZIP, extract it, and run:
|
||||
|
||||
```bash
|
||||
docker compose -f deploy/docker/compose.yaml up --build -d
|
||||
```
|
||||
|
||||
Application updates do not clear private projects stored in the browser. Docker shared projects remain in the existing `sketchforge-shared-projects` volume or the host directory configured with `SKETCHFORGE_SHARED_PROJECTS_VOLUME`. Never add `--volumes` or `-v` to an update command.
|
||||
|
||||
For an administrator-managed one-click installation, configure all of the following server variables:
|
||||
|
||||
- `SKETCHFORGE_UPDATE_TRIGGER_URL`: an internal HTTPS endpoint that pulls/recreates only the SketchForge application while retaining its existing project volume.
|
||||
- `SKETCHFORGE_UPDATE_ADMIN_KEY`: the key the administrator must enter in the confirmation dialog.
|
||||
- `SKETCHFORGE_UPDATE_TRIGGER_TOKEN` (optional): a bearer token SketchForge sends only to the internal update service.
|
||||
|
||||
Without an administrator-managed trigger, the confirmation opens these safe update instructions instead of granting the web container access to the Docker socket.
|
||||
|
||||
### Docker Troubleshooting
|
||||
|
||||
- **`docker` is not recognized**: install Docker Desktop, open it, and try again.
|
||||
@@ -326,7 +345,11 @@ Please do not open public issues for security-sensitive reports. Read [.github/S
|
||||
|
||||
## License
|
||||
|
||||
MIT. See [LICENSE](LICENSE).
|
||||
Copyright © 2026 SketchForge contributors.
|
||||
|
||||
SketchForge is licensed under the **GNU Affero General Public License v3.0 only** (`AGPL-3.0-only`). If you modify SketchForge and let users interact with the modified version over a network, you must offer those users the corresponding source code under the same license. See [LICENSE](LICENSE).
|
||||
|
||||
The application exposes a **Source** link in the dashboard. Operators distributing or hosting a modified build should set `NEXT_PUBLIC_SOURCE_CODE_URL` at build time to the public URL containing that build's complete corresponding source code.
|
||||
|
||||
## SketchForge MCP Skill
|
||||
|
||||
|
||||
@@ -1 +1,7 @@
|
||||
# No environment variables are required for local development.
|
||||
|
||||
# Optional administrator-managed update trigger. Keep these server-side; never
|
||||
# prefix them with NEXT_PUBLIC_. The trigger must preserve /data/projects.
|
||||
# SKETCHFORGE_UPDATE_TRIGGER_URL=https://updater.internal/sketchforge
|
||||
# SKETCHFORGE_UPDATE_ADMIN_KEY=replace-with-a-long-random-key
|
||||
# SKETCHFORGE_UPDATE_TRIGGER_TOKEN=optional-internal-service-token
|
||||
|
After Width: | Height: | Size: 163 KiB |
|
After Width: | Height: | Size: 161 KiB |
|
After Width: | Height: | Size: 160 KiB |
|
After Width: | Height: | Size: 170 KiB |
|
After Width: | Height: | Size: 167 KiB |
|
After Width: | Height: | Size: 166 KiB |
|
After Width: | Height: | Size: 169 KiB |
|
After Width: | Height: | Size: 169 KiB |
|
After Width: | Height: | Size: 165 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 70 KiB |
|
After Width: | Height: | Size: 400 KiB |
|
After Width: | Height: | Size: 43 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 49 KiB |
|
After Width: | Height: | Size: 54 KiB |
|
After Width: | Height: | Size: 70 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 70 KiB |
@@ -0,0 +1,166 @@
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import { NextResponse } from "next/server";
|
||||
import { appUpdateIsAvailable, OFFICIAL_UPDATE_GUIDE_URL, type AppUpdateStatus } from "@/lib/appUpdates";
|
||||
import { SKF_CREATED_WITH_VERSION } from "@/lib/skfProject";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
export const revalidate = false;
|
||||
|
||||
const DEFAULT_MANIFEST_URL = "https://raw.githubusercontent.com/Formsmith746/SketchForge-3D/main/package.json";
|
||||
const UPDATE_CACHE_MS = 5 * 60 * 1000;
|
||||
const UPDATE_TRIGGER_COOLDOWN_MS = 15 * 1000;
|
||||
|
||||
let cachedLatest: { version: string; expiresAt: number } | null = null;
|
||||
let nextTriggerAt = 0;
|
||||
|
||||
function sameOriginRequest(request: Request) {
|
||||
const origin = request.headers.get("origin");
|
||||
if (!origin) return true;
|
||||
try {
|
||||
const requestUrl = new URL(request.url);
|
||||
const forwardedHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim();
|
||||
const forwardedProtocol = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
|
||||
const host = forwardedHost || request.headers.get("host") || requestUrl.host;
|
||||
const protocol = forwardedProtocol || requestUrl.protocol.replace(/:$/, "");
|
||||
return new URL(origin).origin === `${protocol}://${host}`;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function safeEqual(left: string, right: string) {
|
||||
const leftBytes = Buffer.from(left);
|
||||
const rightBytes = Buffer.from(right);
|
||||
return leftBytes.length === rightBytes.length && timingSafeEqual(leftBytes, rightBytes);
|
||||
}
|
||||
|
||||
function updateTriggerUrl() {
|
||||
const configured = process.env.SKETCHFORGE_UPDATE_TRIGGER_URL?.trim();
|
||||
if (!configured) return null;
|
||||
try {
|
||||
const url = new URL(configured);
|
||||
return url.protocol === "http:" || url.protocol === "https:" ? url : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function latestOfficialVersion(force = false) {
|
||||
if (!force && cachedLatest && cachedLatest.expiresAt > Date.now()) return cachedLatest.version;
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 7_500);
|
||||
try {
|
||||
const response = await fetch(process.env.SKETCHFORGE_UPDATE_MANIFEST_URL?.trim() || DEFAULT_MANIFEST_URL, {
|
||||
cache: "no-store",
|
||||
headers: { Accept: "application/json", "User-Agent": "SketchForge update checker" },
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!response.ok) throw new Error(`Update server returned ${response.status}`);
|
||||
const payload = await response.json() as { version?: unknown };
|
||||
const version = typeof payload.version === "string" ? payload.version.trim() : "";
|
||||
if (!/^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version)) {
|
||||
throw new Error("Update server returned an invalid version");
|
||||
}
|
||||
cachedLatest = { version, expiresAt: Date.now() + UPDATE_CACHE_MS };
|
||||
return version;
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
function updateGuideUrl() {
|
||||
return process.env.SKETCHFORGE_UPDATE_GUIDE_URL?.trim() || OFFICIAL_UPDATE_GUIDE_URL;
|
||||
}
|
||||
|
||||
async function statusResponse(force = false): Promise<AppUpdateStatus> {
|
||||
const trigger = updateTriggerUrl();
|
||||
const adminKeyConfigured = Boolean(process.env.SKETCHFORGE_UPDATE_ADMIN_KEY?.trim());
|
||||
try {
|
||||
const latestVersion = await latestOfficialVersion(force);
|
||||
return {
|
||||
currentVersion: SKF_CREATED_WITH_VERSION,
|
||||
latestVersion,
|
||||
updateAvailable: appUpdateIsAvailable(SKF_CREATED_WITH_VERSION, latestVersion),
|
||||
checkedAt: new Date().toISOString(),
|
||||
updateUrl: updateGuideUrl(),
|
||||
installationReady: Boolean(trigger && adminKeyConfigured),
|
||||
requiresUpdateKey: Boolean(trigger && adminKeyConfigured),
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
currentVersion: SKF_CREATED_WITH_VERSION,
|
||||
latestVersion: null,
|
||||
updateAvailable: false,
|
||||
checkedAt: new Date().toISOString(),
|
||||
updateUrl: updateGuideUrl(),
|
||||
installationReady: Boolean(trigger && adminKeyConfigured),
|
||||
requiresUpdateKey: Boolean(trigger && adminKeyConfigured),
|
||||
checkError: error instanceof Error ? error.message : "Could not check for updates",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const force = new URL(request.url).searchParams.get("force") === "1";
|
||||
return NextResponse.json(await statusResponse(force), { headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
if (!sameOriginRequest(request)) return NextResponse.json({ error: "Updates only accept same-origin requests" }, { status: 403 });
|
||||
const trigger = updateTriggerUrl();
|
||||
const adminKey = process.env.SKETCHFORGE_UPDATE_ADMIN_KEY?.trim() || "";
|
||||
if (!trigger || !adminKey) {
|
||||
return NextResponse.json(
|
||||
{ error: "One-click installation is not configured on this server", updateUrl: updateGuideUrl() },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
|
||||
const suppliedKey = request.headers.get("x-sketchforge-update-key")?.trim() || "";
|
||||
if (!suppliedKey || !safeEqual(suppliedKey, adminKey)) {
|
||||
return NextResponse.json({ error: "The update key is incorrect" }, { status: 401 });
|
||||
}
|
||||
if (Date.now() < nextTriggerAt) {
|
||||
return NextResponse.json({ error: "An update was already requested. Wait a moment before trying again." }, { status: 429 });
|
||||
}
|
||||
|
||||
const status = await statusResponse(true);
|
||||
if (status.checkError) return NextResponse.json({ error: status.checkError }, { status: 502 });
|
||||
if (!status.updateAvailable || !status.latestVersion) {
|
||||
return NextResponse.json({ error: "SketchForge is already up to date", status }, { status: 409 });
|
||||
}
|
||||
|
||||
nextTriggerAt = Date.now() + UPDATE_TRIGGER_COOLDOWN_MS;
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 10_000);
|
||||
try {
|
||||
const triggerToken = process.env.SKETCHFORGE_UPDATE_TRIGGER_TOKEN?.trim();
|
||||
const response = await fetch(trigger, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
...(triggerToken ? { Authorization: `Bearer ${triggerToken}` } : {}),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
application: "SketchForge",
|
||||
currentVersion: status.currentVersion,
|
||||
latestVersion: status.latestVersion,
|
||||
preserveProjectStorage: true,
|
||||
}),
|
||||
cache: "no-store",
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!response.ok) throw new Error(`Update service returned ${response.status}`);
|
||||
return NextResponse.json(
|
||||
{ accepted: true, currentVersion: status.currentVersion, latestVersion: status.latestVersion },
|
||||
{ status: 202, headers: { "Cache-Control": "no-store" } },
|
||||
);
|
||||
} catch (error) {
|
||||
nextTriggerAt = 0;
|
||||
return NextResponse.json({ error: error instanceof Error ? error.message : "Could not start the update" }, { status: 502 });
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { Clock3, EllipsisVertical, FileUp, FolderKanban, Grid3X3, HomeIcon, List, Pencil, Plus, RefreshCw, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react";
|
||||
import { Clock3, EllipsisVertical, FileUp, FolderKanban, Grid3X3, HomeIcon, List, Palette, Pencil, Plus, RefreshCw, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { SketchForgeEditor, importedShapeFromStl, importedShapeFromSvg } from "@/components/SketchForgeEditor";
|
||||
import ChallengesDashboard from "@/components/official/ChallengesDashboard";
|
||||
import { applyAppTheme, readStoredAppTheme, resolveAppTheme, storeAppTheme, type AppThemePreference, type ResolvedAppTheme } from "@/lib/appTheme";
|
||||
import type { AppUpdateStatus } from "@/lib/appUpdates";
|
||||
import { isChallengeTutorialId, type ChallengeTutorialId } from "@/lib/challenges";
|
||||
import { hydrateEditorHistoryState, type EditorHistoryEntry } from "@/lib/editorHistory";
|
||||
import { createLocalId } from "@/lib/localIds";
|
||||
import {
|
||||
@@ -21,7 +24,7 @@ import type { GridSize, ProjectAsset, WorkplaneShape, WorkplaneWorkspaceSettings
|
||||
|
||||
type AppView = "dashboard" | "editor";
|
||||
type ViewMode = "grid" | "list";
|
||||
type DashboardSection = "home" | "shared" | "challenges";
|
||||
type DashboardSection = "home" | "shared" | "challenges" | "customization";
|
||||
type DownloadMode = "browser" | "folder";
|
||||
|
||||
type DashboardProject = {
|
||||
@@ -107,8 +110,11 @@ const PROJECT_SHAPES_STORE_NAME = "projectShapes";
|
||||
const PROJECT_SHAPE_RESOURCES_STORE_NAME = "projectShapeResources";
|
||||
const DOWNLOAD_MODE_STORAGE_KEY = "sketchForge.downloadMode";
|
||||
const DOWNLOAD_FOLDER_STORAGE_KEY = "sketchForge.downloadFolder";
|
||||
const ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY = "sketchForge.activeChallengeTutorial";
|
||||
const DISMISSED_UPDATE_VERSION_STORAGE_KEY = "sketchForge.dismissedUpdateVersion";
|
||||
const PROJECT_ACCENTS: DashboardProject["accent"][] = ["cyan", "green", "gold", "red"];
|
||||
const STATIC_EXPORT_BUILD = process.env.NEXT_PUBLIC_STATIC_EXPORT === "true";
|
||||
const SOURCE_CODE_URL = process.env.NEXT_PUBLIC_SOURCE_CODE_URL?.trim() || "https://github.com/Formsmith746/SketchForge-3D";
|
||||
const EDITOR_SKELETON_MIN_DURATION_MS = 320;
|
||||
const knownProjectResourceKeys = new Map<string, Set<string>>();
|
||||
|
||||
@@ -507,6 +513,7 @@ export default function Home() {
|
||||
const [sharedProjects, setSharedProjects] = useState<SharedProject[]>([]);
|
||||
const [sharedProjectsEnabled, setSharedProjectsEnabled] = useState(false);
|
||||
const [sharedProjectsLoading, setSharedProjectsLoading] = useState(false);
|
||||
const [activeChallengeTutorial, setActiveChallengeTutorial] = useState<ChallengeTutorialId | null>(null);
|
||||
const [projectShapesById, setProjectShapesById] = useState<Record<string, ProjectShapeCacheEntry>>({});
|
||||
const projectsJsonRef = useRef("");
|
||||
const dashboardImportInputRef = useRef<HTMLInputElement | null>(null);
|
||||
@@ -562,6 +569,14 @@ export default function Home() {
|
||||
const requestedProjectId = params.get("project");
|
||||
if (requestedProjectId && storedProjects.some((project) => project.id === requestedProjectId)) {
|
||||
setActiveProjectId(requestedProjectId);
|
||||
try {
|
||||
const storedChallenge = JSON.parse(window.localStorage.getItem(ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY) ?? "null") as { projectId?: string; tutorial?: ChallengeTutorialId } | null;
|
||||
if (storedChallenge?.projectId === requestedProjectId && isChallengeTutorialId(storedChallenge.tutorial)) {
|
||||
setActiveChallengeTutorial(storedChallenge.tutorial);
|
||||
}
|
||||
} catch {
|
||||
window.localStorage.removeItem(ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY);
|
||||
}
|
||||
}
|
||||
startEditorTransition();
|
||||
setEditorStarted(true);
|
||||
@@ -704,7 +719,7 @@ export default function Home() {
|
||||
return sortMode === "name" ? [...filtered].sort((a, b) => a.name.localeCompare(b.name)) : [...filtered].sort((a, b) => b.updatedAt - a.updatedAt);
|
||||
}, [query, sharedProjects, sortMode]);
|
||||
|
||||
const openEditor = (projectId: string | null, options: { allowMissingFromStorage?: boolean } = {}) => {
|
||||
const openEditor = (projectId: string | null, options: { allowMissingFromStorage?: boolean; challengeTutorial?: ChallengeTutorialId | null } = {}) => {
|
||||
if (projectId && typeof window !== "undefined" && !options.allowMissingFromStorage) {
|
||||
const storedProjects = readProjects();
|
||||
const storedProject = storedProjects.find((project) => project.id === projectId);
|
||||
@@ -720,6 +735,25 @@ export default function Home() {
|
||||
setProjects((current) => current.map((project) => (project.id === projectId ? { ...project, updatedAt: Date.now() } : project)));
|
||||
}
|
||||
startEditorTransition();
|
||||
let nextChallengeTutorial = options.challengeTutorial ?? null;
|
||||
if (typeof window !== "undefined" && projectId) {
|
||||
if (nextChallengeTutorial) {
|
||||
window.localStorage.setItem(
|
||||
ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY,
|
||||
JSON.stringify({ projectId, tutorial: nextChallengeTutorial }),
|
||||
);
|
||||
} else {
|
||||
try {
|
||||
const storedChallenge = JSON.parse(window.localStorage.getItem(ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY) ?? "null") as { projectId?: string; tutorial?: ChallengeTutorialId } | null;
|
||||
if (storedChallenge?.projectId === projectId && isChallengeTutorialId(storedChallenge.tutorial)) {
|
||||
nextChallengeTutorial = storedChallenge.tutorial;
|
||||
}
|
||||
} catch {
|
||||
window.localStorage.removeItem(ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY);
|
||||
}
|
||||
}
|
||||
}
|
||||
setActiveChallengeTutorial(nextChallengeTutorial);
|
||||
setActiveProjectId(projectId);
|
||||
setEditorStarted(true);
|
||||
setView("editor");
|
||||
@@ -884,7 +918,7 @@ export default function Home() {
|
||||
});
|
||||
}, []);
|
||||
|
||||
const createAndOpenProject = (name?: string) => {
|
||||
const createAndOpenProject = (name?: string, challengeTutorial: ChallengeTutorialId | null = null) => {
|
||||
const project = newProject(name ?? `Untitled design ${projects.length + 1}`, projects.length);
|
||||
setProjectShapesById((current) => ({
|
||||
...current,
|
||||
@@ -898,7 +932,7 @@ export default function Home() {
|
||||
setDashboardNotice("Could not prepare project shape storage");
|
||||
});
|
||||
setProjects((current) => [project, ...current]);
|
||||
openEditor(project.id, { allowMissingFromStorage: true });
|
||||
openEditor(project.id, { allowMissingFromStorage: true, challengeTutorial });
|
||||
};
|
||||
|
||||
const openSkfProjectFromFile = useCallback(async (file: File, sharedProject?: SharedProject) => {
|
||||
@@ -1072,6 +1106,7 @@ export default function Home() {
|
||||
setProjects((current) => current.map((project) => (project.id === activeProjectId ? { ...project, updatedAt: Date.now() } : project)));
|
||||
}
|
||||
setDashboardSection("home");
|
||||
setActiveChallengeTutorial(null);
|
||||
setEditorLoading(false);
|
||||
setView("dashboard");
|
||||
if (typeof window !== "undefined") {
|
||||
@@ -1158,6 +1193,7 @@ export default function Home() {
|
||||
viewMode={viewMode}
|
||||
onCloseSettings={() => setSettingsOpen(false)}
|
||||
onCreate={() => createAndOpenProject()}
|
||||
onStartChallenge={(challenge) => createAndOpenProject(challenge === "nameplate" ? "Personalized Nameplate" : "Key Tag", challenge)}
|
||||
onDeleteProject={deleteProject}
|
||||
onDownloadFolderChange={setDownloadFolder}
|
||||
onDownloadModeChange={setDownloadMode}
|
||||
@@ -1166,6 +1202,10 @@ export default function Home() {
|
||||
setDashboardSection("challenges");
|
||||
setDashboardNotice("");
|
||||
}}
|
||||
onCustomization={() => {
|
||||
setDashboardSection("customization");
|
||||
setDashboardNotice("");
|
||||
}}
|
||||
onDashboardHome={() => setDashboardSection("home")}
|
||||
onOpenSharedProject={(project) => void openSharedProject(project)}
|
||||
onOpenProject={openEditor}
|
||||
@@ -1206,6 +1246,11 @@ export default function Home() {
|
||||
projectModifiedAt={activeProject?.updatedAt}
|
||||
projectRevision={activeProjectShapeEntry?.revision ?? activeProject?.revision ?? 0}
|
||||
sharedProjectsEnabled={sharedProjectsEnabled}
|
||||
challengeTutorial={activeChallengeTutorial}
|
||||
onChallengeTutorialFinish={() => {
|
||||
setActiveChallengeTutorial(null);
|
||||
window.localStorage.removeItem(ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY);
|
||||
}}
|
||||
themePreference={themePreference}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onThemePreferenceChange={setThemePreference}
|
||||
@@ -1302,11 +1347,13 @@ function Dashboard({
|
||||
viewMode,
|
||||
onCloseSettings,
|
||||
onCreate,
|
||||
onStartChallenge,
|
||||
onDeleteProject,
|
||||
onDownloadFolderChange,
|
||||
onDownloadModeChange,
|
||||
onImportFile,
|
||||
onChallenges,
|
||||
onCustomization,
|
||||
onDashboardHome,
|
||||
onOpenSharedProject,
|
||||
onOpenProject,
|
||||
@@ -1334,11 +1381,13 @@ function Dashboard({
|
||||
viewMode: ViewMode;
|
||||
onCloseSettings: () => void;
|
||||
onCreate: () => void;
|
||||
onStartChallenge: (challenge: ChallengeTutorialId) => void;
|
||||
onDeleteProject: (projectId: string) => void;
|
||||
onDownloadFolderChange: (value: string) => void;
|
||||
onDownloadModeChange: (value: DownloadMode) => void;
|
||||
onImportFile: () => void;
|
||||
onChallenges: () => void;
|
||||
onCustomization: () => void;
|
||||
onDashboardHome: () => void;
|
||||
onOpenSharedProject: (project: SharedProject) => void;
|
||||
onOpenProject: (projectId: string) => void;
|
||||
@@ -1355,6 +1404,13 @@ function Dashboard({
|
||||
const [projectPendingDeleteId, setProjectPendingDeleteId] = useState<string | null>(null);
|
||||
const [projectPendingRenameId, setProjectPendingRenameId] = useState<string | null>(null);
|
||||
const [projectNameDraft, setProjectNameDraft] = useState("");
|
||||
const [updateStatus, setUpdateStatus] = useState<AppUpdateStatus | null>(null);
|
||||
const [updateChecking, setUpdateChecking] = useState(false);
|
||||
const [updatePromptOpen, setUpdatePromptOpen] = useState(false);
|
||||
const [updateKey, setUpdateKey] = useState("");
|
||||
const [updateStarting, setUpdateStarting] = useState(false);
|
||||
const [updateMessage, setUpdateMessage] = useState("");
|
||||
const updateCheckedRef = useRef(false);
|
||||
const projectPendingDelete = projects.find((project) => project.id === projectPendingDeleteId) ?? null;
|
||||
const projectPendingRename = projects.find((project) => project.id === projectPendingRenameId) ?? null;
|
||||
|
||||
@@ -1387,6 +1443,79 @@ function Dashboard({
|
||||
closeProjectRename();
|
||||
};
|
||||
|
||||
const checkForUpdates = useCallback(async (force: boolean, alwaysPrompt: boolean) => {
|
||||
if (staticExportBuild) return;
|
||||
setUpdateChecking(true);
|
||||
setUpdateMessage("");
|
||||
try {
|
||||
const response = await fetch(`/api/app-update${force ? "?force=1" : ""}`, { cache: "no-store" });
|
||||
const payload = await response.json() as AppUpdateStatus & { error?: string };
|
||||
if (!response.ok) throw new Error(payload.error || "Could not check for updates");
|
||||
setUpdateStatus(payload);
|
||||
if (payload.updateAvailable && payload.latestVersion) {
|
||||
const dismissedVersion = window.localStorage.getItem(DISMISSED_UPDATE_VERSION_STORAGE_KEY);
|
||||
if (alwaysPrompt || dismissedVersion !== payload.latestVersion) {
|
||||
onCloseSettings();
|
||||
setUpdatePromptOpen(true);
|
||||
}
|
||||
} else if (alwaysPrompt && !payload.checkError) {
|
||||
setUpdateMessage("SketchForge is up to date.");
|
||||
}
|
||||
} catch (error) {
|
||||
setUpdateMessage(error instanceof Error ? error.message : "Could not check for updates");
|
||||
} finally {
|
||||
setUpdateChecking(false);
|
||||
}
|
||||
}, [onCloseSettings, staticExportBuild]);
|
||||
|
||||
useEffect(() => {
|
||||
if (staticExportBuild || updateCheckedRef.current) return;
|
||||
updateCheckedRef.current = true;
|
||||
void checkForUpdates(false, false);
|
||||
}, [checkForUpdates, staticExportBuild]);
|
||||
|
||||
const dismissUpdate = () => {
|
||||
if (updateStatus?.latestVersion) {
|
||||
window.localStorage.setItem(DISMISSED_UPDATE_VERSION_STORAGE_KEY, updateStatus.latestVersion);
|
||||
}
|
||||
setUpdatePromptOpen(false);
|
||||
setUpdateKey("");
|
||||
setUpdateMessage("");
|
||||
};
|
||||
|
||||
const requestUpdate = async () => {
|
||||
if (!updateStatus?.updateAvailable) return;
|
||||
if (!updateStatus.installationReady) {
|
||||
window.open(updateStatus.updateUrl, "_blank", "noopener,noreferrer");
|
||||
dismissUpdate();
|
||||
return;
|
||||
}
|
||||
if (updateStatus.requiresUpdateKey && !updateKey.trim()) {
|
||||
setUpdateMessage("Enter the server update key to continue.");
|
||||
return;
|
||||
}
|
||||
|
||||
setUpdateStarting(true);
|
||||
setUpdateMessage("");
|
||||
try {
|
||||
const response = await fetch("/api/app-update", {
|
||||
method: "POST",
|
||||
headers: { "x-sketchforge-update-key": updateKey.trim() },
|
||||
});
|
||||
const payload = await response.json() as { accepted?: boolean; error?: string; updateUrl?: string };
|
||||
if (!response.ok || !payload.accepted) throw new Error(payload.error || "Could not start the update");
|
||||
if (updateStatus.latestVersion) {
|
||||
window.localStorage.setItem(DISMISSED_UPDATE_VERSION_STORAGE_KEY, updateStatus.latestVersion);
|
||||
}
|
||||
setUpdateMessage("Update started. The server may briefly go offline; reopen this page after it restarts.");
|
||||
setUpdateKey("");
|
||||
} catch (error) {
|
||||
setUpdateMessage(error instanceof Error ? error.message : "Could not start the update");
|
||||
} finally {
|
||||
setUpdateStarting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="dashboard-shell">
|
||||
<header className="dashboard-topbar">
|
||||
@@ -1421,15 +1550,23 @@ function Dashboard({
|
||||
<SlidersHorizontal size={20} />
|
||||
<span>Challenges</span>
|
||||
</button>
|
||||
<button className={`dashboard-nav-item ${dashboardSection === "customization" ? "active" : ""}`} type="button" aria-label="Customization" title="Customization" onClick={onCustomization}>
|
||||
<Palette size={20} />
|
||||
<span>Customization</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className="dashboard-sidebar-footer">
|
||||
<button className="dashboard-nav-item dashboard-settings-button" type="button" aria-label="Settings" title="Settings" onClick={onOpenSettings}>
|
||||
<Settings size={20} />
|
||||
<span>Settings</span>
|
||||
</button>
|
||||
</div>
|
||||
<button className="dashboard-nav-item dashboard-settings-button" type="button" aria-label="Settings" title="Settings" onClick={onOpenSettings}>
|
||||
<Settings size={20} />
|
||||
<span>Settings</span>
|
||||
</button>
|
||||
</aside>
|
||||
|
||||
<section className="dashboard-main" aria-label={dashboardSection === "challenges" ? "Challenges" : dashboardSection === "shared" ? "Shared projects" : "Dashboard"}>
|
||||
<section className="dashboard-main" aria-label={dashboardSection === "challenges" ? "Challenges" : dashboardSection === "shared" ? "Shared projects" : dashboardSection === "customization" ? "Customization" : "Dashboard"}>
|
||||
{dashboardSection === "challenges" ? (
|
||||
<ChallengesDashboard onStartChallenge={onStartChallenge} />
|
||||
) : dashboardSection === "customization" ? (
|
||||
<div className="dashboard-coming-soon" role="status">
|
||||
<strong>Coming soon</strong>
|
||||
</div>
|
||||
@@ -1634,6 +1771,49 @@ function Dashboard({
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{updatePromptOpen && updateStatus?.updateAvailable && updateStatus.latestVersion ? (
|
||||
<section className="dashboard-confirm-overlay" role="dialog" aria-modal="true" aria-labelledby="app-update-title">
|
||||
<div className="dashboard-confirm-dialog dashboard-update-dialog">
|
||||
<header>
|
||||
<strong id="app-update-title">SketchForge {updateStatus.latestVersion} is available</strong>
|
||||
<button type="button" aria-label="Dismiss update" onClick={dismissUpdate} disabled={updateStarting}>
|
||||
<X size={18} />
|
||||
</button>
|
||||
</header>
|
||||
<div className="dashboard-update-copy">
|
||||
<p>Do you want to update from version {updateStatus.currentVersion}?</p>
|
||||
<div className="dashboard-update-safety">
|
||||
Your projects are kept. Private projects stay in this browser, and Docker shared projects remain in the persistent <code>/data/projects</code> volume.
|
||||
</div>
|
||||
{!updateStatus.installationReady ? (
|
||||
<div className="dashboard-update-note">One-click installation is not configured on this server. Continue to the safe update guide.</div>
|
||||
) : null}
|
||||
{updateStatus.requiresUpdateKey ? (
|
||||
<label className="dashboard-update-key">
|
||||
<span>Server update key</span>
|
||||
<input
|
||||
type="password"
|
||||
autoComplete="off"
|
||||
value={updateKey}
|
||||
onChange={(event) => setUpdateKey(event.currentTarget.value)}
|
||||
disabled={updateStarting}
|
||||
/>
|
||||
</label>
|
||||
) : null}
|
||||
{updateMessage ? <div className="dashboard-update-message" role="status">{updateMessage}</div> : null}
|
||||
</div>
|
||||
<div className="dashboard-confirm-actions">
|
||||
<button className="dashboard-confirm-cancel" type="button" onClick={dismissUpdate} disabled={updateStarting}>
|
||||
Not now
|
||||
</button>
|
||||
<button className="dashboard-confirm-save" type="button" onClick={() => void requestUpdate()} disabled={updateStarting}>
|
||||
{updateStarting ? "Starting…" : updateStatus.installationReady ? "Update" : "Open update guide"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{settingsOpen ? (
|
||||
<section className="dashboard-settings-panel" role="dialog" aria-modal="true" aria-label="Settings">
|
||||
<header>
|
||||
@@ -1665,6 +1845,46 @@ function Dashboard({
|
||||
<span>SketchForge version</span>
|
||||
<strong>{SKF_CREATED_WITH_VERSION}</strong>
|
||||
</div>
|
||||
<section className="dashboard-update-settings" aria-label="Software updates">
|
||||
<div>
|
||||
<strong>Software updates</strong>
|
||||
<span>Updates are checked automatically but are never installed without your approval.</span>
|
||||
</div>
|
||||
{staticExportBuild ? (
|
||||
<span className="dashboard-update-status">Managed by the website owner</span>
|
||||
) : updateStatus?.checkError ? (
|
||||
<span className="dashboard-update-status error">{updateStatus.checkError}</span>
|
||||
) : updateStatus?.updateAvailable && updateStatus.latestVersion ? (
|
||||
<button
|
||||
className="dashboard-update-available"
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onCloseSettings();
|
||||
setUpdateMessage("");
|
||||
setUpdatePromptOpen(true);
|
||||
}}
|
||||
>
|
||||
Update to {updateStatus.latestVersion}
|
||||
</button>
|
||||
) : updateStatus ? (
|
||||
<span className="dashboard-update-status ready">Up to date</span>
|
||||
) : null}
|
||||
{!staticExportBuild ? (
|
||||
<button className="dashboard-check-update" type="button" onClick={() => void checkForUpdates(true, true)} disabled={updateChecking}>
|
||||
<RefreshCw size={15} className={updateChecking ? "spin" : ""} />
|
||||
<span>{updateChecking ? "Checking…" : "Check for updates"}</span>
|
||||
</button>
|
||||
) : null}
|
||||
{updateMessage && settingsOpen ? <span className="dashboard-update-status" role="status">{updateMessage}</span> : null}
|
||||
</section>
|
||||
<div className="dashboard-version-row">
|
||||
<span>License</span>
|
||||
<a href="https://www.gnu.org/licenses/agpl-3.0.html" target="_blank" rel="noreferrer">AGPLv3</a>
|
||||
</div>
|
||||
<div className="dashboard-version-row">
|
||||
<span>Corresponding source</span>
|
||||
<a href={SOURCE_CODE_URL} target="_blank" rel="noreferrer">View source</a>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
</main>
|
||||
|
||||
@@ -16,6 +16,7 @@ import gentilisBoldFontJson from "three/examples/fonts/gentilis_bold.typeface.js
|
||||
import helvetikerBoldFontJson from "three/examples/fonts/helvetiker_bold.typeface.json";
|
||||
import optimerBoldFontJson from "three/examples/fonts/optimer_bold.typeface.json";
|
||||
import type { AppThemePreference, ResolvedAppTheme } from "@/lib/appTheme";
|
||||
import type { ChallengeTutorialId } from "@/lib/challenges";
|
||||
import { manifoldModuleSource } from "@/generated/manifoldModuleSource";
|
||||
import { manifoldWasmBase64 } from "@/generated/manifoldWasmBase64";
|
||||
import { sphereTessellation } from "@/lib/sphereTessellation";
|
||||
@@ -84,12 +85,14 @@ import { appendEditorHistorySnapshot, boundedEditorHistoryState, editorHistoryEn
|
||||
import { snapShapeFootprintToVisibleGrid, visibleGridStep } from "@/lib/gridSnap";
|
||||
import { createLocalId } from "@/lib/localIds";
|
||||
import { projectExportFileName } from "@/lib/exportNames";
|
||||
import { exportMeshesToObj } from "@/lib/objExport";
|
||||
import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets";
|
||||
import { findSketchOutlineIntersection } from "@/lib/sketchProfileValidation";
|
||||
import { buildSketchRevolveMesh, DEFAULT_SKETCH_REVOLVE_SETTINGS, normalizeSketchRevolveSettings, type SketchRevolveMesh } from "@/lib/sketchRevolve";
|
||||
import { exportSkfProject, SKF_MEDIA_TYPE } from "@/lib/skfProject";
|
||||
import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog";
|
||||
import { importedShapeFromStl, importExtensionSupported } from "@/lib/stlImport";
|
||||
import { exportMeshesToStl } from "@/lib/stlExport";
|
||||
import { importedShapeFromSvg, invalidSvgMeshReason } from "@/lib/svgImport";
|
||||
import { toSvgProjection, type SvgProjectionLayer } from "@/lib/svgExport";
|
||||
import { normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
|
||||
@@ -113,6 +116,7 @@ import {
|
||||
type SketchForgeMcpViewFace,
|
||||
} from "@/lib/sketchforgeMcpProtocol";
|
||||
import type { CadModifierComponentMesh, CadModifierDisplayEdge, CadModifierEdge, CadModifierKind, CadModifierMeshPart, CadModifierPrimitivePart, CadModifierQuality, CadModifierWorkerRequest, CadModifierWorkerResponse } from "@/lib/cadModifierTypes";
|
||||
import type { SketchCadBuildResponse } from "@/lib/sketchCadTypes";
|
||||
import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ProjectAsset, ShapeAsset, SketchImage, SketchOperation, SketchPoint, SketchProfile, SketchRevolveSettings, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||
|
||||
export { importedShapeFromStl, importedShapeFromSvg };
|
||||
@@ -529,6 +533,76 @@ async function shapeFromSketchProfile(profile: SketchProfile, height: number, ex
|
||||
} satisfies WorkplaneShape);
|
||||
}
|
||||
|
||||
let sketchCadWorker: Worker | null = null;
|
||||
let sketchCadRequestId = 0;
|
||||
const sketchCadPending = new Map<number, {
|
||||
resolve: (response: SketchCadBuildResponse) => void;
|
||||
reject: (error: Error) => void;
|
||||
timer: number;
|
||||
}>();
|
||||
|
||||
function ensureSketchCadWorker() {
|
||||
if (sketchCadWorker) return sketchCadWorker;
|
||||
const worker = new Worker(new URL("../workers/sketchCad.worker.ts", import.meta.url), { type: "module" });
|
||||
worker.onmessage = (event: MessageEvent<SketchCadBuildResponse>) => {
|
||||
const pending = sketchCadPending.get(event.data.requestId);
|
||||
if (!pending) return;
|
||||
window.clearTimeout(pending.timer);
|
||||
sketchCadPending.delete(event.data.requestId);
|
||||
pending.resolve(event.data);
|
||||
};
|
||||
worker.onerror = () => {
|
||||
sketchCadPending.forEach((pending) => {
|
||||
window.clearTimeout(pending.timer);
|
||||
pending.reject(new Error("The OpenCascade sketch worker failed to start"));
|
||||
});
|
||||
sketchCadPending.clear();
|
||||
worker.terminate();
|
||||
sketchCadWorker = null;
|
||||
};
|
||||
sketchCadWorker = worker;
|
||||
return worker;
|
||||
}
|
||||
|
||||
async function cadShapeFromSketchProfile(profile: SketchProfile, height: number, existing?: WorkplaneShape | null) {
|
||||
const safeHeight = Math.max(MIN_SHAPE_DIMENSION, height);
|
||||
const worker = ensureSketchCadWorker();
|
||||
const requestId = ++sketchCadRequestId;
|
||||
const response = await new Promise<SketchCadBuildResponse>((resolve, reject) => {
|
||||
const timer = window.setTimeout(() => {
|
||||
sketchCadPending.delete(requestId);
|
||||
reject(new Error("OpenCascade timed out while building the sketch"));
|
||||
}, 30_000);
|
||||
sketchCadPending.set(requestId, { resolve, reject, timer });
|
||||
worker.postMessage({ type: "build", requestId, profile: cloneSketchProfile(profile), height: safeHeight });
|
||||
});
|
||||
if (response.type === "error") throw new Error(response.message);
|
||||
const source = canonicalizeShape({
|
||||
...(existing ?? {
|
||||
id: createLocalId("sketch-extrusion"),
|
||||
name: "Sketch extrusion",
|
||||
kind: "mesh" as const,
|
||||
color: "#d41721",
|
||||
x: 0,
|
||||
z: 0,
|
||||
size: 1,
|
||||
width: 1,
|
||||
depth: 1,
|
||||
height: safeHeight,
|
||||
rotation: 0,
|
||||
}),
|
||||
sketchProfile: cloneSketchProfile(profile),
|
||||
sketchOperation: "extrude",
|
||||
edgeTreatments: undefined,
|
||||
edgeTreatmentHistory: undefined,
|
||||
cadDisplayEdges: undefined,
|
||||
cadDisplayEdgesVersion: undefined,
|
||||
});
|
||||
const shape = shapeFromCadMesh(source, response.positions, response.normals, response.indices, response.brep);
|
||||
if (!shape) throw new Error("OpenCascade returned an empty sketch solid");
|
||||
return { ...shape, sketchProfile: cloneSketchProfile(profile), sketchOperation: "extrude" as const };
|
||||
}
|
||||
|
||||
async function shapeFromRevolvedSketchProfile(
|
||||
profile: SketchProfile,
|
||||
settings: Partial<SketchRevolveSettings>,
|
||||
@@ -2263,7 +2337,10 @@ function cadModifierPrimitiveForShape(shape: WorkplaneShape): CadModifierPrimiti
|
||||
}
|
||||
|
||||
function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape {
|
||||
if (!shapeHasTransformToBake(shape)) {
|
||||
// Rotation is a non-destructive transform for editable text. Baking it would
|
||||
// change the shape to `kind: "mesh"`, hiding the Text and Font controls even
|
||||
// though the user never grouped or otherwise converted the object.
|
||||
if (shape.kind === "text" || !shapeHasTransformToBake(shape)) {
|
||||
return shape;
|
||||
}
|
||||
|
||||
@@ -2459,53 +2536,6 @@ async function importedShapeFromImage(file: File): Promise<WorkplaneShape> {
|
||||
};
|
||||
}
|
||||
|
||||
function normalFor(a: Vec3, b: Vec3, c: Vec3): Vec3 {
|
||||
const ux = b[0] - a[0];
|
||||
const uy = b[1] - a[1];
|
||||
const uz = b[2] - a[2];
|
||||
const vx = c[0] - a[0];
|
||||
const vy = c[1] - a[1];
|
||||
const vz = c[2] - a[2];
|
||||
const nx = uy * vz - uz * vy;
|
||||
const ny = uz * vx - ux * vz;
|
||||
const nz = ux * vy - uy * vx;
|
||||
const length = Math.hypot(nx, ny, nz) || 1;
|
||||
return [nx / length, ny / length, nz / length];
|
||||
}
|
||||
|
||||
function toStl(meshes: MeshData[]) {
|
||||
const lines = ["solid sketchforge_design"];
|
||||
meshes.forEach((mesh) => {
|
||||
mesh.faces.forEach(([ai, bi, ci]) => {
|
||||
const a = mesh.vertices[ai];
|
||||
const b = mesh.vertices[bi];
|
||||
const c = mesh.vertices[ci];
|
||||
const n = normalFor(a, b, c);
|
||||
lines.push(` facet normal ${n[0]} ${n[1]} ${n[2]}`);
|
||||
lines.push(" outer loop");
|
||||
lines.push(` vertex ${a[0]} ${a[1]} ${a[2]}`);
|
||||
lines.push(` vertex ${b[0]} ${b[1]} ${b[2]}`);
|
||||
lines.push(` vertex ${c[0]} ${c[1]} ${c[2]}`);
|
||||
lines.push(" endloop");
|
||||
lines.push(" endfacet");
|
||||
});
|
||||
});
|
||||
lines.push("endsolid sketchforge_design");
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function toObj(meshes: MeshData[]) {
|
||||
const lines = ["# SketchForge OBJ export"];
|
||||
let offset = 1;
|
||||
meshes.forEach((mesh) => {
|
||||
lines.push(`o ${mesh.name}`);
|
||||
mesh.vertices.forEach(([x, y, z]) => lines.push(`v ${x} ${y} ${z}`));
|
||||
mesh.faces.forEach(([a, b, c]) => lines.push(`f ${a + offset} ${b + offset} ${c + offset}`));
|
||||
offset += mesh.vertices.length;
|
||||
});
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
async function toSvg(shapes: WorkplaneShape[], title: string) {
|
||||
const runtime = await getManifoldRuntime();
|
||||
const layers: SvgProjectionLayer[] = [];
|
||||
@@ -3118,6 +3148,12 @@ function separateMeshParts(shape: WorkplaneShape) {
|
||||
.filter((part): part is WorkplaneShape => Boolean(part));
|
||||
}
|
||||
|
||||
function cadModifierSourceParts(shape: WorkplaneShape) {
|
||||
if (shape.kind !== "text" || shape.importedMesh || shape.cadBrep) return [shape];
|
||||
const glyphParts = separateMeshParts(shape);
|
||||
return glyphParts.length > 1 ? glyphParts : [shape];
|
||||
}
|
||||
|
||||
function separablePartCount(shape: WorkplaneShape) {
|
||||
if (shape.locked || shape.hole) return 0;
|
||||
if (shape.groupedShapes?.length && !shape.importedMesh) return shape.groupedShapes.length;
|
||||
@@ -5279,6 +5315,8 @@ export function SketchForgeEditor({
|
||||
projectModifiedAt = Date.now(),
|
||||
projectRevision = 0,
|
||||
sharedProjectsEnabled = false,
|
||||
challengeTutorial = null,
|
||||
onChallengeTutorialFinish,
|
||||
themePreference = "system",
|
||||
resolvedTheme = "light",
|
||||
onThemePreferenceChange,
|
||||
@@ -5323,6 +5361,8 @@ export function SketchForgeEditor({
|
||||
projectModifiedAt?: number;
|
||||
projectRevision?: number;
|
||||
sharedProjectsEnabled?: boolean;
|
||||
challengeTutorial?: ChallengeTutorialId | null;
|
||||
onChallengeTutorialFinish?: () => void;
|
||||
themePreference?: AppThemePreference;
|
||||
resolvedTheme?: ResolvedAppTheme;
|
||||
onThemePreferenceChange?: (preference: AppThemePreference) => void;
|
||||
@@ -6566,8 +6606,9 @@ export function SketchForgeEditor({
|
||||
if (sketchOperation === "revolve") {
|
||||
resolved = await shapeFromRevolvedSketchProfile(sketchProfile, sketchRevolveSettings, existing);
|
||||
} else {
|
||||
const extrusion = await shapeFromSketchProfile(sketchProfile, height, existing);
|
||||
resolved = extrusion ? placeSketchExtrusion(extrusion, activeSketchWorkplane, existing) : null;
|
||||
setNotice("Building exact sketch geometry…");
|
||||
const extrusion = await cadShapeFromSketchProfile(sketchProfile, height, existing);
|
||||
resolved = placeSketchExtrusion(extrusion, activeSketchWorkplane, existing);
|
||||
}
|
||||
} catch (error) {
|
||||
setNotice(error instanceof Error ? error.message : `The sketch profile cannot be ${sketchOperation === "revolve" ? "revolved" : "extruded"} to 3D`);
|
||||
@@ -6579,7 +6620,7 @@ export function SketchForgeEditor({
|
||||
}
|
||||
const nextShapes = existing ? shapes.map((shape) => (shape.id === existing.id ? resolved : shape)) : [...shapes, resolved];
|
||||
const action = sketchOperation === "revolve" ? "Revolve sketch" : "Sketch";
|
||||
commitShapes(nextShapes, resolved.id, existing ? `${action} updated` : sketchOperation === "revolve" ? "Revolved sketch created" : "Sketch created at 10 mm height");
|
||||
commitShapes(nextShapes, resolved.id, existing ? `${action} updated` : sketchOperation === "revolve" ? "Revolved sketch created" : "Exact sketch created at 10 mm height");
|
||||
setSketchActive(false);
|
||||
setSketchRevolvePreview(null);
|
||||
setEditingSketchShapeId(null);
|
||||
@@ -7072,7 +7113,9 @@ export function SketchForgeEditor({
|
||||
invalidateCadModifierSession();
|
||||
const appliedEdgeTreatmentCount = edgeTreatmentFeatureCount(selectedShape);
|
||||
const hasAppliedEdgeTreatment = Boolean(selectedShape.importedMesh && selectedShape.edgeTreatments?.length);
|
||||
const sourceParts = selectedShape.groupedShapes?.length && !hasAppliedEdgeTreatment ? restoreGroupedChildren(selectedShape) : [selectedShape];
|
||||
const sourceParts = (selectedShape.groupedShapes?.length && !hasAppliedEdgeTreatment
|
||||
? restoreGroupedChildren(selectedShape)
|
||||
: [selectedShape]).flatMap(cadModifierSourceParts);
|
||||
const partInputs: Array<{ shape: WorkplaneShape; mesh?: MeshData; brep?: string; brepTransform?: number[]; primitive?: CadModifierPrimitivePart }> = sourceParts.map((shape) => {
|
||||
const frame = shape.cadBrepFrame;
|
||||
const preserveNeedsRetessellation = preservesEdgeTreatmentSize(shape) && Boolean(frame) && (
|
||||
@@ -7145,7 +7188,9 @@ export function SketchForgeEditor({
|
||||
}
|
||||
const appliedEdgeTreatmentCount = edgeTreatmentFeatureCount(shape);
|
||||
const hasAppliedEdgeTreatment = Boolean(shape.importedMesh && shape.edgeTreatments?.length);
|
||||
const sourceParts = shape.groupedShapes?.length && !hasAppliedEdgeTreatment ? restoreGroupedChildren(shape) : [shape];
|
||||
const sourceParts = (shape.groupedShapes?.length && !hasAppliedEdgeTreatment
|
||||
? restoreGroupedChildren(shape)
|
||||
: [shape]).flatMap(cadModifierSourceParts);
|
||||
const partInputs: Array<{ shape: WorkplaneShape; mesh?: MeshData; brep?: string; brepTransform?: number[]; primitive?: CadModifierPrimitivePart }> = sourceParts.map((partShape) => {
|
||||
const frame = partShape.cadBrepFrame;
|
||||
const preserveNeedsRetessellation = preservesEdgeTreatmentSize(partShape) && Boolean(frame) && (
|
||||
@@ -7711,8 +7756,7 @@ export function SketchForgeEditor({
|
||||
let shape: WorkplaneShape;
|
||||
if (kind === "sketch") {
|
||||
const profile = defaultMcpSketchProfile(width, depth);
|
||||
const extruded = await shapeFromSketchProfile(profile, height);
|
||||
if (!extruded) throw new Error("Could not create the sketch profile");
|
||||
const extruded = await cadShapeFromSketchProfile(profile, height);
|
||||
shape = canonicalizeShape({
|
||||
...extruded,
|
||||
name,
|
||||
@@ -7724,7 +7768,7 @@ export function SketchForgeEditor({
|
||||
rotationX: mcpNumber(params.rotationX, 0),
|
||||
rotationZ: mcpNumber(params.rotationZ, 0),
|
||||
});
|
||||
} else if (kind === "box" || kind === "cylinder") {
|
||||
} else if (kind === "box" || kind === "cylinder" || kind === "text") {
|
||||
shape = sceneShape({
|
||||
name,
|
||||
kind,
|
||||
@@ -7740,9 +7784,13 @@ export function SketchForgeEditor({
|
||||
rotationX: mcpNumber(params.rotationX, 0),
|
||||
rotationZ: mcpNumber(params.rotationZ, 0),
|
||||
sides: kind === "cylinder" ? Math.max(3, Math.floor(mcpNumber(params.sides, 96))) : undefined,
|
||||
text: kind === "text" ? mcpString(params.text, "TEXT") : undefined,
|
||||
font: kind === "text" ? mcpString(params.font, "Multilanguage") : undefined,
|
||||
bevel: kind === "text" ? Math.max(0, mcpNumber(params.bevel, 0)) : undefined,
|
||||
segments: kind === "text" ? Math.max(1, Math.floor(mcpNumber(params.segments, 2))) : undefined,
|
||||
});
|
||||
} else {
|
||||
throw new Error("MCP create_shape currently supports box, cube, cylinder, and sketch");
|
||||
throw new Error("MCP create_shape currently supports box, cube, cylinder, text, and sketch");
|
||||
}
|
||||
const committedShape = canonicalizeShape(bakeShapeTransformIntoMesh(shape));
|
||||
commitShapes([...currentShapes(), committedShape], committedShape.id, `${committedShape.name} added by MCP`);
|
||||
@@ -7822,6 +7870,9 @@ export function SketchForgeEditor({
|
||||
if (typeof params.color === "string") patch.color = params.color;
|
||||
if (typeof params.name === "string") patch.name = params.name;
|
||||
if (typeof params.hole === "boolean") patch.hole = params.hole;
|
||||
if (typeof params.text === "string") patch.text = params.text;
|
||||
if (typeof params.font === "string") patch.font = params.font;
|
||||
if (typeof params.bevel === "number" && Number.isFinite(params.bevel)) patch.bevel = Math.max(0, params.bevel);
|
||||
const nextShapes = currentShapes().map((shape) => {
|
||||
if (shape.id !== target.id) return shape;
|
||||
const patched = { ...shape, ...cleanShapePatch(patch) };
|
||||
@@ -8272,12 +8323,12 @@ export function SketchForgeEditor({
|
||||
}
|
||||
const meshes = exportable.map(meshForShape);
|
||||
if (format === "stl") {
|
||||
void downloadTextFile(projectExportFileName(exportName, "stl"), toStl(meshes), "model/stl")
|
||||
void downloadTextFile(projectExportFileName(exportName, "stl"), exportMeshesToStl(meshes), "model/stl")
|
||||
.then((result) => finishNotice("STL", result))
|
||||
.catch((error: unknown) => failNotice("STL", error));
|
||||
return;
|
||||
}
|
||||
void downloadTextFile(projectExportFileName(exportName, "obj"), toObj(meshes), "text/plain")
|
||||
void downloadTextFile(projectExportFileName(exportName, "obj"), exportMeshesToObj(meshes), "text/plain")
|
||||
.then((result) => finishNotice("OBJ", result))
|
||||
.catch((error: unknown) => failNotice("OBJ", error));
|
||||
}, [hasSelection, projectName, selectedShapes, shapes]);
|
||||
@@ -8897,6 +8948,8 @@ export function SketchForgeEditor({
|
||||
modifierEdges={edgeModifier?.edges.filter((edge) => modifierAvailableEdgeIds.includes(edge.id)) ?? []}
|
||||
selectedModifierEdgeIds={edgeModifier?.selectedEdgeIds ?? []}
|
||||
onModifierEdgeToggle={toggleModifierEdge}
|
||||
challengeTutorial={challengeTutorial}
|
||||
onChallengeTutorialFinish={onChallengeTutorialFinish}
|
||||
themePreference={themePreference}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onThemePreferenceChange={onThemePreferenceChange}
|
||||
@@ -9274,7 +9327,15 @@ function SecondaryToolbar({
|
||||
const { icon: Icon, action, enabled, label } = tool;
|
||||
const active = "active" in tool && Boolean(tool.active);
|
||||
return (
|
||||
<button className={`toolbar-icon ${enabled ? "" : "disabled"} ${active ? "active" : ""}`} key={label} aria-label={label} title={label} onClick={action} disabled={!enabled}>
|
||||
<button
|
||||
className={`toolbar-icon ${enabled ? "" : "disabled"} ${active ? "active" : ""}`}
|
||||
key={label}
|
||||
data-sketchforge-tool={label === "Fillet" ? "fillet" : undefined}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
onClick={action}
|
||||
disabled={!enabled}
|
||||
>
|
||||
<Icon />
|
||||
</button>
|
||||
);
|
||||
|
||||
@@ -608,14 +608,7 @@ export function SketchWorkspace({
|
||||
const end = pointById.get(segment.endId);
|
||||
return Boolean(start && end && (contains(start) || contains(end) || contains({ x: (start.x + end.x) / 2, z: (start.z + end.z) / 2 })));
|
||||
}).map((segment) => segment.id);
|
||||
const imageIds = (profile.images ?? []).filter((image) => {
|
||||
const imageMinX = image.x - image.width / 2;
|
||||
const imageMaxX = image.x + image.width / 2;
|
||||
const imageMinZ = image.z - image.depth / 2;
|
||||
const imageMaxZ = image.z + image.depth / 2;
|
||||
return imageMaxX >= minX && imageMinX <= maxX && imageMaxZ >= minZ && imageMinZ <= maxZ;
|
||||
}).map((image) => image.id);
|
||||
onSelectMany(pointIds, segmentIds, imageIds);
|
||||
onSelectMany(pointIds, segmentIds, []);
|
||||
setPointerAction(null);
|
||||
return;
|
||||
}
|
||||
@@ -745,7 +738,6 @@ export function SketchWorkspace({
|
||||
if (event.button !== 0 || tool !== "select") return;
|
||||
const point = pointFromEvent(event);
|
||||
if (!point) return;
|
||||
onSelectImage(image.id);
|
||||
beginEntityDrag(event, {
|
||||
kind: "move-image",
|
||||
pointerId: event.pointerId,
|
||||
@@ -989,7 +981,7 @@ export function SketchWorkspace({
|
||||
<button type="button" title="Split handles" onClick={() => onSetPointMode(selectedPoint.id, "split")}><Split /><span>Split</span></button>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="grid-settings sketch-grid-settings">
|
||||
<div className="grid-settings">
|
||||
<SnapGridControl snap={snap} snapOpen={snapOpen} onSnapChange={setSnap} onSnapOpenChange={setSnapOpen} />
|
||||
</div>
|
||||
</main>
|
||||
|
||||
@@ -21,8 +21,11 @@ import optimerBoldFontJson from "three/examples/fonts/optimer_bold.typeface.json
|
||||
import { AlignOverlay, MirrorOverlay, type AlignOverlayState, type MirrorOverlayState } from "@/components/workplane/ActionOverlays";
|
||||
import { MoveDimensionOverlay } from "@/components/workplane/MoveDimensionOverlay";
|
||||
import { ShapeInspector, SnapGridControl, type ShapeInspectorUpdateOptions } from "@/components/workplane/ShapeInspector";
|
||||
import { KeyTagTutorialPanel } from "@/components/workplane/KeyTagTutorialPanel";
|
||||
import { NameplateTutorialPanel } from "@/components/workplane/NameplateTutorialPanel";
|
||||
import { WorkspaceSettingsModal } from "@/components/workplane/WorkspaceSettingsModal";
|
||||
import type { AppThemePreference, ResolvedAppTheme } from "@/lib/appTheme";
|
||||
import type { ChallengeTutorialId } from "@/lib/challenges";
|
||||
import { cadModifierPrimitiveForBakedShape, cadTransformFromMatrix, cadTransformToMatrix } from "@/lib/cadBakeMetadata";
|
||||
import { createGearGeometry } from "@/lib/gearGeometry";
|
||||
import { parseMeasurementInput } from "@/lib/measurementUnits";
|
||||
@@ -201,6 +204,8 @@ type WorkplaneViewportProps = {
|
||||
modifierEdges?: CadModifierEdge[];
|
||||
selectedModifierEdgeIds?: number[];
|
||||
onModifierEdgeToggle?: (id: number, singleEdge: boolean) => void;
|
||||
challengeTutorial?: ChallengeTutorialId | null;
|
||||
onChallengeTutorialFinish?: () => void;
|
||||
themePreference?: AppThemePreference;
|
||||
resolvedTheme?: ResolvedAppTheme;
|
||||
onThemePreferenceChange?: (preference: AppThemePreference) => void;
|
||||
@@ -2223,6 +2228,8 @@ export function WorkplaneViewport({
|
||||
modifierEdges = [],
|
||||
selectedModifierEdgeIds = [],
|
||||
onModifierEdgeToggle,
|
||||
challengeTutorial = null,
|
||||
onChallengeTutorialFinish,
|
||||
themePreference = "system",
|
||||
resolvedTheme = "light",
|
||||
onThemePreferenceChange,
|
||||
@@ -2254,6 +2261,12 @@ export function WorkplaneViewport({
|
||||
const [rulerOverlay, setRulerOverlay] = useState<RulerOverlayState | null>(null);
|
||||
const [moveDimensionOverlay, setMoveDimensionOverlay] = useState<MoveDimensionOverlayState | null>(null);
|
||||
const [moveDimensionsEnabled, setMoveDimensionsEnabled] = useState(true);
|
||||
const [challengeTutorialCollapsed, setChallengeTutorialCollapsed] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setChallengeTutorialCollapsed(false);
|
||||
}, [challengeTutorial]);
|
||||
|
||||
const hostRef = useRef<HTMLDivElement | null>(null);
|
||||
const threeRef = useRef<ThreeState | null>(null);
|
||||
const shapesRef = useRef(shapes);
|
||||
@@ -3220,6 +3233,7 @@ export function WorkplaneViewport({
|
||||
}
|
||||
return shapesRef.current
|
||||
.filter((shape) => !shape.hidden)
|
||||
.filter((shape) => !shape.imagePlate)
|
||||
.filter((shape) => {
|
||||
const bounds = shapeScreenBounds(state, shape);
|
||||
return bounds ? boundsIntersectRect(bounds, rect) : false;
|
||||
@@ -3778,7 +3792,12 @@ export function WorkplaneViewport({
|
||||
state.raycaster.layers.set(RENDER_LAYER_SHAPES);
|
||||
|
||||
const intersections = state.raycaster.intersectObjects(state.shapeLayer.children, true);
|
||||
const hit = intersections.find((entry) => typeof entry.object.userData.shapeId === "string");
|
||||
const hit = intersections.find((entry) => {
|
||||
const shapeId = entry.object.userData.shapeId;
|
||||
if (typeof shapeId !== "string") return false;
|
||||
const shape = shapesRef.current.find((candidate) => candidate.id === shapeId);
|
||||
return shape ? !shape.imagePlate : false;
|
||||
});
|
||||
if (hit) {
|
||||
return hit.object.userData.shapeId as string;
|
||||
}
|
||||
@@ -3786,6 +3805,7 @@ export function WorkplaneViewport({
|
||||
let nearestId: string | null = null;
|
||||
let nearestDistance = Number.POSITIVE_INFINITY;
|
||||
shapesRef.current.forEach((shape) => {
|
||||
if (shape.imagePlate) return;
|
||||
const center = new THREE.Vector3(shape.x, (shape.elevation ?? 0) + shape.height / 2, shape.z).project(state.camera);
|
||||
const screenX = rect.left + ((center.x + 1) / 2) * rect.width;
|
||||
const screenY = rect.top + ((1 - center.y) / 2) * rect.height;
|
||||
@@ -4757,7 +4777,7 @@ export function WorkplaneViewport({
|
||||
}, [onWorkplaneModeChange, resetView, rulerToolsOpen, setPlacementWorkplaneAtSelection, setRulerActive, togglePlacementWorkplane, toggleProjection, zoomCamera]);
|
||||
|
||||
return (
|
||||
<main className="workplane-stage">
|
||||
<main className={`workplane-stage ${challengeTutorial ? `key-tag-tutorial-active ${challengeTutorialCollapsed ? "key-tag-tutorial-collapsed" : ""}` : ""}`}>
|
||||
<div className="view-cube" aria-label="View orientation cube" onPointerDown={(event) => event.stopPropagation()}>
|
||||
<div className="view-cube-inner" ref={viewCubeRef}>
|
||||
<button type="button" className="cube-face cube-top" aria-label="Bottom view" onClick={() => setViewCubeFace("bottom")}>BOTTOM</button>
|
||||
@@ -4939,6 +4959,20 @@ export function WorkplaneViewport({
|
||||
onClose={() => setSettingsOpen(false)}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{challengeTutorial === "key-tag" ? (
|
||||
<KeyTagTutorialPanel
|
||||
onFinish={onChallengeTutorialFinish}
|
||||
collapsed={challengeTutorialCollapsed}
|
||||
onCollapsedChange={setChallengeTutorialCollapsed}
|
||||
/>
|
||||
) : challengeTutorial === "nameplate" ? (
|
||||
<NameplateTutorialPanel
|
||||
onFinish={onChallengeTutorialFinish}
|
||||
collapsed={challengeTutorialCollapsed}
|
||||
onCollapsedChange={setChallengeTutorialCollapsed}
|
||||
/>
|
||||
) : null}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
"use client";
|
||||
|
||||
import { AlignCenter, Box, CircleDotDashed, Group, LockKeyhole, MoveUp, Type } from "lucide-react";
|
||||
import type { ChallengeTutorialId } from "@/lib/challenges";
|
||||
|
||||
function KeyTagPreview() {
|
||||
return (
|
||||
<>
|
||||
<img
|
||||
className="challenge-key-tag-photo challenge-key-tag-photo-light"
|
||||
src="/assets/challenges/key-tag/card-key-tag-light.webp"
|
||||
alt="Finished red Key Tag model on the SketchForge workplane"
|
||||
/>
|
||||
<img
|
||||
className="challenge-key-tag-photo challenge-key-tag-photo-dark"
|
||||
src="/assets/challenges/key-tag/card-key-tag-dark.webp"
|
||||
alt="Finished red Key Tag model on the dark SketchForge workplane"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function NameplatePreview() {
|
||||
return (
|
||||
<>
|
||||
<img
|
||||
className="challenge-key-tag-photo challenge-key-tag-photo-light"
|
||||
src="/assets/challenges/nameplate/card-nameplate-light.webp"
|
||||
alt="Finished blue ALEX nameplate on the SketchForge workplane"
|
||||
/>
|
||||
<img
|
||||
className="challenge-key-tag-photo challenge-key-tag-photo-dark"
|
||||
src="/assets/challenges/nameplate/card-nameplate-dark.webp"
|
||||
alt="Finished blue ALEX nameplate on the dark SketchForge workplane"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ChallengesDashboard({ onStartChallenge }: { onStartChallenge: (challenge: ChallengeTutorialId) => void }) {
|
||||
return (
|
||||
<div className="challenge-key-tag-page">
|
||||
<div className="challenge-key-tag-rail" aria-hidden="true">
|
||||
<span />
|
||||
<span />
|
||||
</div>
|
||||
|
||||
<div className="challenge-card-stack">
|
||||
<article className="challenge-key-tag-card">
|
||||
<div className="challenge-key-tag-preview">
|
||||
<KeyTagPreview />
|
||||
</div>
|
||||
|
||||
<div className="challenge-key-tag-content">
|
||||
<div className="challenge-key-tag-title-row">
|
||||
<span>01</span>
|
||||
<h2>Key Tag</h2>
|
||||
</div>
|
||||
|
||||
<p>Build your first Key Tag from simple shapes.</p>
|
||||
|
||||
<div className="challenge-key-tag-skills" aria-label="Skills used in this challenge">
|
||||
<span><Box size={16} aria-hidden="true" /> Basic shapes</span>
|
||||
<span><AlignCenter size={16} aria-hidden="true" /> Align</span>
|
||||
<span><CircleDotDashed size={16} aria-hidden="true" /> Hole</span>
|
||||
<span><LockKeyhole size={16} aria-hidden="true" /> Lock</span>
|
||||
<span><Group size={16} aria-hidden="true" /> Group</span>
|
||||
</div>
|
||||
|
||||
<button type="button" className="challenge-key-tag-start" onClick={() => onStartChallenge("key-tag")}>
|
||||
Start Challenge
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<article className="challenge-key-tag-card">
|
||||
<div className="challenge-key-tag-preview">
|
||||
<NameplatePreview />
|
||||
</div>
|
||||
|
||||
<div className="challenge-key-tag-content">
|
||||
<div className="challenge-key-tag-title-row">
|
||||
<span>02</span>
|
||||
<h2>Personalized Nameplate</h2>
|
||||
</div>
|
||||
|
||||
<p>Create a printable nameplate with rounded edges and raised custom text.</p>
|
||||
|
||||
<div className="challenge-key-tag-skills" aria-label="Skills used in this challenge">
|
||||
<span><Box size={16} aria-hidden="true" /> Box</span>
|
||||
<span><CircleDotDashed size={16} aria-hidden="true" /> Fillet</span>
|
||||
<span><Type size={16} aria-hidden="true" /> Text</span>
|
||||
<span><MoveUp size={16} aria-hidden="true" /> Elevation</span>
|
||||
<span><AlignCenter size={16} aria-hidden="true" /> Align</span>
|
||||
<span><Group size={16} aria-hidden="true" /> Group</span>
|
||||
</div>
|
||||
|
||||
<button type="button" className="challenge-key-tag-start" onClick={() => onStartChallenge("nameplate")}>
|
||||
Start Challenge
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
"use client";
|
||||
|
||||
import { ChevronLeft, ChevronRight } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
|
||||
const KEY_TAG_STEP_STORAGE_KEY = "sketchforge:key-tag-tutorial-step";
|
||||
|
||||
type TutorialDimension = {
|
||||
label: "Length" | "Width" | "Height";
|
||||
value: string;
|
||||
slider: number;
|
||||
};
|
||||
|
||||
type TutorialStep = {
|
||||
eyebrow: string;
|
||||
title: string;
|
||||
body: string;
|
||||
image: string;
|
||||
alt: string;
|
||||
dimensions?: TutorialDimension[];
|
||||
snapGrid?: string;
|
||||
};
|
||||
|
||||
const STEPS: TutorialStep[] = [
|
||||
{
|
||||
eyebrow: "Before you start",
|
||||
title: "Build a Key Tag",
|
||||
body: "Set Snap Grid to 0.5 mm, then build the Key Tag from simple shapes.",
|
||||
image: "/assets/challenges/key-tag/01-finished-target.png",
|
||||
alt: "Finished Key Tag shown in the SketchForge workplane",
|
||||
snapGrid: "0.5 mm",
|
||||
},
|
||||
{
|
||||
eyebrow: "Step 1",
|
||||
title: "Make the middle",
|
||||
body: "Add a Box, then set its size in the shape panel.",
|
||||
image: "/assets/challenges/key-tag/02-middle-box.png",
|
||||
alt: "The middle box of the Key Tag in SketchForge",
|
||||
dimensions: [
|
||||
{ label: "Length", value: "25.50 mm", slider: 38 },
|
||||
{ label: "Width", value: "11.50 mm", slider: 20 },
|
||||
{ label: "Height", value: "1.00 mm", slider: 5 },
|
||||
],
|
||||
},
|
||||
{
|
||||
eyebrow: "Step 2",
|
||||
title: "Add the left round end",
|
||||
body: "Add a solid Cylinder and place half of it over the left end of the box.",
|
||||
image: "/assets/challenges/key-tag/03-left-round-end.png",
|
||||
alt: "A solid cylinder added to the left end of the Key Tag",
|
||||
dimensions: [
|
||||
{ label: "Length", value: "11.50 mm", slider: 20 },
|
||||
{ label: "Width", value: "11.50 mm", slider: 20 },
|
||||
{ label: "Height", value: "1.00 mm", slider: 5 },
|
||||
],
|
||||
},
|
||||
{
|
||||
eyebrow: "Step 3",
|
||||
title: "Make the other end",
|
||||
body: "Duplicate the solid cylinder and place the copy on the right end.",
|
||||
image: "/assets/challenges/key-tag/04-right-round-end.png",
|
||||
alt: "Two solid cylinders forming both rounded ends of the Key Tag",
|
||||
},
|
||||
{
|
||||
eyebrow: "Step 4",
|
||||
title: "Lock the left circle",
|
||||
body: "Select the left solid cylinder and press Lock. It will be the alignment reference.",
|
||||
image: "/assets/challenges/key-tag/05-select-left-circle.png",
|
||||
alt: "The left solid cylinder selected in the SketchForge workplane",
|
||||
},
|
||||
{
|
||||
eyebrow: "Step 5",
|
||||
title: "Create the hole",
|
||||
body: "Add another Cylinder, set its size, then change it from Solid to Hole.",
|
||||
image: "/assets/challenges/key-tag/06-hole-cylinder.png",
|
||||
alt: "The small hole cylinder added near the left end of the Key Tag",
|
||||
dimensions: [
|
||||
{ label: "Length", value: "3.00 mm", slider: 8 },
|
||||
{ label: "Width", value: "3.00 mm", slider: 8 },
|
||||
{ label: "Height", value: "2.00 mm", slider: 7 },
|
||||
],
|
||||
},
|
||||
{
|
||||
eyebrow: "Step 6",
|
||||
title: "Align the hole",
|
||||
body: "Select the hole and the locked left circle. Press Align and choose the middle on both horizontal axes.",
|
||||
image: "/assets/challenges/key-tag/07-align-hole.png",
|
||||
alt: "The hole aligned to the center of the left solid cylinder",
|
||||
},
|
||||
{
|
||||
eyebrow: "Step 7",
|
||||
title: "Unlock the circle",
|
||||
body: "Select the left solid circle again and press Unlock.",
|
||||
image: "/assets/challenges/key-tag/08-unlock-left-circle.png",
|
||||
alt: "The left solid cylinder selected again after the hole has been aligned",
|
||||
},
|
||||
{
|
||||
eyebrow: "Step 8",
|
||||
title: "Group the Key Tag",
|
||||
body: "Select the box, both solid circles, and the hole. Press Group.",
|
||||
image: "/assets/challenges/key-tag/09-grouped-key-tag.png",
|
||||
alt: "The finished grouped Key Tag selected in SketchForge",
|
||||
},
|
||||
];
|
||||
|
||||
function storedStepIndex() {
|
||||
if (typeof window === "undefined") return 0;
|
||||
const parsed = Number.parseInt(window.localStorage.getItem(KEY_TAG_STEP_STORAGE_KEY) ?? "0", 10);
|
||||
return Number.isFinite(parsed) ? Math.max(0, Math.min(STEPS.length - 1, parsed)) : 0;
|
||||
}
|
||||
|
||||
export function KeyTagTutorialPanel({
|
||||
onFinish,
|
||||
collapsed = false,
|
||||
onCollapsedChange,
|
||||
}: {
|
||||
onFinish?: () => void;
|
||||
collapsed?: boolean;
|
||||
onCollapsedChange?: (collapsed: boolean) => void;
|
||||
}) {
|
||||
const [stepIndex, setStepIndex] = useState(storedStepIndex);
|
||||
const step = STEPS[stepIndex];
|
||||
const first = stepIndex === 0;
|
||||
const last = stepIndex === STEPS.length - 1;
|
||||
|
||||
const goToStep = (index: number) => {
|
||||
const next = Math.max(0, Math.min(STEPS.length - 1, index));
|
||||
setStepIndex(next);
|
||||
window.localStorage.setItem(KEY_TAG_STEP_STORAGE_KEY, String(next));
|
||||
};
|
||||
|
||||
if (collapsed) {
|
||||
return (
|
||||
<aside className="key-tag-tutorial-panel key-tag-tutorial-panel-collapsed" aria-label="Key Tag challenge instructions">
|
||||
<button
|
||||
type="button"
|
||||
className="key-tag-tutorial-expand"
|
||||
title="Expand challenge instructions"
|
||||
aria-label="Expand challenge instructions"
|
||||
onClick={() => onCollapsedChange?.(false)}
|
||||
>
|
||||
<ChevronLeft size={19} />
|
||||
</button>
|
||||
<span className="key-tag-tutorial-collapsed-label">Key Tag</span>
|
||||
<span className="key-tag-tutorial-collapsed-count">{stepIndex + 1}/{STEPS.length}</span>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="key-tag-tutorial-panel"
|
||||
aria-label="Key Tag challenge instructions"
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
onWheel={(event) => event.stopPropagation()}
|
||||
>
|
||||
<header className="key-tag-tutorial-header">
|
||||
<div>
|
||||
<span>Challenge 1</span>
|
||||
<strong>Key Tag</strong>
|
||||
</div>
|
||||
<div className="key-tag-tutorial-header-actions">
|
||||
<span className="key-tag-tutorial-count">{stepIndex + 1} / {STEPS.length}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="key-tag-tutorial-collapse"
|
||||
title="Minimize challenge instructions"
|
||||
aria-label="Minimize challenge instructions"
|
||||
onClick={() => onCollapsedChange?.(true)}
|
||||
>
|
||||
<ChevronRight size={18} />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="key-tag-tutorial-body">
|
||||
<div className="key-tag-tutorial-copy">
|
||||
<span className="key-tag-tutorial-eyebrow">{step.eyebrow}</span>
|
||||
<h2>{step.title}</h2>
|
||||
<p>{step.body}</p>
|
||||
|
||||
{step.snapGrid ? (
|
||||
<div className="key-tag-snap-row" aria-label={`Snap Grid ${step.snapGrid}`}>
|
||||
<span>Snap Grid</span>
|
||||
<strong>{step.snapGrid}</strong>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{step.dimensions ? (
|
||||
<div className="key-tag-tutorial-dimensions" aria-label="Required dimensions">
|
||||
{step.dimensions.map((dimension) => (
|
||||
<div className="key-tag-tutorial-dimension-control" key={dimension.label}>
|
||||
<div className="key-tag-tutorial-dimension-heading">
|
||||
<span>{dimension.label}</span>
|
||||
<strong>{dimension.value}</strong>
|
||||
</div>
|
||||
<div className="key-tag-tutorial-slider" aria-hidden="true">
|
||||
<span style={{ width: `${dimension.slider}%` }} />
|
||||
<i style={{ left: `${dimension.slider}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="key-tag-tutorial-image-box">
|
||||
<img className="key-tag-tutorial-capture" src={step.image} alt={step.alt} draggable={false} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer className="key-tag-tutorial-footer">
|
||||
<button type="button" className="secondary" disabled={first} onClick={() => goToStep(stepIndex - 1)}>
|
||||
<ChevronLeft size={17} /> Previous
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="primary"
|
||||
onClick={() => {
|
||||
if (last) {
|
||||
window.localStorage.removeItem(KEY_TAG_STEP_STORAGE_KEY);
|
||||
onFinish?.();
|
||||
return;
|
||||
}
|
||||
goToStep(stepIndex + 1);
|
||||
}}
|
||||
>
|
||||
{last ? "Finish" : "Next"} {!last ? <ChevronRight size={17} /> : null}
|
||||
</button>
|
||||
</footer>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowUp, ChevronLeft, ChevronRight } from "lucide-react";
|
||||
import { useLayoutEffect, useState } from "react";
|
||||
|
||||
const NAMEPLATE_STEP_STORAGE_KEY = "sketchforge:nameplate-tutorial-step";
|
||||
|
||||
type TutorialDimension = {
|
||||
label: "Length" | "Width" | "Height" | "Elevation";
|
||||
value: string;
|
||||
slider: number;
|
||||
};
|
||||
|
||||
type TutorialStep = {
|
||||
eyebrow: string;
|
||||
title: string;
|
||||
body: string;
|
||||
image: string;
|
||||
alt: string;
|
||||
dimensions?: TutorialDimension[];
|
||||
snapGrid?: string;
|
||||
callout?: string;
|
||||
};
|
||||
|
||||
const STEPS: TutorialStep[] = [
|
||||
{
|
||||
eyebrow: "Before you start",
|
||||
title: "Build a Nameplate",
|
||||
body: "Create a rounded base, personalize a Text object, then combine both parts into one printable design.",
|
||||
image: "/assets/challenges/nameplate/01-finished-target.webp",
|
||||
alt: "Finished blue ALEX nameplate on the SketchForge workplane",
|
||||
snapGrid: "0.5 mm",
|
||||
},
|
||||
{
|
||||
eyebrow: "Step 1",
|
||||
title: "Make the base",
|
||||
body: "Add a Box and enter these dimensions in the shape panel.",
|
||||
image: "/assets/challenges/nameplate/02-base-box.webp",
|
||||
alt: "Plain rectangular blue nameplate base",
|
||||
dimensions: [
|
||||
{ label: "Length", value: "24.00 mm", slider: 24 },
|
||||
{ label: "Width", value: "70.00 mm", slider: 70 },
|
||||
{ label: "Height", value: "3.00 mm", slider: 12 },
|
||||
],
|
||||
},
|
||||
{
|
||||
eyebrow: "Step 2",
|
||||
title: "Round the outside",
|
||||
body: "Select the base, press Fillet, select its outside edges, and apply the treatment.",
|
||||
image: "/assets/challenges/nameplate/03-rounded-base.webp",
|
||||
alt: "Blue nameplate base with softly rounded outer edges",
|
||||
callout: "Use a 1.00 mm fillet amount.",
|
||||
},
|
||||
{
|
||||
eyebrow: "Step 3",
|
||||
title: "Add a Text object",
|
||||
body: "Open Shapes and add Text. The new object starts with the letter T.",
|
||||
image: "/assets/challenges/nameplate/04-text-added.webp",
|
||||
alt: "A red capital T Text object on the blue nameplate base",
|
||||
},
|
||||
{
|
||||
eyebrow: "Step 4",
|
||||
title: "Personalize the text",
|
||||
body: "Change the Text field to your name. This example uses ALEX. Pick any font you like.",
|
||||
image: "/assets/challenges/nameplate/05-text-customized.webp",
|
||||
alt: "Raised red ALEX text placed off-center on the blue base",
|
||||
dimensions: [
|
||||
{ label: "Height", value: "2.00 mm", slider: 9 },
|
||||
],
|
||||
},
|
||||
{
|
||||
eyebrow: "Step 5",
|
||||
title: "Place it on top",
|
||||
body: "Lift the Text object until its bottom sits exactly on the top face of the 3 mm base.",
|
||||
image: "/assets/challenges/nameplate/05-text-customized.webp",
|
||||
alt: "Raised red ALEX text resting on the blue nameplate base",
|
||||
dimensions: [
|
||||
{ label: "Elevation", value: "3.00 mm", slider: 12 },
|
||||
],
|
||||
},
|
||||
{
|
||||
eyebrow: "Step 6",
|
||||
title: "Center the name",
|
||||
body: "Lock the base, select the Text and base, then Align to the middle on both horizontal axes. Unlock the base afterward.",
|
||||
image: "/assets/challenges/nameplate/06-text-centered.webp",
|
||||
alt: "Red ALEX text centered on the blue nameplate base",
|
||||
callout: "The locked base stays fixed as your alignment reference.",
|
||||
},
|
||||
{
|
||||
eyebrow: "Step 7",
|
||||
title: "Group the Nameplate",
|
||||
body: "Select the base and Text object, then press Group to make one finished printable model.",
|
||||
image: "/assets/challenges/nameplate/07-grouped-nameplate.webp",
|
||||
alt: "Finished grouped blue ALEX nameplate",
|
||||
},
|
||||
];
|
||||
|
||||
function storedStepIndex() {
|
||||
if (typeof window === "undefined") return 0;
|
||||
const parsed = Number.parseInt(window.localStorage.getItem(NAMEPLATE_STEP_STORAGE_KEY) ?? "0", 10);
|
||||
return Number.isFinite(parsed) ? Math.max(0, Math.min(STEPS.length - 1, parsed)) : 0;
|
||||
}
|
||||
|
||||
function FilletButtonCoachmark() {
|
||||
const [position, setPosition] = useState<{ left: number; top: number } | null>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const target = document.querySelector<HTMLButtonElement>('button[data-sketchforge-tool="fillet"]');
|
||||
if (!target) return;
|
||||
|
||||
const updatePosition = () => {
|
||||
const rect = target.getBoundingClientRect();
|
||||
setPosition({
|
||||
left: rect.left + rect.width / 2,
|
||||
top: rect.bottom + 42,
|
||||
});
|
||||
};
|
||||
|
||||
target.classList.add("nameplate-fillet-button-target");
|
||||
updatePosition();
|
||||
window.addEventListener("resize", updatePosition);
|
||||
window.addEventListener("scroll", updatePosition, true);
|
||||
const observer = new ResizeObserver(updatePosition);
|
||||
observer.observe(target);
|
||||
|
||||
return () => {
|
||||
target.classList.remove("nameplate-fillet-button-target");
|
||||
window.removeEventListener("resize", updatePosition);
|
||||
window.removeEventListener("scroll", updatePosition, true);
|
||||
observer.disconnect();
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (!position) return null;
|
||||
|
||||
return (
|
||||
<div className="nameplate-fillet-coachmark" style={position} role="status">
|
||||
<ArrowUp size={30} strokeWidth={3} aria-hidden="true" />
|
||||
<strong>Click Fillet</strong>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function NameplateTutorialPanel({
|
||||
onFinish,
|
||||
collapsed = false,
|
||||
onCollapsedChange,
|
||||
}: {
|
||||
onFinish?: () => void;
|
||||
collapsed?: boolean;
|
||||
onCollapsedChange?: (collapsed: boolean) => void;
|
||||
}) {
|
||||
const [stepIndex, setStepIndex] = useState(storedStepIndex);
|
||||
const step = STEPS[stepIndex];
|
||||
const first = stepIndex === 0;
|
||||
const last = stepIndex === STEPS.length - 1;
|
||||
|
||||
const goToStep = (index: number) => {
|
||||
const next = Math.max(0, Math.min(STEPS.length - 1, index));
|
||||
setStepIndex(next);
|
||||
window.localStorage.setItem(NAMEPLATE_STEP_STORAGE_KEY, String(next));
|
||||
};
|
||||
|
||||
if (collapsed) {
|
||||
return (
|
||||
<aside className="key-tag-tutorial-panel key-tag-tutorial-panel-collapsed" aria-label="Personalized Nameplate challenge instructions">
|
||||
<button
|
||||
type="button"
|
||||
className="key-tag-tutorial-expand"
|
||||
title="Expand challenge instructions"
|
||||
aria-label="Expand challenge instructions"
|
||||
onClick={() => onCollapsedChange?.(false)}
|
||||
>
|
||||
<ChevronLeft size={19} />
|
||||
</button>
|
||||
<span className="key-tag-tutorial-collapsed-label">Nameplate</span>
|
||||
<span className="key-tag-tutorial-collapsed-count">{stepIndex + 1}/{STEPS.length}</span>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{stepIndex === 2 ? <FilletButtonCoachmark /> : null}
|
||||
<aside
|
||||
className="key-tag-tutorial-panel"
|
||||
aria-label="Personalized Nameplate challenge instructions"
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
onWheel={(event) => event.stopPropagation()}
|
||||
>
|
||||
<header className="key-tag-tutorial-header">
|
||||
<div>
|
||||
<span>Challenge 2</span>
|
||||
<strong>Personalized Nameplate</strong>
|
||||
</div>
|
||||
<div className="key-tag-tutorial-header-actions">
|
||||
<span className="key-tag-tutorial-count">{stepIndex + 1} / {STEPS.length}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="key-tag-tutorial-collapse"
|
||||
title="Minimize challenge instructions"
|
||||
aria-label="Minimize challenge instructions"
|
||||
onClick={() => onCollapsedChange?.(true)}
|
||||
>
|
||||
<ChevronRight size={18} />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="key-tag-tutorial-body">
|
||||
<div className="key-tag-tutorial-copy">
|
||||
<span className="key-tag-tutorial-eyebrow">{step.eyebrow}</span>
|
||||
<h2>{step.title}</h2>
|
||||
<p>{step.body}</p>
|
||||
|
||||
{step.snapGrid ? (
|
||||
<div className="key-tag-snap-row" aria-label={`Snap Grid ${step.snapGrid}`}>
|
||||
<span>Snap Grid</span>
|
||||
<strong>{step.snapGrid}</strong>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{step.callout ? <div className="nameplate-tutorial-callout">{step.callout}</div> : null}
|
||||
|
||||
{step.dimensions ? (
|
||||
<div className="key-tag-tutorial-dimensions" aria-label="Required dimensions">
|
||||
{step.dimensions.map((dimension) => (
|
||||
<div className="key-tag-tutorial-dimension-control" key={dimension.label}>
|
||||
<div className="key-tag-tutorial-dimension-heading">
|
||||
<span>{dimension.label}</span>
|
||||
<strong>{dimension.value}</strong>
|
||||
</div>
|
||||
<div className="key-tag-tutorial-slider" aria-hidden="true">
|
||||
<span style={{ width: `${dimension.slider}%` }} />
|
||||
<i style={{ left: `${dimension.slider}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="key-tag-tutorial-image-box">
|
||||
<img className="key-tag-tutorial-capture" src={step.image} alt={step.alt} draggable={false} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer className="key-tag-tutorial-footer">
|
||||
<button type="button" className="secondary" disabled={first} onClick={() => goToStep(stepIndex - 1)}>
|
||||
<ChevronLeft size={17} /> Previous
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="primary"
|
||||
onClick={() => {
|
||||
if (last) {
|
||||
window.localStorage.removeItem(NAMEPLATE_STEP_STORAGE_KEY);
|
||||
onFinish?.();
|
||||
return;
|
||||
}
|
||||
goToStep(stepIndex + 1);
|
||||
}}
|
||||
>
|
||||
{last ? "Finish" : "Next"} {!last ? <ChevronRight size={17} /> : null}
|
||||
</button>
|
||||
</footer>
|
||||
</aside>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
export const OFFICIAL_UPDATE_GUIDE_URL = "https://github.com/Formsmith746/SketchForge-3D#update-sketchforge-later";
|
||||
|
||||
export type AppUpdateStatus = {
|
||||
currentVersion: string;
|
||||
latestVersion: string | null;
|
||||
updateAvailable: boolean;
|
||||
checkedAt: string;
|
||||
updateUrl: string;
|
||||
installationReady: boolean;
|
||||
requiresUpdateKey: boolean;
|
||||
checkError?: string;
|
||||
};
|
||||
|
||||
type ParsedVersion = {
|
||||
major: number;
|
||||
minor: number;
|
||||
patch: number;
|
||||
prerelease: string[];
|
||||
};
|
||||
|
||||
function parseVersion(value: string): ParsedVersion | null {
|
||||
const match = value.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);
|
||||
if (!match) return null;
|
||||
return {
|
||||
major: Number(match[1]),
|
||||
minor: Number(match[2]),
|
||||
patch: Number(match[3]),
|
||||
prerelease: match[4] ? match[4].split(".") : [],
|
||||
};
|
||||
}
|
||||
|
||||
function comparePrereleasePart(left: string, right: string) {
|
||||
const leftNumber = /^\d+$/.test(left) ? Number(left) : null;
|
||||
const rightNumber = /^\d+$/.test(right) ? Number(right) : null;
|
||||
if (leftNumber !== null && rightNumber !== null) return Math.sign(leftNumber - rightNumber);
|
||||
if (leftNumber !== null) return -1;
|
||||
if (rightNumber !== null) return 1;
|
||||
return left.localeCompare(right);
|
||||
}
|
||||
|
||||
export function compareAppVersions(leftValue: string, rightValue: string) {
|
||||
const left = parseVersion(leftValue);
|
||||
const right = parseVersion(rightValue);
|
||||
if (!left || !right) return leftValue.trim().localeCompare(rightValue.trim());
|
||||
|
||||
for (const key of ["major", "minor", "patch"] as const) {
|
||||
if (left[key] !== right[key]) return Math.sign(left[key] - right[key]);
|
||||
}
|
||||
if (!left.prerelease.length && !right.prerelease.length) return 0;
|
||||
if (!left.prerelease.length) return 1;
|
||||
if (!right.prerelease.length) return -1;
|
||||
|
||||
const partCount = Math.max(left.prerelease.length, right.prerelease.length);
|
||||
for (let index = 0; index < partCount; index += 1) {
|
||||
if (left.prerelease[index] === undefined) return -1;
|
||||
if (right.prerelease[index] === undefined) return 1;
|
||||
const comparison = comparePrereleasePart(left.prerelease[index], right.prerelease[index]);
|
||||
if (comparison !== 0) return comparison;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function appUpdateIsAvailable(currentVersion: string, latestVersion: string) {
|
||||
return compareAppVersions(latestVersion, currentVersion) > 0;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export const CHALLENGE_TUTORIAL_IDS = ["key-tag", "nameplate"] as const;
|
||||
|
||||
export type ChallengeTutorialId = (typeof CHALLENGE_TUTORIAL_IDS)[number];
|
||||
|
||||
export function isChallengeTutorialId(value: unknown): value is ChallengeTutorialId {
|
||||
return typeof value === "string" && CHALLENGE_TUTORIAL_IDS.includes(value as ChallengeTutorialId);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export type MeshPoint = readonly [number, number, number];
|
||||
|
||||
/** Maps the Z-up coordinate convention used by slicers/CAD files into SketchForge's Y-up scene. */
|
||||
export function zUpToSketchForge([x, y, z]: MeshPoint): [number, number, number] {
|
||||
return [x, z, -y];
|
||||
}
|
||||
|
||||
/** Maps SketchForge's Y-up scene into the Z-up coordinate convention expected by slicers. */
|
||||
export function sketchForgeToZUp([x, y, z]: MeshPoint): [number, number, number] {
|
||||
return [x, -z, y];
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import type { MeshPoint } from "@/lib/meshCoordinates";
|
||||
|
||||
export type ObjExportMesh = {
|
||||
name: string;
|
||||
vertices: readonly MeshPoint[];
|
||||
faces: readonly (readonly [number, number, number])[];
|
||||
};
|
||||
|
||||
const OBJ_WELD_TOLERANCE = 0.00001;
|
||||
|
||||
function bucketKey(x: number, y: number, z: number) {
|
||||
return `${x}:${y}:${z}`;
|
||||
}
|
||||
|
||||
function weldMeshVertices(mesh: ObjExportMesh) {
|
||||
const vertices: Array<[number, number, number]> = [];
|
||||
const buckets = new Map<string, number[]>();
|
||||
const remappedIndices: number[] = [];
|
||||
|
||||
mesh.vertices.forEach((sourceVertex) => {
|
||||
// OBJ tools conventionally treat Y as up. Keep SketchForge's Y-up
|
||||
// coordinates here so slicers do not apply their OBJ axis conversion a
|
||||
// second time. STL is exported separately using explicit Z-up coordinates.
|
||||
const vertex: [number, number, number] = [...sourceVertex];
|
||||
const bucketX = Math.floor(vertex[0] / OBJ_WELD_TOLERANCE);
|
||||
const bucketY = Math.floor(vertex[1] / OBJ_WELD_TOLERANCE);
|
||||
const bucketZ = Math.floor(vertex[2] / OBJ_WELD_TOLERANCE);
|
||||
let weldedIndex: number | undefined;
|
||||
|
||||
for (let xOffset = -1; xOffset <= 1 && weldedIndex === undefined; xOffset += 1) {
|
||||
for (let yOffset = -1; yOffset <= 1 && weldedIndex === undefined; yOffset += 1) {
|
||||
for (let zOffset = -1; zOffset <= 1 && weldedIndex === undefined; zOffset += 1) {
|
||||
const candidates = buckets.get(bucketKey(bucketX + xOffset, bucketY + yOffset, bucketZ + zOffset)) ?? [];
|
||||
weldedIndex = candidates.find((candidateIndex) => {
|
||||
const candidate = vertices[candidateIndex];
|
||||
return (
|
||||
Math.abs(candidate[0] - vertex[0]) <= OBJ_WELD_TOLERANCE &&
|
||||
Math.abs(candidate[1] - vertex[1]) <= OBJ_WELD_TOLERANCE &&
|
||||
Math.abs(candidate[2] - vertex[2]) <= OBJ_WELD_TOLERANCE
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (weldedIndex === undefined) {
|
||||
weldedIndex = vertices.length;
|
||||
vertices.push(vertex);
|
||||
const key = bucketKey(bucketX, bucketY, bucketZ);
|
||||
buckets.set(key, [...(buckets.get(key) ?? []), weldedIndex]);
|
||||
}
|
||||
remappedIndices.push(weldedIndex);
|
||||
});
|
||||
|
||||
const faces = mesh.faces
|
||||
.map(([a, b, c]) => [remappedIndices[a], remappedIndices[b], remappedIndices[c]] as [number, number, number])
|
||||
.filter(([a, b, c]) => a !== b && b !== c && c !== a);
|
||||
|
||||
return { vertices, faces };
|
||||
}
|
||||
|
||||
function objNumber(value: number) {
|
||||
return Math.abs(value) < 1e-12 ? "0" : String(value);
|
||||
}
|
||||
|
||||
export function exportMeshesToObj(meshes: readonly ObjExportMesh[]) {
|
||||
const lines = ["# SketchForge OBJ export"];
|
||||
let offset = 1;
|
||||
|
||||
meshes.forEach((mesh) => {
|
||||
const welded = weldMeshVertices(mesh);
|
||||
lines.push(`o ${mesh.name}`);
|
||||
welded.vertices.forEach(([x, y, z]) => lines.push(`v ${objNumber(x)} ${objNumber(y)} ${objNumber(z)}`));
|
||||
welded.faces.forEach(([a, b, c]) => lines.push(`f ${a + offset} ${b + offset} ${c + offset}`));
|
||||
offset += welded.vertices.length;
|
||||
});
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import type { SketchPoint, SketchProfile, SketchSegment } from "@/types/sketchforge";
|
||||
|
||||
export type OrderedCadSketchStep = { segment: SketchSegment; from: SketchPoint; to: SketchPoint };
|
||||
export type OrderedCadSketchPath = { id: string; points: SketchPoint[]; steps: OrderedCadSketchStep[]; closed: boolean };
|
||||
export type CadSketchRegion = { outer: OrderedCadSketchPath; holes: OrderedCadSketchPath[] };
|
||||
|
||||
export function orderedCadSketchPaths(profile: SketchProfile): OrderedCadSketchPath[] {
|
||||
const pointById = new Map(profile.points.map((point) => [point.id, point]));
|
||||
const adjacency = new Map<string, Array<{ pointId: string; segment: SketchSegment }>>();
|
||||
profile.points.forEach((point) => adjacency.set(point.id, []));
|
||||
const valid = profile.segments.filter((segment) => {
|
||||
if (segment.startId === segment.endId || !pointById.has(segment.startId) || !pointById.has(segment.endId)) return false;
|
||||
adjacency.get(segment.startId)?.push({ pointId: segment.endId, segment });
|
||||
adjacency.get(segment.endId)?.push({ pointId: segment.startId, segment });
|
||||
return true;
|
||||
});
|
||||
const unvisited = new Set(valid.map((segment) => segment.id));
|
||||
const paths: OrderedCadSketchPath[] = [];
|
||||
|
||||
while (unvisited.size > 0) {
|
||||
const seedId = unvisited.values().next().value as string;
|
||||
const seed = valid.find((segment) => segment.id === seedId);
|
||||
if (!seed) break;
|
||||
const component = new Set<string>();
|
||||
const queue = [seed.startId, seed.endId];
|
||||
while (queue.length > 0) {
|
||||
const id = queue.pop();
|
||||
if (!id || component.has(id)) continue;
|
||||
component.add(id);
|
||||
adjacency.get(id)?.forEach((edge) => queue.push(edge.pointId));
|
||||
}
|
||||
const startId = [...component].find((id) => (adjacency.get(id)?.filter((edge) => unvisited.has(edge.segment.id)).length ?? 0) === 1) ?? seed.startId;
|
||||
const first = pointById.get(startId);
|
||||
if (!first) {
|
||||
unvisited.delete(seed.id);
|
||||
continue;
|
||||
}
|
||||
const points = [first];
|
||||
const steps: OrderedCadSketchStep[] = [];
|
||||
let currentId = startId;
|
||||
for (let guard = 0; guard <= valid.length; guard += 1) {
|
||||
const edge = adjacency.get(currentId)?.find((candidate) => unvisited.has(candidate.segment.id));
|
||||
if (!edge) break;
|
||||
const from = pointById.get(currentId);
|
||||
const to = pointById.get(edge.pointId);
|
||||
if (!from || !to) break;
|
||||
unvisited.delete(edge.segment.id);
|
||||
steps.push({ segment: edge.segment, from, to });
|
||||
currentId = to.id;
|
||||
if (currentId === startId) break;
|
||||
points.push(to);
|
||||
}
|
||||
paths.push({ id: seed.id, points, steps, closed: currentId === startId && steps.length >= 3 });
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
function sampledPath(path: OrderedCadSketchPath) {
|
||||
const samples: Array<{ x: number; z: number }> = [];
|
||||
path.steps.forEach(({ segment, from, to }, stepIndex) => {
|
||||
if (stepIndex === 0) samples.push({ x: from.x, z: from.z });
|
||||
const forward = segment.startId === from.id;
|
||||
const first = forward ? from.handleOut : from.handleIn;
|
||||
const second = forward ? to.handleIn : to.handleOut;
|
||||
if (segment.kind === "line" || !first || !second) {
|
||||
samples.push({ x: to.x, z: to.z });
|
||||
return;
|
||||
}
|
||||
for (let index = 1; index <= 16; index += 1) {
|
||||
const amount = index / 16;
|
||||
const inverse = 1 - amount;
|
||||
samples.push({
|
||||
x: inverse ** 3 * from.x + 3 * inverse ** 2 * amount * first.x + 3 * inverse * amount ** 2 * second.x + amount ** 3 * to.x,
|
||||
z: inverse ** 3 * from.z + 3 * inverse ** 2 * amount * first.z + 3 * inverse * amount ** 2 * second.z + amount ** 3 * to.z,
|
||||
});
|
||||
}
|
||||
});
|
||||
return samples;
|
||||
}
|
||||
|
||||
function signedArea(points: Array<{ x: number; z: number }>) {
|
||||
return points.reduce((area, point, index) => {
|
||||
const next = points[(index + 1) % points.length];
|
||||
return area + point.x * next.z - next.x * point.z;
|
||||
}, 0) / 2;
|
||||
}
|
||||
|
||||
function pointInPolygon(point: { x: number; z: number }, polygon: Array<{ x: number; z: number }>) {
|
||||
let inside = false;
|
||||
for (let index = 0, previous = polygon.length - 1; index < polygon.length; previous = index, index += 1) {
|
||||
const current = polygon[index];
|
||||
const before = polygon[previous];
|
||||
if ((current.z > point.z) !== (before.z > point.z)
|
||||
&& point.x < ((before.x - current.x) * (point.z - current.z)) / (before.z - current.z) + current.x) inside = !inside;
|
||||
}
|
||||
return inside;
|
||||
}
|
||||
|
||||
export function cadSketchRegions(profile: SketchProfile): CadSketchRegion[] {
|
||||
const allPaths = orderedCadSketchPaths(profile);
|
||||
const openCount = allPaths.filter((path) => !path.closed).length;
|
||||
const records = allPaths
|
||||
.filter((path) => path.closed)
|
||||
.map((path) => {
|
||||
const polygon = sampledPath(path);
|
||||
return { path, polygon, area: Math.abs(signedArea(polygon)) };
|
||||
})
|
||||
.filter((record) => record.polygon.length >= 3 && record.area > 1e-8)
|
||||
.sort((a, b) => b.area - a.area);
|
||||
|
||||
// Compute nesting depth: count how many larger closed paths contain each record.
|
||||
// Even depth = solid (outer boundary), odd depth = hole.
|
||||
const depths = records.map((record, index) => {
|
||||
let depth = 0;
|
||||
for (let i = 0; i < records.length; i++) {
|
||||
if (i === index) continue;
|
||||
if (records[i].area > record.area && pointInPolygon(record.polygon[0], records[i].polygon)) {
|
||||
depth++;
|
||||
}
|
||||
}
|
||||
return depth;
|
||||
});
|
||||
|
||||
const regions: CadSketchRegion[] = [];
|
||||
records.forEach((record, index) => {
|
||||
const depth = depths[index];
|
||||
if (depth % 2 === 0) {
|
||||
regions.push({ outer: record.path, holes: [] });
|
||||
} else {
|
||||
// Odd depth: find the nearest even-depth ancestor (smallest containing solid)
|
||||
let bestParent: (typeof records)[number] | null = null;
|
||||
for (let i = 0; i < records.length; i++) {
|
||||
if (i === index) continue;
|
||||
if (depths[i] % 2 === 0 && depths[i] < depth && records[i].area > record.area && pointInPolygon(record.polygon[0], records[i].polygon)) {
|
||||
if (!bestParent || records[i].area < bestParent.area) {
|
||||
bestParent = records[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (bestParent) {
|
||||
const region = regions.find((r) => r.outer === bestParent!.path);
|
||||
if (region) region.holes.push(record.path);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (regions.length === 0 && openCount > 0 && allPaths.length > 0) {
|
||||
throw new Error("All profile paths are open. Close at least one loop before finishing the sketch.");
|
||||
}
|
||||
return regions;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { SketchProfile } from "@/types/sketchforge";
|
||||
|
||||
export type SketchCadBuildRequest = {
|
||||
type: "build";
|
||||
requestId: number;
|
||||
profile: SketchProfile;
|
||||
height: number;
|
||||
};
|
||||
|
||||
export type SketchCadBuildResponse =
|
||||
| {
|
||||
type: "built";
|
||||
requestId: number;
|
||||
positions: Float32Array;
|
||||
normals: Float32Array;
|
||||
indices: Uint32Array;
|
||||
triangleCount: number;
|
||||
brep: string;
|
||||
}
|
||||
| { type: "error"; requestId: number; message: string };
|
||||
@@ -11,7 +11,7 @@ import type { GridSize, ProjectAsset, ProjectAssetSourceFormat, SketchOperation,
|
||||
export const SKF_SCHEMA_ID = "com.sketchforge.project";
|
||||
export const SKF_FORMAT_VERSION = 1;
|
||||
export const SKF_MINIMUM_READER_VERSION = 1;
|
||||
export const SKF_CREATED_WITH_VERSION = "0.9.0";
|
||||
export const SKF_CREATED_WITH_VERSION = "1.0.0";
|
||||
export const SKF_MEDIA_TYPE = "application/vnd.sketchforge.project+zip";
|
||||
|
||||
export const SKF_LIMITS = {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { sketchForgeToZUp, type MeshPoint } from "@/lib/meshCoordinates";
|
||||
|
||||
export type StlExportMesh = {
|
||||
vertices: readonly MeshPoint[];
|
||||
faces: readonly (readonly [number, number, number])[];
|
||||
};
|
||||
|
||||
function normalFor(a: MeshPoint, b: MeshPoint, c: MeshPoint): [number, number, number] {
|
||||
const ux = b[0] - a[0];
|
||||
const uy = b[1] - a[1];
|
||||
const uz = b[2] - a[2];
|
||||
const vx = c[0] - a[0];
|
||||
const vy = c[1] - a[1];
|
||||
const vz = c[2] - a[2];
|
||||
const nx = uy * vz - uz * vy;
|
||||
const ny = uz * vx - ux * vz;
|
||||
const nz = ux * vy - uy * vx;
|
||||
const length = Math.hypot(nx, ny, nz) || 1;
|
||||
return [nx / length, ny / length, nz / length];
|
||||
}
|
||||
|
||||
export function exportMeshesToStl(meshes: readonly StlExportMesh[]) {
|
||||
const lines = ["solid sketchforge_design"];
|
||||
meshes.forEach((mesh) => {
|
||||
mesh.faces.forEach(([ai, bi, ci]) => {
|
||||
const a = sketchForgeToZUp(mesh.vertices[ai]);
|
||||
const b = sketchForgeToZUp(mesh.vertices[bi]);
|
||||
const c = sketchForgeToZUp(mesh.vertices[ci]);
|
||||
const n = normalFor(a, b, c);
|
||||
lines.push(` facet normal ${n[0]} ${n[1]} ${n[2]}`);
|
||||
lines.push(" outer loop");
|
||||
lines.push(` vertex ${a[0]} ${a[1]} ${a[2]}`);
|
||||
lines.push(` vertex ${b[0]} ${b[1]} ${b[2]}`);
|
||||
lines.push(` vertex ${c[0]} ${c[1]} ${c[2]}`);
|
||||
lines.push(" endloop");
|
||||
lines.push(" endfacet");
|
||||
});
|
||||
});
|
||||
lines.push("endsolid sketchforge_design");
|
||||
return lines.join("\n");
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as THREE from "three";
|
||||
import { STLLoader } from "three/examples/jsm/loaders/STLLoader.js";
|
||||
import { createLocalId } from "@/lib/localIds";
|
||||
import { zUpToSketchForge } from "@/lib/meshCoordinates";
|
||||
import type { WorkplaneShape } from "@/types/sketchforge";
|
||||
|
||||
const stlLoader = new STLLoader();
|
||||
@@ -10,6 +11,34 @@ function fileExtension(fileName: string) {
|
||||
return fileName.split(".").pop()?.toLowerCase() ?? "";
|
||||
}
|
||||
|
||||
function stlHeader(buffer: ArrayBuffer) {
|
||||
return new TextDecoder("ascii").decode(new Uint8Array(buffer, 0, Math.min(80, buffer.byteLength))).toLowerCase();
|
||||
}
|
||||
|
||||
function stlUsesSketchForgeYUp(buffer: ArrayBuffer, position: THREE.BufferAttribute | THREE.InterleavedBufferAttribute) {
|
||||
// SketchForge's older ASCII STL exports were already Y-up. Preserve those,
|
||||
// including tall models where geometry alone cannot reveal an up axis.
|
||||
if (stlHeader(buffer).includes("sketchforge")) return true;
|
||||
|
||||
let minY = Number.POSITIVE_INFINITY;
|
||||
let maxY = Number.NEGATIVE_INFINITY;
|
||||
let minZ = Number.POSITIVE_INFINITY;
|
||||
let maxZ = Number.NEGATIVE_INFINITY;
|
||||
for (let i = 0; i < position.count; i += 1) {
|
||||
minY = Math.min(minY, position.getY(i));
|
||||
maxY = Math.max(maxY, position.getY(i));
|
||||
minZ = Math.min(minZ, position.getZ(i));
|
||||
maxZ = Math.max(maxZ, position.getZ(i));
|
||||
}
|
||||
|
||||
const ySpan = maxY - minY;
|
||||
const zSpan = maxZ - minZ;
|
||||
// Some legacy/model-library STLs (including the Raspberry Pi fixture) are
|
||||
// unmistakably flat on Y. Keep that established orientation; ambiguous STL
|
||||
// files follow the slicer-standard Z-up convention.
|
||||
return Number.isFinite(ySpan) && Number.isFinite(zSpan) && ySpan <= zSpan * 0.55;
|
||||
}
|
||||
|
||||
export function importedShapeFromTriangleSoup(
|
||||
fileName: string,
|
||||
rawPositions: number[],
|
||||
@@ -97,11 +126,14 @@ export function importedShapeFromStl(fileName: string, buffer: ArrayBuffer): Wor
|
||||
const normal = geometry.getAttribute("normal");
|
||||
const rawPositions: number[] = [];
|
||||
const rawNormals: number[] = [];
|
||||
const usesSketchForgeYUp = stlUsesSketchForgeYUp(buffer, position);
|
||||
|
||||
for (let i = 0; i < position.count; i += 1) {
|
||||
rawPositions.push(position.getX(i), position.getY(i), position.getZ(i));
|
||||
const sourcePosition: [number, number, number] = [position.getX(i), position.getY(i), position.getZ(i)];
|
||||
rawPositions.push(...(usesSketchForgeYUp ? sourcePosition : zUpToSketchForge(sourcePosition)));
|
||||
if (normal) {
|
||||
rawNormals.push(normal.getX(i), normal.getY(i), normal.getZ(i));
|
||||
const sourceNormal: [number, number, number] = [normal.getX(i), normal.getY(i), normal.getZ(i)];
|
||||
rawNormals.push(...(usesSketchForgeYUp ? sourceNormal : zUpToSketchForge(sourceNormal)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
/// <reference lib="webworker" />
|
||||
|
||||
import { OcctKernel, type ShapeHandle } from "occt-wasm";
|
||||
import { cadSketchRegions, type OrderedCadSketchPath } from "@/lib/sketchCadProfile";
|
||||
import type { SketchCadBuildRequest, SketchCadBuildResponse } from "@/lib/sketchCadTypes";
|
||||
|
||||
let kernelPromise: Promise<OcctKernel> | null = null;
|
||||
|
||||
function kernel() {
|
||||
const moduleUrl = "/occt/occt-wasm.js";
|
||||
kernelPromise ??= import(/* webpackIgnore: true */ moduleUrl)
|
||||
.then((imported: { default: (options?: { locateFile?: (path: string) => string }) => Promise<unknown> }) => imported.default({
|
||||
locateFile: (path) => path.endsWith(".wasm") ? "/occt/occt-wasm.wasm" : path,
|
||||
}))
|
||||
.then((module) => {
|
||||
const KernelConstructor = OcctKernel as unknown as new (rawModule: unknown) => OcctKernel;
|
||||
return new KernelConstructor(module);
|
||||
});
|
||||
return kernelPromise;
|
||||
}
|
||||
|
||||
function post(message: SketchCadBuildResponse, transfer: Transferable[] = []) {
|
||||
self.postMessage(message, { transfer });
|
||||
}
|
||||
|
||||
function pathWire(cad: OcctKernel, path: OrderedCadSketchPath) {
|
||||
const edges = path.steps.map(({ segment, from, to }) => {
|
||||
const forward = segment.startId === from.id;
|
||||
const first = forward ? from.handleOut : from.handleIn;
|
||||
const second = forward ? to.handleIn : to.handleOut;
|
||||
if (segment.kind !== "line" && first && second) {
|
||||
return cad.makeBezierEdge([
|
||||
{ x: from.x, y: 0, z: from.z },
|
||||
{ x: first.x, y: 0, z: first.z },
|
||||
{ x: second.x, y: 0, z: second.z },
|
||||
{ x: to.x, y: 0, z: to.z },
|
||||
]);
|
||||
}
|
||||
return cad.makeLineEdge({ x: from.x, y: 0, z: from.z }, { x: to.x, y: 0, z: to.z });
|
||||
});
|
||||
return cad.makeWire(edges);
|
||||
}
|
||||
|
||||
self.onmessage = async (event: MessageEvent<SketchCadBuildRequest>) => {
|
||||
const request = event.data;
|
||||
let cad: OcctKernel | null = null;
|
||||
try {
|
||||
cad = await kernel();
|
||||
cad.releaseAll();
|
||||
const regions = cadSketchRegions(request.profile);
|
||||
if (regions.length === 0) throw new Error("No closed profile found. Draw at least one closed loop and ensure it has no degenerate (zero-area) geometry.");
|
||||
const solids: ShapeHandle[] = regions.map((region) => {
|
||||
let face = cad!.makeFace(pathWire(cad!, region.outer));
|
||||
if (region.holes.length > 0) face = cad!.addHolesInFace(face, region.holes.map((hole) => pathWire(cad!, hole)));
|
||||
return cad!.extrude(face, 0, request.height, 0);
|
||||
});
|
||||
const result = solids.length === 1 ? solids[0] : cad.makeCompound(solids);
|
||||
if (!cad.isValid(result)) throw new Error("OpenCascade produced invalid sketch topology");
|
||||
const mesh = cad.tessellate(result, { linearDeflection: 0.05, angularDeflection: 0.16 });
|
||||
const positions = new Float32Array(mesh.positions);
|
||||
const normals = new Float32Array(mesh.normals);
|
||||
const indices = new Uint32Array(mesh.indices);
|
||||
const brep = cad.toBREP(result);
|
||||
post({ type: "built", requestId: request.requestId, positions, normals, indices, triangleCount: mesh.triangleCount, brep }, [positions.buffer, normals.buffer, indices.buffer]);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error ?? "The CAD kernel could not build this sketch");
|
||||
post({ type: "error", requestId: request.requestId, message });
|
||||
if (/memory|WebAssembly|abort/i.test(message)) kernelPromise = null;
|
||||
} finally {
|
||||
try {
|
||||
cad?.releaseAll();
|
||||
} catch {
|
||||
// The arena may already have reset after a kernel error.
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export {};
|
||||
@@ -5,6 +5,9 @@ services:
|
||||
- "${SKETCHFORGE_PORT:-3000}:3000"
|
||||
environment:
|
||||
SKETCHFORGE_SHARED_PROJECTS_DIR: /data/projects
|
||||
SKETCHFORGE_UPDATE_TRIGGER_URL: "${SKETCHFORGE_UPDATE_TRIGGER_URL:-}"
|
||||
SKETCHFORGE_UPDATE_ADMIN_KEY: "${SKETCHFORGE_UPDATE_ADMIN_KEY:-}"
|
||||
SKETCHFORGE_UPDATE_TRIGGER_TOKEN: "${SKETCHFORGE_UPDATE_TRIGGER_TOKEN:-}"
|
||||
volumes:
|
||||
- "${SKETCHFORGE_SHARED_PROJECTS_VOLUME:-sketchforge-shared-projects}:/data/projects"
|
||||
restart: unless-stopped
|
||||
|
||||
@@ -8,6 +8,9 @@ services:
|
||||
- "${SKETCHFORGE_PORT:-3000}:3000"
|
||||
environment:
|
||||
SKETCHFORGE_SHARED_PROJECTS_DIR: /data/projects
|
||||
SKETCHFORGE_UPDATE_TRIGGER_URL: "${SKETCHFORGE_UPDATE_TRIGGER_URL:-}"
|
||||
SKETCHFORGE_UPDATE_ADMIN_KEY: "${SKETCHFORGE_UPDATE_ADMIN_KEY:-}"
|
||||
SKETCHFORGE_UPDATE_TRIGGER_TOKEN: "${SKETCHFORGE_UPDATE_TRIGGER_TOKEN:-}"
|
||||
volumes:
|
||||
- "${SKETCHFORGE_SHARED_PROJECTS_VOLUME:-sketchforge-shared-projects}:/data/projects"
|
||||
restart: unless-stopped
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
{
|
||||
"name": "sketchforge",
|
||||
"version": "0.9.0",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "sketchforge",
|
||||
"version": "0.9.0",
|
||||
"license": "MIT",
|
||||
"version": "1.0.0",
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@tailwindcss/postcss": "^4.1.8",
|
||||
"@types/three": "^0.184.1",
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "sketchforge",
|
||||
"version": "0.9.0",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"license": "AGPL-3.0-only",
|
||||
"scripts": {
|
||||
"copy:occt": "node scripts/copy-occt-wasm.mjs",
|
||||
"predev": "npm run copy:occt",
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, join } from "node:path";
|
||||
import type { SketchProfile } from "@/types/sketchforge";
|
||||
|
||||
// Load the real OCCT kernel directly (same approach as stepRoundTrip.e2e.ts).
|
||||
vi.mock("@/lib/brepKernel", async () => {
|
||||
const brep = await import("brepjs");
|
||||
const { OcctKernel } = await import("occt-wasm");
|
||||
const wasm = join(dirname(fileURLToPath(import.meta.resolve("occt-wasm"))), "occt-wasm.wasm");
|
||||
let ready: Promise<typeof brep> | null = null;
|
||||
return {
|
||||
loadBrepWithOcct: () =>
|
||||
(ready ??= (async () => {
|
||||
const kernel = await OcctKernel.init({ wasm });
|
||||
brep.registerKernel("occt-wasm", brep.OcctWasmAdapter.fromKernel(kernel));
|
||||
return brep;
|
||||
})()),
|
||||
};
|
||||
});
|
||||
|
||||
let cadSketchRegions: typeof import("@/lib/sketchCadProfile").cadSketchRegions;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ cadSketchRegions } = await import("@/lib/sketchCadProfile"));
|
||||
});
|
||||
|
||||
function rectangle(id: string, x: number, z: number, width: number, depth: number): SketchProfile {
|
||||
const points = [
|
||||
{ id: `${id}-0`, x, z },
|
||||
{ id: `${id}-1`, x: x + width, z },
|
||||
{ id: `${id}-2`, x: x + width, z: z + depth },
|
||||
{ id: `${id}-3`, x, z: z + depth },
|
||||
];
|
||||
const segments = points.map((point, index) => ({
|
||||
id: `${id}-s${index}`,
|
||||
kind: "line" as const,
|
||||
startId: point.id,
|
||||
endId: points[(index + 1) % points.length].id,
|
||||
}));
|
||||
return { points, segments };
|
||||
}
|
||||
|
||||
function mergeProfiles(...profiles: SketchProfile[]): SketchProfile {
|
||||
return {
|
||||
points: profiles.flatMap((p) => p.points),
|
||||
segments: profiles.flatMap((p) => p.segments),
|
||||
};
|
||||
}
|
||||
|
||||
describe("Sketch CAD profile → B-Rep extrusion (real OCCT kernel)", () => {
|
||||
it("produces valid B-Rep from a single closed rectangle", async () => {
|
||||
const { OcctKernel } = await import("occt-wasm");
|
||||
const profile = rectangle("rect", 0, 0, 20, 10);
|
||||
const regions = cadSketchRegions(profile);
|
||||
expect(regions).toHaveLength(1);
|
||||
expect(regions[0].outer.closed).toBe(true);
|
||||
expect(regions[0].holes).toHaveLength(0);
|
||||
|
||||
const wasm = join(dirname(fileURLToPath(import.meta.resolve("occt-wasm"))), "occt-wasm.wasm");
|
||||
const kernel = await OcctKernel.init({ wasm });
|
||||
|
||||
const edges = regions[0].outer.steps.map(({ from, to }) =>
|
||||
kernel.makeLineEdge({ x: from.x, y: 0, z: from.z }, { x: to.x, y: 0, z: to.z }),
|
||||
);
|
||||
const wire = kernel.makeWire(edges);
|
||||
const face = kernel.makeFace(wire);
|
||||
const solid = kernel.extrude(face, 0, 15, 0);
|
||||
expect(kernel.isValid(solid)).toBe(true);
|
||||
expect(kernel.isSolid(solid)).toBe(true);
|
||||
|
||||
const mesh = kernel.tessellate(solid, { linearDeflection: 0.05, angularDeflection: 0.16 });
|
||||
expect(mesh.triangleCount).toBeGreaterThan(0);
|
||||
expect(mesh.positions.length).toBeGreaterThanOrEqual(9);
|
||||
expect(mesh.indices.length).toBeGreaterThanOrEqual(3);
|
||||
|
||||
const brep = kernel.toBREP(solid);
|
||||
expect(brep).toBeTruthy();
|
||||
expect(brep.length).toBeGreaterThan(0);
|
||||
kernel.releaseAll();
|
||||
});
|
||||
|
||||
it("extrudes a rectangle with a hole into a valid hollow solid", async () => {
|
||||
const { OcctKernel } = await import("occt-wasm");
|
||||
const profile = mergeProfiles(
|
||||
rectangle("outer", 0, 0, 40, 40),
|
||||
rectangle("hole", 10, 10, 20, 20),
|
||||
);
|
||||
const regions = cadSketchRegions(profile);
|
||||
expect(regions).toHaveLength(1);
|
||||
expect(regions[0].holes).toHaveLength(1);
|
||||
|
||||
const wasm = join(dirname(fileURLToPath(import.meta.resolve("occt-wasm"))), "occt-wasm.wasm");
|
||||
const kernel = await OcctKernel.init({ wasm });
|
||||
|
||||
const outerEdges = regions[0].outer.steps.map(({ from, to }) =>
|
||||
kernel.makeLineEdge({ x: from.x, y: 0, z: from.z }, { x: to.x, y: 0, z: to.z }),
|
||||
);
|
||||
const outerWire = kernel.makeWire(outerEdges);
|
||||
let face = kernel.makeFace(outerWire);
|
||||
|
||||
const holeEdges = regions[0].holes[0].steps.map(({ from, to }) =>
|
||||
kernel.makeLineEdge({ x: from.x, y: 0, z: from.z }, { x: to.x, y: 0, z: to.z }),
|
||||
);
|
||||
const holeWire = kernel.makeWire(holeEdges);
|
||||
face = kernel.addHolesInFace(face, [holeWire]);
|
||||
|
||||
const solid = kernel.extrude(face, 0, 10, 0);
|
||||
expect(kernel.isValid(solid)).toBe(true);
|
||||
expect(kernel.isSolid(solid)).toBe(true);
|
||||
|
||||
const mesh = kernel.tessellate(solid, { linearDeflection: 0.05, angularDeflection: 0.16 });
|
||||
expect(mesh.triangleCount).toBeGreaterThan(0);
|
||||
kernel.releaseAll();
|
||||
});
|
||||
|
||||
it("produces two separate solids from disjoint rectangles", async () => {
|
||||
const { OcctKernel } = await import("occt-wasm");
|
||||
const profile = mergeProfiles(
|
||||
rectangle("left", 0, 0, 10, 10),
|
||||
rectangle("right", 20, 0, 10, 10),
|
||||
);
|
||||
const regions = cadSketchRegions(profile);
|
||||
expect(regions).toHaveLength(2);
|
||||
|
||||
const wasm = join(dirname(fileURLToPath(import.meta.resolve("occt-wasm"))), "occt-wasm.wasm");
|
||||
const kernel = await OcctKernel.init({ wasm });
|
||||
|
||||
const solids = regions.map((region) => {
|
||||
const edges = region.outer.steps.map(({ from, to }) =>
|
||||
kernel.makeLineEdge({ x: from.x, y: 0, z: from.z }, { x: to.x, y: 0, z: to.z }),
|
||||
);
|
||||
const wire = kernel.makeWire(edges);
|
||||
const face = kernel.makeFace(wire);
|
||||
return kernel.extrude(face, 0, 5, 0);
|
||||
});
|
||||
|
||||
const compound = kernel.makeCompound(solids);
|
||||
expect(kernel.isValid(compound)).toBe(true);
|
||||
|
||||
const mesh = kernel.tessellate(compound, { linearDeflection: 0.05, angularDeflection: 0.16 });
|
||||
expect(mesh.triangleCount).toBeGreaterThan(0);
|
||||
kernel.releaseAll();
|
||||
});
|
||||
|
||||
it("extrudes a profile with an island inside a hole", async () => {
|
||||
const { OcctKernel } = await import("occt-wasm");
|
||||
const profile = mergeProfiles(
|
||||
rectangle("outer", 0, 0, 40, 40),
|
||||
rectangle("hole", 5, 5, 30, 30),
|
||||
rectangle("island", 12, 12, 16, 16),
|
||||
);
|
||||
const regions = cadSketchRegions(profile);
|
||||
expect(regions).toHaveLength(2);
|
||||
|
||||
const outerRegion = regions.find((r) => r.outer.id.includes("outer"));
|
||||
const islandRegion = regions.find((r) => r.outer.id.includes("island"));
|
||||
expect(outerRegion).toBeDefined();
|
||||
expect(islandRegion).toBeDefined();
|
||||
expect(outerRegion!.holes).toHaveLength(1);
|
||||
expect(islandRegion!.holes).toHaveLength(0);
|
||||
|
||||
const wasm = join(dirname(fileURLToPath(import.meta.resolve("occt-wasm"))), "occt-wasm.wasm");
|
||||
const kernel = await OcctKernel.init({ wasm });
|
||||
|
||||
const buildSolid = (region: { outer: typeof regions[0]["outer"]; holes: typeof regions[0]["holes"] }) => {
|
||||
const outerEdges = region.outer.steps.map(({ from, to }) =>
|
||||
kernel.makeLineEdge({ x: from.x, y: 0, z: from.z }, { x: to.x, y: 0, z: to.z }),
|
||||
);
|
||||
let face = kernel.makeFace(kernel.makeWire(outerEdges));
|
||||
if (region.holes.length > 0) {
|
||||
const holeWires = region.holes.map((hole) => {
|
||||
const holeEdges = hole.steps.map(({ from, to }) =>
|
||||
kernel.makeLineEdge({ x: from.x, y: 0, z: from.z }, { x: to.x, y: 0, z: to.z }),
|
||||
);
|
||||
return kernel.makeWire(holeEdges);
|
||||
});
|
||||
face = kernel.addHolesInFace(face, holeWires);
|
||||
}
|
||||
return kernel.extrude(face, 0, 8, 0);
|
||||
};
|
||||
|
||||
const solids = regions.map(buildSolid);
|
||||
const compound = kernel.makeCompound(solids);
|
||||
expect(kernel.isValid(compound)).toBe(true);
|
||||
|
||||
const mesh = kernel.tessellate(compound, { linearDeflection: 0.05, angularDeflection: 0.16 });
|
||||
expect(mesh.triangleCount).toBeGreaterThan(0);
|
||||
kernel.releaseAll();
|
||||
});
|
||||
|
||||
it("rejects a profile with only open paths", () => {
|
||||
const openProfile: SketchProfile = {
|
||||
points: [
|
||||
{ id: "a-0", x: 0, z: 0 },
|
||||
{ id: "a-1", x: 10, z: 0 },
|
||||
{ id: "a-2", x: 10, z: 10 },
|
||||
],
|
||||
segments: [
|
||||
{ id: "a-s0", kind: "line", startId: "a-0", endId: "a-1" },
|
||||
{ id: "a-s1", kind: "line", startId: "a-1", endId: "a-2" },
|
||||
],
|
||||
};
|
||||
expect(() => cadSketchRegions(openProfile)).toThrow(/open/i);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { appUpdateIsAvailable, compareAppVersions } from "@/lib/appUpdates";
|
||||
|
||||
describe("application update versions", () => {
|
||||
it("orders semantic releases numerically", () => {
|
||||
expect(compareAppVersions("0.10.0", "0.9.9")).toBeGreaterThan(0);
|
||||
expect(compareAppVersions("1.0.0", "0.99.99")).toBeGreaterThan(0);
|
||||
expect(compareAppVersions("v1.0.0", "1.0.0")).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps prereleases below their stable release", () => {
|
||||
expect(compareAppVersions("1.0.0-beta.2", "1.0.0-beta.1")).toBeGreaterThan(0);
|
||||
expect(compareAppVersions("1.0.0", "1.0.0-rc.1")).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("only offers a strictly newer version", () => {
|
||||
expect(appUpdateIsAvailable("1.0.0", "1.0.1")).toBe(true);
|
||||
expect(appUpdateIsAvailable("1.0.0", "1.0.0")).toBe(false);
|
||||
expect(appUpdateIsAvailable("1.0.0", "0.9.9")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { CHALLENGE_TUTORIAL_IDS, isChallengeTutorialId } from "@/lib/challenges";
|
||||
|
||||
describe("challenge tutorial ids", () => {
|
||||
it("recognizes every supported challenge", () => {
|
||||
expect(CHALLENGE_TUTORIAL_IDS).toEqual(["key-tag", "nameplate"]);
|
||||
expect(CHALLENGE_TUTORIAL_IDS.every(isChallengeTutorialId)).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects stale or malformed stored values", () => {
|
||||
expect(isChallengeTutorialId("phone-stand")).toBe(false);
|
||||
expect(isChallengeTutorialId(null)).toBe(false);
|
||||
expect(isChallengeTutorialId({ tutorial: "nameplate" })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { sketchForgeToZUp, zUpToSketchForge } from "@/lib/meshCoordinates";
|
||||
|
||||
describe("mesh coordinate conventions", () => {
|
||||
it("maps slicer Z-up coordinates to SketchForge Y-up and back", () => {
|
||||
const slicerPoint: [number, number, number] = [12, 34, 56];
|
||||
const sketchForgePoint = zUpToSketchForge(slicerPoint);
|
||||
|
||||
expect(sketchForgePoint).toEqual([12, 56, -34]);
|
||||
expect(sketchForgeToZUp(sketchForgePoint)).toEqual(slicerPoint);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { exportMeshesToObj, type ObjExportMesh } from "@/lib/objExport";
|
||||
|
||||
function duplicatedTetrahedron(): ObjExportMesh {
|
||||
const a: [number, number, number] = [0, 0, 0];
|
||||
const b: [number, number, number] = [10, 0, 0];
|
||||
const c: [number, number, number] = [0, 10, 0];
|
||||
const d: [number, number, number] = [0, 0, 10];
|
||||
return {
|
||||
name: "closed_tetrahedron",
|
||||
vertices: [a, c, b, a, b, d, b, c, d, c, a, d],
|
||||
faces: [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]],
|
||||
};
|
||||
}
|
||||
|
||||
describe("OBJ export", () => {
|
||||
it("preserves OBJ's conventional Y-up coordinates", () => {
|
||||
const obj = exportMeshesToObj([duplicatedTetrahedron()]);
|
||||
const vertices = obj.split("\n").filter((line) => line.startsWith("v "));
|
||||
|
||||
expect(vertices).toContain("v 0 0 10");
|
||||
expect(vertices).toContain("v 0 10 0");
|
||||
});
|
||||
|
||||
it("welds coincident triangle vertices so a closed mesh has no boundary edges", () => {
|
||||
const obj = exportMeshesToObj([duplicatedTetrahedron()]);
|
||||
const vertices = obj.split("\n").filter((line) => line.startsWith("v "));
|
||||
const faces = obj.split("\n").filter((line) => line.startsWith("f "));
|
||||
const edgeUse = new Map<string, number>();
|
||||
|
||||
faces.forEach((line) => {
|
||||
const [a, b, c] = line.slice(2).trim().split(/\s+/).map(Number);
|
||||
[[a, b], [b, c], [c, a]].forEach(([start, end]) => {
|
||||
const key = start < end ? `${start}:${end}` : `${end}:${start}`;
|
||||
edgeUse.set(key, (edgeUse.get(key) ?? 0) + 1);
|
||||
});
|
||||
});
|
||||
|
||||
expect(vertices).toHaveLength(4);
|
||||
expect(faces).toHaveLength(4);
|
||||
expect([...edgeUse.values()].every((count) => count === 2)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { cadSketchRegions, orderedCadSketchPaths } from "@/lib/sketchCadProfile";
|
||||
import type { SketchPoint, SketchProfile, SketchSegment } from "@/types/sketchforge";
|
||||
|
||||
function rectangle(id: string, x: number, z: number, width: number, depth: number) {
|
||||
const points: SketchPoint[] = [
|
||||
{ id: `${id}-0`, x, z },
|
||||
{ id: `${id}-1`, x: x + width, z },
|
||||
{ id: `${id}-2`, x: x + width, z: z + depth },
|
||||
{ id: `${id}-3`, x, z: z + depth },
|
||||
];
|
||||
const segments: SketchSegment[] = points.map((point, index) => ({
|
||||
id: `${id}-s${index}`,
|
||||
kind: "line",
|
||||
startId: point.id,
|
||||
endId: points[(index + 1) % points.length].id,
|
||||
}));
|
||||
return { points, segments };
|
||||
}
|
||||
|
||||
function profile(...rectangles: ReturnType<typeof rectangle>[]): SketchProfile {
|
||||
return {
|
||||
points: rectangles.flatMap((rectangle) => rectangle.points),
|
||||
segments: rectangles.flatMap((rectangle) => rectangle.segments),
|
||||
};
|
||||
}
|
||||
|
||||
describe("OCCT sketch profile preparation", () => {
|
||||
it("orders a closed loop even when its segments arrive out of order", () => {
|
||||
const square = rectangle("outer", 0, 0, 20, 10);
|
||||
const paths = orderedCadSketchPaths({ ...profile(square), segments: [...square.segments].reverse() });
|
||||
expect(paths).toHaveLength(1);
|
||||
expect(paths[0].closed).toBe(true);
|
||||
expect(paths[0].steps).toHaveLength(4);
|
||||
});
|
||||
|
||||
it("assigns an enclosed loop as a hole", () => {
|
||||
const regions = cadSketchRegions(profile(
|
||||
rectangle("outer", 0, 0, 20, 20),
|
||||
rectangle("hole", 5, 5, 4, 4),
|
||||
));
|
||||
expect(regions).toHaveLength(1);
|
||||
expect(regions[0].outer.id).toContain("outer");
|
||||
expect(regions[0].holes).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("keeps disjoint loops as separate solids", () => {
|
||||
const regions = cadSketchRegions(profile(
|
||||
rectangle("left", 0, 0, 4, 4),
|
||||
rectangle("right", 10, 0, 4, 4),
|
||||
));
|
||||
expect(regions).toHaveLength(2);
|
||||
expect(regions.every((region) => region.holes.length === 0)).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects open paths with a clear error", () => {
|
||||
const square = rectangle("open", 0, 0, 10, 10);
|
||||
square.segments.pop();
|
||||
expect(() => cadSketchRegions(profile(square))).toThrow(/open/i);
|
||||
});
|
||||
|
||||
it("creates a solid island inside a hole (3-level nesting)", () => {
|
||||
const regions = cadSketchRegions(profile(
|
||||
rectangle("outer", 0, 0, 40, 40),
|
||||
rectangle("hole", 5, 5, 30, 30),
|
||||
rectangle("island", 12, 12, 16, 16),
|
||||
));
|
||||
expect(regions).toHaveLength(2);
|
||||
const outerRegion = regions.find((r) => r.outer.id.includes("outer"));
|
||||
const islandRegion = regions.find((r) => r.outer.id.includes("island"));
|
||||
expect(outerRegion).toBeDefined();
|
||||
expect(outerRegion!.holes).toHaveLength(1);
|
||||
expect(outerRegion!.holes[0].id).toContain("hole");
|
||||
expect(islandRegion).toBeDefined();
|
||||
expect(islandRegion!.holes).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("handles 4-level nesting (outer > hole > island > island-hole)", () => {
|
||||
const regions = cadSketchRegions(profile(
|
||||
rectangle("outer", 0, 0, 60, 60),
|
||||
rectangle("hole", 5, 5, 50, 50),
|
||||
rectangle("island", 15, 15, 30, 30),
|
||||
rectangle("ihole", 20, 20, 20, 20),
|
||||
));
|
||||
const outerRegion = regions.find((r) => r.outer.id.includes("outer"));
|
||||
const islandRegion = regions.find((r) => r.outer.id.includes("island"));
|
||||
expect(outerRegion).toBeDefined();
|
||||
expect(outerRegion!.holes).toHaveLength(1);
|
||||
expect(outerRegion!.holes[0].id).toContain("hole");
|
||||
expect(islandRegion).toBeDefined();
|
||||
expect(islandRegion!.holes).toHaveLength(1);
|
||||
expect(islandRegion!.holes[0].id).toContain("ihole");
|
||||
});
|
||||
|
||||
it("throws when all paths are open", () => {
|
||||
const open1 = rectangle("a", 0, 0, 10, 10);
|
||||
open1.segments.pop();
|
||||
const open2 = rectangle("b", 20, 0, 10, 10);
|
||||
open2.segments.pop();
|
||||
expect(() => cadSketchRegions(profile(open1, open2))).toThrow(/open/i);
|
||||
});
|
||||
|
||||
it("returns empty for a single degenerate zero-area path", () => {
|
||||
const degenerate: SketchProfile = {
|
||||
points: [
|
||||
{ id: "d-0", x: 0, z: 0 },
|
||||
{ id: "d-1", x: 1, z: 0 },
|
||||
{ id: "d-2", x: 0, z: 0 },
|
||||
],
|
||||
segments: [
|
||||
{ id: "d-s0", kind: "line", startId: "d-0", endId: "d-1" },
|
||||
{ id: "d-s1", kind: "line", startId: "d-1", endId: "d-2" },
|
||||
{ id: "d-s2", kind: "line", startId: "d-2", endId: "d-0" },
|
||||
],
|
||||
};
|
||||
expect(cadSketchRegions(degenerate)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { exportMeshesToStl } from "@/lib/stlExport";
|
||||
|
||||
describe("STL export orientation", () => {
|
||||
it("writes editor Y-up coordinates as slicer Z-up coordinates", () => {
|
||||
const stl = exportMeshesToStl([{
|
||||
vertices: [[0, 0, 0], [10, 0, 0], [0, 20, 5]],
|
||||
faces: [[0, 1, 2]],
|
||||
}]);
|
||||
|
||||
expect(stl).toContain("vertex 0 -5 20");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { importedShapeFromStl } from "@/lib/stlImport";
|
||||
|
||||
function boxStl(width: number, ySize: number, zSize: number, name = "box") {
|
||||
const vertices = [
|
||||
[0, 0, 0], [width, 0, 0], [width, ySize, 0], [0, ySize, 0],
|
||||
[0, 0, zSize], [width, 0, zSize], [width, ySize, zSize], [0, ySize, zSize],
|
||||
];
|
||||
const faces = [
|
||||
[0, 2, 1], [0, 3, 2], [4, 5, 6], [4, 6, 7],
|
||||
[0, 1, 5], [0, 5, 4], [1, 2, 6], [1, 6, 5],
|
||||
[2, 3, 7], [2, 7, 6], [3, 0, 4], [3, 4, 7],
|
||||
];
|
||||
const facets = faces.map(([a, b, c]) => `facet normal 0 0 0
|
||||
outer loop
|
||||
vertex ${vertices[a].join(" ")}
|
||||
vertex ${vertices[b].join(" ")}
|
||||
vertex ${vertices[c].join(" ")}
|
||||
endloop
|
||||
endfacet`).join("\n");
|
||||
const source = `solid ${name}\n${facets}\nendsolid ${name}`;
|
||||
return new TextEncoder().encode(source).buffer;
|
||||
}
|
||||
|
||||
describe("STL import orientation", () => {
|
||||
it("maps a clearly Z-up slicer model to SketchForge Y-up", () => {
|
||||
const shape = importedShapeFromStl("z-up-box.stl", boxStl(80, 60, 20));
|
||||
|
||||
expect(shape.importedMesh?.baseWidth).toBeCloseTo(80);
|
||||
expect(shape.importedMesh?.baseHeight).toBeCloseTo(20);
|
||||
expect(shape.importedMesh?.baseDepth).toBeCloseTo(60);
|
||||
});
|
||||
|
||||
it("preserves an unmistakably flat Y-up legacy model", () => {
|
||||
const shape = importedShapeFromStl("raspberry-pi-like.stl", boxStl(89, 20, 58));
|
||||
|
||||
expect(shape.importedMesh?.baseWidth).toBeCloseTo(89);
|
||||
expect(shape.importedMesh?.baseHeight).toBeCloseTo(20);
|
||||
expect(shape.importedMesh?.baseDepth).toBeCloseTo(58);
|
||||
});
|
||||
|
||||
it("preserves previous SketchForge STL exports regardless of proportions", () => {
|
||||
const shape = importedShapeFromStl("legacy-sketchforge.stl", boxStl(20, 80, 10, "sketchforge_design"));
|
||||
|
||||
expect(shape.importedMesh?.baseHeight).toBeCloseTo(80);
|
||||
expect(shape.importedMesh?.baseDepth).toBeCloseTo(10);
|
||||
});
|
||||
});
|
||||